Merge remote-tracking branch 'upstream/main' into feat/view-zoom-to-selection-5601

# Conflicts:
#	docs/ui-parity.md
This commit is contained in:
Don Omondi committed 2026-11-06 04:37:59 -05:00
commit 32744d4a61
56 files changed
+1521 -114

No files matched your search

+4
View File
@@ -209,3 +209,7 @@ sync_github_name = true
real_name = "Alexander Buraga"
display_name = "Alexander Buraga"
sync_github_name = false
[people.adikshan11]
real_name = "Adithya Shankaran"
sync_github_name = true
+7 -1
View File
@@ -307,7 +307,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}),
),
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
r("blur.gaussian", "Gaussian Blur…", BLUR, "{radius: pt (5)}", json!({"radius": 5.0})),
r(
"blur.gaussian",
"Gaussian Blur…",
BLUR,
"{radius: pt (5), linear?: bool (false; blurs the colours in linear light, as an SVG filter with color-interpolation-filters=\"linearRGB\" does)}",
json!({"radius": 5.0}),
),
r(
"artistic.coloredPencil",
"Colored Pencil…",
+41
View File
@@ -1079,6 +1079,47 @@ pub fn gaussian_rgba(data: &mut [u8], w: usize, h: usize, sigma: f64) {
}
}
/// [`gaussian_rgba`] with the colours mixed in linear light: decoded from sRGB before the blur
/// and encoded again after it (Filter Effects 1 §16, `color-interpolation-filters: linearRGB`,
/// <https://www.w3.org/TR/filter-effects-1/#ColorInterpolationFiltersProperty>). The blur runs on
/// 16-bit values, so dark linear tones keep their steps.
pub fn gaussian_rgba_linear(data: &mut [u8], w: usize, h: usize, sigma: f64) {
use vectorcraft_doc::color::cms::lab::{linear_to_srgb, srgb_to_linear};
if let Some(px) = pixels(data, w, h)
&& sigma >= 0.2
{
// Each colour is unpremultiplied, decoded (by table) and premultiplied again.
let decode: Vec<f32> = (0..=255u8).map(|v| srgb_to_linear(f32::from(v) / 255.0)).collect();
let mut wide: Vec<Px16> = px
.iter()
.map(|p| {
let a = f32::from(p[3]) / 255.0;
let lin = |v: u8| {
if p[3] == 0 {
return 0;
}
let straight = (f32::from(v) / f32::from(p[3]) * 255.0).round().clamp(0.0, 255.0) as usize;
(decode.get(straight).copied().unwrap_or(0.0) * a * 65535.0).round().clamp(0.0, 65535.0) as u16
};
[lin(p[0]), lin(p[1]), lin(p[2]), u16::from(p[3]) * 257]
})
.collect();
gaussian(&mut wide, w, sigma);
for (p, q) in px.iter_mut().zip(&wide) {
let a = to8(q[3]);
let alpha = f32::from(q[3]) / 65535.0;
let enc = |v: u16| {
if alpha <= 0.0 {
return 0;
}
let straight = (f32::from(v) / 65535.0 / alpha).clamp(0.0, 1.0);
(linear_to_srgb(straight) * f32::from(a)).round().clamp(0.0, f32::from(a)) as u8
};
*p = [enc(q[0]), enc(q[1]), enc(q[2]), a];
}
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
+22
View File
@@ -887,6 +887,28 @@ fn gaussian_and_plane_blurs_keep_their_mass() {
assert!((plane.iter().sum::<f32>() - 100.0).abs() < 0.5 && plane[15 * w + 13] > 0.0 && plane[13 * w + 15] > 0.0);
}
/// Blurred in linear light, black beside white meets at about 188/255 (half the light, encoded),
/// where the plain blur meets at about 128; flat areas and alpha stay as they are (#5877).
#[test]
fn linear_light_blur_mixes_light_not_values() {
// Large enough that the transparency past the edges doesn't reach the middle.
let (w, h) = (120, 60);
let src = image(w, h, |x, _| if x < 60 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
let (mut plain, mut linear) = (src.clone(), src.clone());
gaussian_rgba(&mut plain, w, h, 3.0);
gaussian_rgba_linear(&mut linear, w, h, 3.0);
let mid = |d: &[u8]| (f32::from(at(d, w, 59, 30)[0]) + f32::from(at(d, w, 60, 30)[0])) / 2.0;
assert!((mid(&plain) - 128.0).abs() < 6.0, "{}", mid(&plain));
assert!((mid(&linear) - 188.0).abs() < 6.0, "{}", mid(&linear));
assert_eq!((at(&linear, w, 30, 30), at(&linear, w, 90, 30)), ([0, 0, 0, 255], [255, 255, 255, 255]));
// Premultiplied input: a half-transparent white square blurs to white at any alpha.
let mut soft = image(30, 30, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [128, 128, 128, 128] } else { [0, 0, 0, 0] });
gaussian_rgba_linear(&mut soft, 30, 30, 2.0);
for p in soft.as_chunks::<4>().0 {
assert!(p[0] <= p[3] && p[3] <= 128 && (p[3] < 8 || p[0] + 2 >= p[3]), "{p:?}");
}
}
/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored
/// --nocapture pixel_timings`).
#[test]
+5 -3
View File
@@ -48,9 +48,11 @@ pub enum RasterFx {
Feather {
radius: f64,
},
/// Blur the whole object (σ = radius / 2).
/// Blur the whole object (σ = radius / 2): its colours mixed as they are, or in linear light
/// (`linear`, as an SVG filter asks with `color-interpolation-filters="linearRGB"`).
GaussianBlur {
radius: f64,
linear: bool,
},
/// A Photoshop-style filter over the object's pixels (Radial Blur, Unsharp Mask…).
Pixel(PixelFx),
@@ -77,7 +79,7 @@ impl RasterFx {
RasterFx::DropShadow { dx, dy, blur, .. } => dx.abs().max(dy.abs()) + 1.5 * blur,
RasterFx::OuterGlow { blur, .. } => 1.5 * blur,
RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => 0.0,
RasterFx::GaussianBlur { radius } => 1.5 * radius,
RasterFx::GaussianBlur { radius, .. } => 1.5 * radius,
RasterFx::Pixel(p) => p.outset(bounds),
RasterFx::Rasterize(r) => r.outset(),
}
@@ -416,7 +418,7 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
center: text(&p, "source", "edge").eq_ignore_ascii_case("center"),
},
"stylize.feather" => RasterFx::Feather { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) },
"blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) },
"blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0), linear: flag(&p, "linear", false) },
RASTERIZE => RasterFx::Rasterize(Rasterize::parse(&p)),
id => RasterFx::Pixel(pixel::parse(id, &p)?),
})
+1 -1
View File
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Attributes",
[],
None,
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG export links the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
has_doc,
set
),
+8 -5
View File
@@ -20,7 +20,9 @@
//! pixels, or opacity or a blending mode on the image, the fill, the shape or a group it is in) is
//! expanded into its tiles first so its images flatten too. With `omit` the images with
//! see-through pixels, opacity or a blending mode of their own are left out, and pattern fills stay
//! as the writer draws them (their tiles opaque over white). An image that can't be decoded is
//! as the writer draws them (their tiles opaque over white). A colorized image is flattened or
//! left out the same way, unless its pixels are all black or white: the writer writes that one as
//! a 1-bit image mask in its color, which keeps its white pixels clear. An image that can't be decoded is
//! missing from the images that flattening and expanding raster effects draw, and the warnings
//! then carry the raster exports' note once.
//!
@@ -179,8 +181,10 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> {
}
/// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as
/// [`Document::walk`] counts). These have see-through pixels or a colorize paint, or have opacity
/// or a blending mode of their own or, with `flatten`, of a group they are in.
/// [`Document::walk`] counts). These have see-through pixels or a colorize paint (except the
/// colorized images the writer writes as image masks, clear pixels included,
/// [`vectorcraft_eps::writes_image_mask`]), or
/// have opacity or a blending mode of their own or, with `flatten`, of a group they are in.
/// With `flatten` only visible images are returned, because a hidden one (which the hidden objects
/// option may write) is written over white. With `omit` all of them are returned.
fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
@@ -189,8 +193,7 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
let mut at = 0;
d.walk(|n| {
if let NodeKind::Image(im) = &n.kind
&& (keys.contains(&im.key)
|| n.extras().colorize.is_some()
&& (((keys.contains(&im.key) || n.extras().colorize.is_some()) && !vectorcraft_eps::writes_image_mask(d, n))
|| n.opacity < 1.0
|| n.blend != BlendMode::Normal
|| (mode == SeeThrough::Flatten && transparent(d, n.id)))
+1 -1
View File
@@ -121,7 +121,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
name: "transparentImages",
ty: "string",
default: "\"flatten\"",
description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity or a blending mode): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)",
description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity, a blending mode, or a colorize color unless every pixel is black or white): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)",
},
FormatOption {
name: "hiddenObjects",
+2 -1
View File
@@ -205,7 +205,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
};
let independent = switch_or(p, "independent", false, C)?;
let with = spine_points_param(p, C)?;
if handle.is_some() && !with.is_empty() {
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "`with` moves points, not a handle"));
}
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
+93
View File
@@ -24,6 +24,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
stroke_set
),
cmd!(
"stroke.weightUp",
"Stroke Weight Up",
[],
Some("Cmd+Alt+."),
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn → {objects}",
has_doc,
|s, p| stroke_step(s, p, true)
),
cmd!(
"stroke.weightDown",
"Stroke Weight Down",
[],
Some("Cmd+Alt+,"),
"{ids?|id?} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}",
has_doc,
|s, p| stroke_step(s, p, false)
),
cmd!(
"stroke.setAdvanced",
"Stroke Options",
@@ -261,6 +279,61 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
}
/// `w` (pt) one step up or down in `unit` (Units › Stroke): a quarter unit up to one unit,
/// whole units above it, from 0.25 unit to 1000 pt. A weight between steps goes to the next step
/// in that direction (0.6 pt up is 0.75 pt); a weight below a quarter unit doesn't go down.
pub(crate) fn step_weight(w: f64, unit: Unit, up: bool) -> f64 {
const EPS: f64 = 1e-9;
let k = Some(unit.to_pt(1.0)).filter(|k| k.is_finite() && *k > 0.0).unwrap_or(1.0);
let w = if w.is_finite() { w.max(0.0) } else { 0.0 };
let v = w / k;
let next = if up {
if v < 1.0 - EPS { ((v * 4.0 + EPS).floor() + 1.0) / 4.0 } else { (v + EPS).floor() + 1.0 }
} else if v <= 1.0 + EPS {
(((v * 4.0 - EPS).ceil() - 1.0) / 4.0).max(0.25)
} else {
(v - EPS).ceil() - 1.0
};
let r = (next * k).min(1000.0);
// Never a step the wrong way: past 1000 pt up stays, below a quarter unit down stays.
if up { r.max(w) } else { r.min(w) }
}
/// `stroke.weightUp` / `stroke.weightDown`: each target stroke stepped from its own weight.
fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
let c = if up { "stroke.weightUp" } else { "stroke.weightDown" };
let unit = s.stroke_unit();
let item = item_target(s, p, c)?.of_kind(s, false);
let ids = item.targets(s, p)?;
if no_targets(&ids, p) {
let w = step_weight(s.paint.stroke_width, unit, up);
s.paint.stroke_width = w;
if let Some(st) = s.new_art_stroke_mut() {
st.width = w;
}
return Ok(json!({"objects": 0}));
}
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
edit_items(s, &ids, item, c, label, false, |n, index| {
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
{
// Character strokes are drawn in text space, scaled by the type's transform.
let k = Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0);
for r in t.runs.iter_mut().filter(|r| !matches!(r.style.stroke, Paint::None)) {
let change = StrokeChange { weight: Some(step_weight(r.style.stroke_width * k, unit, up)), ..StrokeChange::default() };
change.apply_char_scaled(&mut r.style, k);
}
return Ok(());
}
if let Some(st) = n.appearance.stroke_at_mut(index) {
st.width = step_weight(st.width, unit, up);
}
Ok(())
})?;
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
}
impl Session {
/// Units > Stroke (Preferences): the unit stroke weights and dash lengths show in.
pub fn stroke_unit(&self) -> Unit {
@@ -514,3 +587,23 @@ fn profile_list(s: &mut Session, _: &Value) -> Result<Value> {
let current = s.shown_stroke().map(|st| s.profile_entry(st.profile.as_ref()).map_or("custom", |e| e.id).to_string());
Ok(json!({ "profiles": profiles, "current": current }))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn weight_steps_follow_units_and_stop_at_their_bounds() {
assert_eq!(step_weight(0.6, Unit::Points, true), 0.75);
assert_eq!(step_weight(0.6, Unit::Points, false), 0.5);
assert_eq!(step_weight(2.5, Unit::Points, true), 3.0);
assert_eq!(step_weight(2.5, Unit::Points, false), 2.0);
assert_eq!(step_weight(0.1, Unit::Points, false), 0.1, "below a quarter point a step down keeps it");
assert_eq!(step_weight(1000.0, Unit::Points, true), 1000.0);
assert_eq!(step_weight(2000.0, Unit::Points, true), 2000.0, "a step up never lowers a weight");
assert_eq!(step_weight(f64::NAN, Unit::Points, true), 0.25);
let mm = Unit::Millimeters.to_pt(1.0);
assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9);
assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9);
}
}
+27 -4
View File
@@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Tab Stops",
["Window", "Tabs"],
None,
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches)",
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); supplied align, leader and alignOn must be strings, and alignOn cannot be empty",
has_selection,
set
),
@@ -44,15 +44,31 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
if !(0.0..=100_000.0).contains(&position) {
return Err(bad(C, "positions must be between 0 and 100000 pt"));
}
let align = match s.get("align").and_then(Value::as_str).unwrap_or("left").to_ascii_lowercase().as_str() {
let align = match s.get("align") {
None | Some(Value::Null) => "left",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(C, "`align` must be a string")),
};
let align = match align.to_ascii_lowercase().as_str() {
"left" => TabAlign::Left,
"center" | "centre" => TabAlign::Center,
"right" => TabAlign::Right,
"decimal" => TabAlign::Decimal,
other => return Err(bad(C, format!("unknown align `{other}`"))),
};
let leader = s.get("leader").and_then(Value::as_str).unwrap_or("").chars().take(8).collect();
let align_on = s.get("alignOn").and_then(Value::as_str).and_then(|a| a.chars().next()).unwrap_or('.');
let leader = match s.get("leader") {
None | Some(Value::Null) => "",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(C, "`leader` must be a string")),
}
.chars()
.take(8)
.collect();
let align_on = match s.get("alignOn") {
None | Some(Value::Null) => '.',
Some(Value::String(value)) => value.chars().next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?,
Some(_) => return Err(bad(C, "`alignOn` must be a string")),
};
stops.push(TabStop { position, align, leader, align_on });
}
stops.sort_by(|a, b| a.position.total_cmp(&b.position));
@@ -116,6 +132,13 @@ mod tests {
use crate::Session;
#[test]
fn supplied_tab_stop_fields_require_strings() {
for stop in [json!({"position": 40, "align": false}), json!({"position": 40, "leader": 1}), json!({"position": 40, "alignOn": ""})] {
assert!(super::parse_stops(&json!({"stops": [stop.clone()]})).is_err(), "accepted {stop}");
}
}
#[test]
fn set_get_clear_tabs() {
let mut s = Session::new();
+21
View File
@@ -39,6 +39,27 @@ fn empty_later_frames_keep_the_first_frames_edited_paragraph_style() {
assert_eq!([hyphenates(a), hyphenates(b), hyphenates(c)], [true, true, true]);
}
#[test]
fn a_restyled_empty_frame_keeps_its_style_before_an_unedited_empty_frame() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "First\n", "area": {"width": 150, "height": 60}})).unwrap()["id"]
.as_u64()
.unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
let c = s.execute("shape.rectangle", &json!({"x": 400, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
assert_eq!([text(&s, a), text(&s, b), text(&s, c)], ["First\n", "", ""]);
s.execute("text.setFormat", &json!({"ids": [b], "hyphenate": true})).unwrap();
let hyphenates = |id, para| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.para_at(para).hyphenate,
_ => panic!("not text"),
};
// The empty paragraph after the break takes the style; the paragraph "First" keeps its own.
assert_eq!([hyphenates(a, 0), hyphenates(a, 1), hyphenates(b, 0), hyphenates(c, 0)], [false, true, true, true]);
}
#[test]
fn thread_flows_reflows_on_edit_and_survives_delete() {
let (mut s, a, b) = setup();
+9 -6
View File
@@ -11,7 +11,7 @@
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
//! is a link that leads nowhere).
//! - The result must lie inside one of the roots of its kind, compared by whole components
//! (`/work2` isn't inside `/work`), without regard to case on Windows.
//! (`/work2` isn't inside `/work`), exactly apart from the case of a Windows drive or share prefix.
//! - Read and write access are separate: a root given alone grants only its own kind of access.
//!
//! Roots are in force on a thread inside [`confine`], and in the whole process after
@@ -260,7 +260,7 @@ fn resolve(path: &str) -> Result<PathBuf, String> {
}
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case in a
/// Windows drive prefix only: resolved folder names have their real case, and a folder that differs
/// Windows drive or share prefix only: resolved folder names have their real case, and a folder that differs
/// in case alone may be another, on a case-sensitive Windows folder)?
fn inside(path: &Path, root: &Path) -> bool {
let mut path = path.components();
@@ -280,10 +280,11 @@ fn same_component(a: Component, b: Component) -> bool {
}
}
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension), which names no file.
pub(crate) fn is_device_name(component: &str) -> bool {
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
let numbered =
|prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"));
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
}
@@ -499,6 +500,8 @@ mod tests {
let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err();
assert!(e.contains("reserved device names"), "{e}");
assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err());
let e = roots.check(&s(base.join("out/COM¹.txt")), Access::Write).unwrap_err();
assert!(e.contains("reserved device names"), "{e}");
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
let _ = std::fs::remove_dir_all(base);
}
@@ -527,10 +530,10 @@ mod tests {
#[test]
fn device_names() {
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL "] {
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL ", "COM¹", "Lpt²", "lpt³.txt"] {
assert!(is_device_name(d), "{d}");
}
for f in ["console", "com10", "COM0", "lpt", "a.svg", "nul-x"] {
for f in ["console", "com10", "COM0", "lpt", "a.svg", "nul-x", "COM⁴", "com¹0", "lpt¹x"] {
assert!(!is_device_name(f), "{f}");
}
}
+1
View File
@@ -76,6 +76,7 @@ fn spine_points_move_together() {
let before = spec(&s, g);
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [9]})).is_err());
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [2], "handle": "in"})).is_err());
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [], "handle": "in"})).is_err());
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": "2"})).is_err());
assert_eq!(spec(&s, g), before, "refused requests change nothing");
s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [2, 1]})).unwrap();
+9 -1
View File
@@ -370,13 +370,21 @@ fn colorized_gray_image_is_flattened_for_pdf_x_1a() {
assert!(!String::from_utf8_lossy(&bytes).contains("/SMask"), "PDF/X-1a has no soft mask");
}
/// A colorized image with a gray pixel is left out; one of black and white pixels is written as an
/// image mask and kept.
#[test]
fn colorized_gray_image_is_omitted_from_legacy_ai_when_requested() {
let mut s = session();
let mid = png(image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 128]).unwrap()));
let id = image(&mut s, "mid", mid);
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap();
let out = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": "omit"})).unwrap();
assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]);
let mut s = session();
let id = image(&mut s, "gray", gray(false));
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap();
let out = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": "omit"})).unwrap();
assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]);
assert!(!out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]);
}
#[test]
+96 -1
View File
@@ -447,6 +447,100 @@ fn transparent_images_can_be_left_out_and_opacity_makes_one_transparent() {
assert_eq!(v["options"]["transparentImages"]["value"], "flatten", "{v}");
}
/// A red square (10–50 × 10–50) half under a 4 × 2 black-and-white image (30–70 × 10–30) that the
/// spot color `Ink` colorizes. Returns the session and the image's pixels.
fn colorized_bitmap_over_square() -> (Session, Vec<u8>) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let gray = vec![0, 255, 0, 255, 255, 0, 255, 0];
let mut bytes = vec![];
image::GrayImage::from_raw(4, 2, gray.clone()).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let p = json!({"name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 40, 20]});
s.execute("file.place", &p).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
(s, gray)
}
/// An image's pixels' coverage and its colorize paint.
type Colorized = (Option<(u32, u32, Vec<u8>)>, Option<vectorcraft_color::Paint>);
/// The colorized image of each image node of `d`, with its pixels' coverage.
fn colorized(d: &vectorcraft_doc::Document) -> Vec<Colorized> {
let mut out = vec![];
d.walk(|n| {
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
out.push((d.image_blob(im).and_then(vectorcraft_doc::ImageBlob::coverage), n.extras().colorize.as_deref().cloned()));
}
});
out
}
/// A colorized image of black and white pixels is neither flattened nor left out: it is written as
/// a 1-bit image mask in its color, with either setting of `transparentImages`, and opens again
/// colorized with that color, its white pixels clear over the square, and the square as it was.
#[test]
fn a_colorized_black_and_white_image_is_written_as_an_image_mask() {
let (mut s, gray) = colorized_bitmap_over_square();
let before = colorized(&s.doc().unwrap().doc);
let want: Vec<u8> = gray.iter().map(|v| 255 - v).collect();
assert!(matches!(before.as_slice(), [(Some((4, 2, c)), Some(_))] if *c == want), "{before:?}");
for mode in ["flatten", "omit"] {
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": mode})).unwrap();
assert!(!warnings(&r).iter().any(|w| w.contains("transparent images") || w.contains("flattened")), "{mode}: {r}");
let mut t = Session::new();
t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap();
let d = &t.doc().unwrap().doc;
let after = colorized(d);
assert_eq!(after.len(), 1, "{mode}: {after:?}");
assert_eq!(after[0].0, before[0].0, "{mode}");
let (Some(a), Some(b)) = (&after[0].1, &before[0].1) else { panic!("{mode}: {after:?}") };
let rgb = |p: &vectorcraft_color::Paint| p.color().map(|c| c.to_rgb()).unwrap();
assert!(rgb(a).iter().zip(rgb(b)).all(|(x, y)| (x - y).abs() < 0.01), "{mode}: {a:?} {b:?}");
assert_eq!(images(d), (1, 0), "{mode}");
// The first row draws as before: black (the color) and white (clear) over the square, then
// black and white (clear) over the page.
let src = &s.doc().unwrap().doc;
for x in [35.0, 45.0, 55.0, 65.0] {
let (now, was) = (colour_at(d, x, 15.0), colour_at(src, x, 15.0));
assert!(now.iter().zip(was).all(|(a, b)| a.abs_diff(b) <= 3), "{mode} at {x}: {now:?} {was:?}");
}
assert_ne!(colour_at(src, 35.0, 15.0), colour_at(src, 45.0, 15.0), "{mode}");
assert_ne!(colour_at(src, 55.0, 15.0), colour_at(src, 65.0, 15.0), "{mode}");
}
}
/// A colorized image of black and clear pixels is written as an image mask too, its clear pixels
/// clear, instead of being flattened or left out for its see-through pixels.
#[test]
fn a_colorized_image_of_black_and_clear_pixels_is_written_as_an_image_mask() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
let mut bytes = vec![];
image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0])
.unwrap()
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
let p = json!({"name": "c.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 20, 10]});
s.execute("file.place", &p).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
let before = colorized(&s.doc().unwrap().doc);
assert!(matches!(before.as_slice(), [(Some((2, 1, c)), Some(_))] if *c == [255, 0]), "{before:?}");
for mode in ["flatten", "omit"] {
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": mode})).unwrap();
assert!(!warnings(&r).iter().any(|w| w.contains("transparent images") || w.contains("flattened")), "{mode}: {r}");
let mut t = Session::new();
t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap();
let after = colorized(&t.doc().unwrap().doc);
assert_eq!(after.len(), 1, "{mode}: {after:?}");
assert_eq!(after[0].0, before[0].0, "{mode}");
assert!(after[0].1.is_some(), "{mode}: {after:?}");
}
}
/// #2692's file, an image clipped to a circle inside a circle's stroke, and #2830's, an image with
/// see-through pixels (which the save flattens into an image inside a clipping group), each with
/// an orange square on the next layer.
@@ -639,7 +733,8 @@ fn colorized_grayscale_image_pattern_keeps_its_colors_in_legacy_ai() {
for (a, b) in before.iter().zip(&after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 3), "before {before:?} after {after:?}");
}
assert!(saved_warnings.iter().any(|w| w.contains("flattened with the art under them")), "{saved_warnings:?}");
// The tile's pixels are black or white: its images are written as image masks, not flattened.
assert!(!saved_warnings.iter().any(|w| w.contains("flattened with the art under them")), "{saved_warnings:?}");
}
/// #3666: a pattern fill whose tile is an image, under opacity, is flattened with the art under it
+1 -1
View File
@@ -126,7 +126,7 @@ fn effect_params_are_the_effects_own() {
check_effect_params("effect.apply", e.id, &e.defaults).unwrap_or_else(|why| panic!("{}'s defaults: {why}", e.id));
}
let apply = |effect: &str, params| json!({"effect": effect, "params": params});
assert_eq!(refusal("effect.apply", apply("blur.gaussian", json!({"blurr": 3}))), "unknown parameter `blurr`; the command takes: radius");
assert_eq!(refusal("effect.apply", apply("blur.gaussian", json!({"blurr": 3}))), "unknown parameter `blurr`; the command takes: radius, linear");
assert_eq!(
refusal("appearance.addEffect", apply("stylize.dropShadow", json!({"opacty": 50}))),
"unknown parameter `opacty`; did you mean `opacity`?"
+46
View File
@@ -111,3 +111,49 @@ fn inspect_reports_stroke_options() {
let text = doc["layers"][0]["children"].as_array().unwrap().iter().find(|c| c["kind"] == "Text" || c.get("text").is_some()).unwrap().clone();
assert_eq!(text["strokeOptions"]["join"], "round", "{text}");
}
/// Stroke Weight Up and Down (Cmd/Ctrl+Alt+. and ,) step each selected stroke from its own
/// weight, a quarter point at a time below 1 pt and whole points above, in one undo step each.
#[test]
fn stroke_weight_up_and_down_step_each_selected_stroke() {
let mut s = session();
let (a, b, bare) = (rect(&mut s, 10.0), rect(&mut s, 60.0), rect(&mut s, 110.0));
select(&mut s, &[a]);
run(&mut s, "stroke.set", json!({"weight": 0.6}));
select(&mut s, &[b]);
run(&mut s, "stroke.set", json!({"weight": 3}));
select(&mut s, &[bare]);
run(&mut s, "paint.setStroke", json!({"none": true}));
let has_stroke = |s: &Session| {
s.doc().unwrap().doc.node(bare).unwrap().appearance.stroke().is_some_and(|st| !matches!(st.paint, vectorcraft_color::Paint::None))
};
let bare_before = has_stroke(&s);
let w = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
select(&mut s, &[a, b, bare]);
run(&mut s, "stroke.weightUp", json!({}));
assert_eq!((w(&s, a), w(&s, b)), (0.75, 4.0));
run(&mut s, "stroke.weightUp", json!({}));
assert_eq!((w(&s, a), w(&s, b)), (1.0, 5.0));
assert_eq!(has_stroke(&s), bare_before, "an object without a stroke takes none");
for _ in 0..6 {
run(&mut s, "stroke.weightDown", json!({}));
}
// 1 → 0.75 → 0.5 → 0.25, where it stays; 5 → 4 → 3 → 2 → 1 → 0.75 → 0.5.
assert_eq!((w(&s, a), w(&s, b)), (0.25, 0.5));
run(&mut s, "edit.undo", json!({}));
assert_eq!((w(&s, a), w(&s, b)), (0.25, 0.75), "one undo step per press");
}
/// With nothing selected the next object drawn takes the stepped weight.
#[test]
fn stroke_weight_up_with_nothing_selected_sets_up_new_art() {
let mut s = session();
run(&mut s, "select.none", json!({}));
run(&mut s, "stroke.set", json!({"weight": 2}));
run(&mut s, "stroke.weightUp", json!({}));
assert_eq!(s.paint.stroke_width, 3.0);
let r = rect(&mut s, 10.0);
assert_eq!(s.doc().unwrap().doc.node(r).unwrap().appearance.stroke_width(), 3.0);
assert_eq!(crate::cmd::find_command("stroke.weightUp").unwrap().shortcut, Some("Cmd+Alt+."));
assert_eq!(crate::cmd::find_command("stroke.weightDown").unwrap().shortcut, Some("Cmd+Alt+,"));
}
+11 -3
View File
@@ -769,9 +769,17 @@ fn a_pattern_library_adds_only_the_picked_pattern_and_it_undoes_and_saves() {
#[test]
fn a_library_file_name_is_never_a_windows_device_name() {
use crate::cmd::swatchlib::library_file_name;
for (title, ext) in
[("CON", "json"), ("nul", "json"), ("Com1", "acb"), ("LPT9", "ase"), ("aux.", "json"), ("CON.txt", "json"), ("nul.tar.gz", "acb")]
{
for (title, ext) in [
("CON", "json"),
("nul", "json"),
("Com1", "acb"),
("LPT9", "ase"),
("aux.", "json"),
("CON.txt", "json"),
("nul.tar.gz", "acb"),
("COM¹", "json"),
("lpt³.x", "ase"),
] {
let file = library_file_name(title, ext);
assert!(!crate::file_access::is_device_name(&file), "{title}: {file}");
assert!(
+107 -30
View File
@@ -22,6 +22,19 @@ fn ruler_unit(v: u8) -> Option<Unit> {
})
}
/// `base`, or the first of "base 2", "base 3"… not in `taken`, as [`Document::free_swatch_name`]
/// gives it when `taken` holds the document's swatch and colour group names; `taken` takes the
/// name returned.
fn free_swatch_name(taken: &mut std::collections::HashSet<String>, base: &str) -> String {
let name = if taken.contains(base) {
(2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n)).unwrap_or_else(|| base.to_string())
} else {
base.to_string()
};
taken.insert(name.clone());
name
}
/// An artboard of the `/Document`'s `ArtboardArray`: its name, its rect in art space and its
/// display options.
#[derive(Clone, Debug)]
@@ -820,6 +833,86 @@ impl<'a> Reader<'a> {
Some((swatches, groups))
}
/// The swatches of the file's named colors and patterns, added to `doc`'s, and the new name of
/// each color that took a numbered one.
///
/// The colour operators' definitions come first: a gradient, defined before the art, names a
/// global process colour as a stop and would otherwise make it an ink (#1771). The header's
/// custom colors follow. The first definition of a name makes its swatch, and takes the place
/// of a default swatch of that name when the file has no palette of its own (`own_palette`; a
/// reserved name in brackets, such as `[None]`, keeps its swatch). Then each pattern gets a
/// swatch. A color whose name a gradient or pattern swatch of the palette has, and a pattern
/// whose name another swatch has, take the first free "Name 2", "Name 3"…
/// ([`Document::free_swatch_name`]) once the other colors and the patterns have their swatches;
/// a pattern a swatch already paints with gets no other.
fn file_swatches(&self, doc: &mut Document, own_palette: bool) -> HashMap<String, String> {
let mut defined = std::collections::HashSet::new();
let mut clashes = vec![];
// The swatch names there are, looked up rather than scanned for each name a file defines
// (`Document::swatch` also knows the registration colour).
let mut have: std::collections::HashSet<String> = doc.swatches_iter().map(|s| s.name.clone()).collect();
have.insert(vectorcraft_color::swatch::REGISTRATION.to_string());
// The names a swatch of another kind than a gradient or pattern has.
let mut solid: std::collections::HashSet<String> =
doc.swatches_iter().filter(|s| !matches!(s.paint, Paint::Gradient(_) | Paint::Pattern { .. })).map(|s| s.name.clone()).collect();
let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true)));
for (n, spot) in colors {
let first = defined.insert(n.name.clone());
let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot };
let reserved = n.name.starts_with('[') && n.name.ends_with(']');
if have.insert(n.name.clone()) {
solid.insert(n.name.clone());
doc.swatches.push(swatch);
} else if first && !reserved {
if !own_palette && let Some(default) = doc.swatch_mut(&n.name) {
*default = swatch;
solid.insert(n.name.clone());
} else if !solid.contains(&n.name) {
clashes.push(swatch);
}
}
}
let mut unnamed = vec![];
for pattern in doc.patterns.iter().map(|p| p.name.clone()).collect::<Vec<_>>() {
if have.insert(pattern.clone()) {
doc.swatches.push(Swatch {
paint: Paint::Pattern { pattern: pattern.clone(), xf: Affine::IDENTITY },
name: pattern,
global: false,
spot: false,
});
} else {
unnamed.push(pattern);
}
}
// Every color and pattern name now has a swatch, so a numbered name takes none of them. The
// names taken and the patterns painted with are looked up rather than scanned for each one.
let mut taken: std::collections::HashSet<String> = doc.swatches_iter().map(|s| s.name.clone()).collect();
taken.extend(doc.swatch_groups.iter().map(|g| g.name.clone()));
taken.insert(vectorcraft_color::swatch::REGISTRATION.to_string());
let mut painted: std::collections::HashSet<String> = doc
.swatches_iter()
.filter_map(|s| match &s.paint {
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
_ => None,
})
.collect();
let mut renamed = HashMap::new();
for swatch in clashes {
let name = free_swatch_name(&mut taken, &swatch.name);
renamed.insert(swatch.name.clone(), name.clone());
doc.swatches.push(Swatch { name, ..swatch });
}
for pattern in unnamed {
if !painted.insert(pattern.clone()) {
continue;
}
let name = free_swatch_name(&mut taken, &pattern);
doc.swatches.push(Swatch { paint: Paint::Pattern { pattern, xf: Affine::IDENTITY }, name, global: false, spot: false });
}
renamed
}
/// The brushes read ([`brush::finish_brushes`]) and how many weren't; `None` when the file has
/// no brush objects (the document keeps the default brushes).
fn brush_library(&mut self) -> Option<(Vec<vectorcraft_brush::Brush>, usize)> {
@@ -957,39 +1050,11 @@ impl<'a> Reader<'a> {
}
None => false,
};
// The colour operators' definitions first: a gradient, defined before the art, names a
// global process colour as a stop and would otherwise make it an ink (#1771). The header's
// custom colors follow. The first definition of a name makes its swatch, and takes the place
// of a default swatch of that name when the file has no palette of its own (a reserved name
// in brackets, such as `[None]`, keeps its swatch).
let mut defined = std::collections::HashSet::new();
// The swatch names there are, looked up rather than scanned for each name a file defines
// (`Document::swatch` also knows the registration colour).
let mut have: std::collections::HashSet<String> = doc.swatches_iter().map(|s| s.name.clone()).collect();
have.insert(vectorcraft_color::swatch::REGISTRATION.to_string());
let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true)));
for (n, spot) in colors {
let first = defined.insert(n.name.clone());
let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot };
if have.insert(n.name.clone()) {
doc.swatches.push(swatch);
} else if first
&& !own_palette
&& !(n.name.starts_with('[') && n.name.ends_with(']'))
&& let Some(default) = doc.swatch_mut(&n.name)
{
*default = swatch;
}
}
let renamed = self.file_swatches(&mut doc, own_palette);
if let Some(author) = self.author.take() {
doc.metadata.author = author;
}
for name in doc.patterns.iter().map(|p| p.name.clone()).collect::<Vec<_>>() {
if have.insert(name.clone()) {
doc.swatches.push(Swatch { paint: Paint::Pattern { pattern: name.clone(), xf: Affine::IDENTITY }, name, global: false, spot: false });
}
}
let brushes = self.brush_library();
let mut brushes = self.brush_library();
// The file's graphic styles in place of the defaults, and the objects linked to them.
let (styles, ids) = self.graphic_styles();
let styles_read = !styles.is_empty();
@@ -1003,6 +1068,18 @@ impl<'a> Reader<'a> {
}
doc.graphic_styles = styles.into();
}
// The colors linked to a color that took a free name follow it.
if !renamed.is_empty() {
let mut follow = |_: &mut vectorcraft_color::Color, link: &mut Option<String>, _: &mut f32| {
let Some(new) = link.as_ref().and_then(|l| renamed.get(l)) else { return false };
*link = Some(new.clone());
true
};
doc.map_solid_paints(&mut follow);
for a in brushes.iter_mut().flat_map(|(lib, _)| lib.iter_mut().flat_map(|b| b.art_mut())) {
vectorcraft_doc::swatches::map_node_solid_paints(a, &mut follow);
}
}
let mut warnings = self.warnings;
if let Some((lib, unread)) = brushes {
vectorcraft_brush::store(&mut doc, &lib);
+65
View File
@@ -818,6 +818,71 @@ fn pattern_names_are_numbered_around_the_documents_swatches() {
assert_eq!(names(&d), ["Sea 2"]);
}
/// A pattern whose name has no newline keeps it, and its swatch takes the first free "Name 2" when
/// another swatch has the name: a default swatch, a named color the art uses, or a color of the
/// palette. A pattern a swatch already paints with gets no other.
#[test]
fn a_pattern_swatch_named_as_another_swatch_is_numbered() {
let def = |name: &str| DOTS.replace("(Dots)", &format!("({name})"));
let filled = |name: &str| format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 20.0, 70.0, 80.0));
let ink = format!("0 1 1 0 (Ink) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0));
let paints = |d: &Document, name: &str| d.swatches_iter().find(|s| s.name == name).map(|s| s.paint.clone());
let doc = read_ok(&format!("{}{}{}", def("White"), def("Ink"), layer(&format!("{}{}{ink}", filled("White"), filled("Ink"))))).doc;
assert_eq!(doc.patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["White", "Ink"]);
for name in ["White", "Ink"] {
assert!(matches!(paints(&doc, name), Some(Paint::Solid { .. })), "{name}");
let numbered = format!("{name} 2");
assert!(matches!(paints(&doc, &numbered), Some(Paint::Pattern { pattern, .. }) if pattern == name), "{numbered}");
}
let fills: Vec<_> = art(&doc).iter().map(|n| fill(n)).collect();
assert!(matches!(&fills[..2], [Paint::Pattern { pattern: a, .. }, Paint::Pattern { pattern: b, .. }] if a == "White" && b == "Ink"));
// A pattern defined later under the numbered name keeps its swatch's name.
let doc = read_ok(&format!("{}{}{}", def("White"), def("White 2"), layer(&filled("White")))).doc;
assert!(matches!(paints(&doc, "White 2"), Some(Paint::Pattern { pattern, .. }) if pattern == "White 2"));
assert!(matches!(paints(&doc, "White 3"), Some(Paint::Pattern { pattern, .. }) if pattern == "White"));
// A color of the palette.
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\nPB\n%AI5_EndPalette\n";
let doc = read_ok(&format!("{}{palette}{}", def("Mist"), layer(&filled("Mist")))).doc;
assert!(matches!(paints(&doc, "Mist"), Some(Paint::Solid { .. })));
assert!(matches!(paints(&doc, "Mist 2"), Some(Paint::Pattern { pattern, .. }) if pattern == "Mist"));
// A palette swatch under another name already paints with the pattern.
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\n(Mist) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Fog)\nPc\nPB\n%AI5_EndPalette\n";
let doc = read_ok(&format!("{}{palette}{}", def("Mist"), layer(&filled("Mist")))).doc;
let names: Vec<&str> = doc.swatches_iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["[None]", "Mist", "Fog"]);
}
/// A named color whose name a gradient or pattern swatch of the palette has takes the first free
/// "Name 2", and the fills and gradient stops linked to it follow it.
#[test]
fn a_color_named_as_a_palette_gradient_or_pattern_is_numbered() {
let gradient = "%AI5_BeginGradient: (Brand)\n(Brand) 0 2 Bd\n[\n\
%_0 1 1 0 (Brand) 0 0 5 1 6 50 0 Bs\n%_0 0 0 0 1 0 0 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
let palette = "%AI5_BeginPalette\n0 0 Pb\nBb\n2 (Brand) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Brand)\nPc\n\
(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Ink)\nPc\nPB\n%AI5_EndPalette\n";
let colored = |name: &str| format!("0 1 1 0 ({name}) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0));
let doc = read_ok(&format!("{gradient}{DOTS}{palette}{}", layer(&format!("{}{}", colored("Brand"), colored("Ink"))))).doc;
let paints = |name: &str| doc.swatches_iter().find(|s| s.name == name).map(|s| s.paint.clone());
assert!(matches!(paints("Brand"), Some(Paint::Gradient(_))));
assert!(matches!(paints("Ink"), Some(Paint::Pattern { .. })));
for name in ["Brand 2", "Ink 2"] {
let sw = doc.swatches_iter().find(|s| s.name == name).unwrap_or_else(|| panic!("{name}"));
assert!(matches!(sw.paint, Paint::Solid { .. }) && sw.global && sw.spot, "{sw:?}");
}
let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Solid { swatch, .. } = fill(n) { swatch } else { None }).collect();
assert_eq!(links, [Some("Brand 2".to_string()), Some("Ink 2".to_string())]);
let Some(Paint::Gradient(g)) = paints("Brand") else { panic!() };
assert_eq!(g.gradient.stops[0].swatch.as_deref(), Some("Brand 2"), "the stop's link");
// A color defined later under the numbered name keeps it and its links.
let later = format!("0 0 1 0 (Brand 2) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0));
let doc = read_ok(&format!("{gradient}{DOTS}{palette}{}", layer(&format!("{}{later}", colored("Brand"))))).doc;
let color = |name: &str| doc.swatches_iter().find(|s| s.name == name).and_then(|s| s.paint.color());
assert_eq!(color("Brand 2"), Some(Color::cmyk(0.0, 0.0, 1.0, 0.0)));
assert_eq!(color("Brand 3"), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0)));
let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Solid { swatch, .. } = fill(n) { swatch } else { None }).collect();
assert_eq!(links, [Some("Brand 3".to_string()), Some("Brand 2".to_string())]);
}
/// A palette's pattern swatch named by its pattern takes the name the pattern is shown with.
#[test]
fn a_palette_pattern_swatch_takes_its_patterns_shown_name() {
+21
View File
@@ -150,6 +150,27 @@ pub struct LegacyAiOutput {
pub warnings: Vec<String>,
}
/// Whether image node `n` of `doc` is written as a 1-bit image mask in its colorize color
/// (ImageMask 1, §8.1) that draws as the document does: it is colorized with a solid color, its
/// pixels take the color and are all black or white (or clear), it has no opacity mask turned on,
/// and it has no more pixels than the writer writes. Such an image keeps its clear pixels in the file.
pub fn writes_image_mask(doc: &Document, n: &Node) -> bool {
let NodeKind::Image(im) = &n.kind else { return false };
// The size from the file's header, before any pixels are decoded.
let fits = |bytes: &[u8]| {
image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.ok()
.and_then(|r| r.into_dimensions().ok())
.is_some_and(|(w, h)| w > 0 && h > 0 && u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS)
};
matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. }))
&& !n.extras().mask.as_ref().is_some_and(|m| !m.disabled)
&& doc
.image_blob(im)
.is_some_and(|b| b.takes_colorize() && fits(&b.bytes) && b.coverage().is_some_and(|(_, _, c)| c.iter().all(|&v| v == 0 || v == 255)))
}
/// Write `doc`'s first artboard and every layer (all its art, on the artboard or not) as a
/// legacy `.ai` file of version 7. Art space is y up, its origin at the artboard's left edge and
/// just under its bottom edge: the artboard's top is on a whole point, where readers that place
+5 -3
View File
@@ -36,7 +36,7 @@ pub(crate) const PROCSET: &str = "VectorCraft_Legacy 1 0";
/// application's procedure set): paths and their painting with the fill and stroke colours,
/// compound paths painted as one path, clipping groups, guides that don't print, layers that are
/// hidden or don't print marking nothing, and images drawn from the samples on the comment lines
/// that follow `XI`. Gradients fill with the colour set before them (the writer sets the first
/// that follow `XI` (an image mask's 0 bits in the fill color). Gradients fill with the colour set before them (the writer sets the first
/// stop's), and type marks nothing: apps that read the format draw both. The page trailer's
/// `annotatepage` (§3, Script Setup: `gsave annotatepage grestore showpage`) marks nothing.
pub(super) const PROLOG: &str = "%%BeginResource: procset VectorCraft_Legacy 1 0
@@ -96,9 +96,11 @@ VCLegacy begin
/_l 256 string def /_s 128 string def
/_row {{currentfile _l readline not {exit} if dup length 1 gt {exit} if pop} loop
dup length 1 gt {dup length 1 sub 1 exch getinterval /ASCIIHexDecode filter _s readstring pop} {pop ()} ifelse} bd
/XI {pop pop pop pop /_ic exch def /_ib exch def /_ih exch def /_iw exch def pop pop pop pop
% An image mask (ImageMask 1) paints its 0 bits in the fill color.
/XI {1 eq /_im exch def pop pop pop /_ic exch def /_ib exch def /_ih exch def /_iw exch def pop pop pop pop
[1 0 0 -1 0 0] exch matrix concatmatrix
_on {gsave concat _iw _ih _ib [1 0 0 1 0 0] /_row load false _ic 1 eq {1} {_ic} ifelse colorimage grestore} {pop} ifelse} bd
_on {gsave concat _im {_fc _iw _ih false [1 0 0 1 0 0] /_row load imagemask}
{_iw _ih _ib [1 0 0 1 0 0] /_row load false _ic 1 eq {1} {_ic} ifelse colorimage} ifelse grestore} {pop} ifelse} bd
% Type (15) is set by the app that reads the file: its operators take their operands and mark
% nothing; encodings (3.3) are skipped.
/TE {cleartomark} bd /TZ {cleartomark} bd
+88
View File
@@ -442,6 +442,94 @@ fn empty_images_get_the_size_note_and_undecodable_ones_the_decode_note() {
assert_eq!(notes(b"not an image".to_vec()), [UNDECODED]);
}
/// A gray image of `doc`, `w` × `h` pixels of `gray`, colorized `paint`, placed 10 pt a pixel
/// at (`x`, `y`).
fn colorized_image(doc: &mut Document, (w, h): (u32, u32), gray: Vec<u8>, paint: &Paint, (x, y): (f64, f64)) -> Node {
let mut png = vec![];
image::GrayImage::from_raw(w, h, gray).unwrap().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let blob = ImageBlob::new("image/png", png);
let key = blob.content_key();
doc.images.insert(key.clone(), blob);
let xf = Affine::new([10.0, 0.0, 0.0, 10.0, x, y]);
let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None };
let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im)));
n.extras_mut().colorize = Some(Box::new(paint.clone()));
n
}
/// A colorized image whose pixels are black or white is written as a 1-bit image mask
/// (ImageMask 1) after its color as the fill: its black pixels are 0 bits, which take the color, and its
/// white pixels 1 bits, which are clear. It prints in its color over the square behind it and
/// reads back colorized with that color and with the same clear pixels. A colorized image with
/// gray pixels is written with its color in its pixels, over white, with the note for
/// transparent pixels.
#[test]
fn colorized_images_keep_their_color() {
let mut doc = Document::new(200.0, 100.0);
doc.layers.clear();
let layer = doc.add_layer(Some("Art"));
let square = shape(&mut doc, shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 30.0)), red(), Paint::None);
doc.insert(Some(layer), usize::MAX, square).unwrap();
let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0));
// 1 0 0 1 0 1 1 0 / 0 1 1 0 1 0 0 1 in black (1) and white (0).
let mask: Vec<u8> = "1001011001101001".bytes().map(|b| if b == b'1' { 0 } else { 255 }).collect();
let bitmap = colorized_image(&mut doc, (8, 2), mask.clone(), &paint, (10.0, 10.0));
doc.insert(Some(layer), usize::MAX, bitmap).unwrap();
let out = write(&doc);
let text = String::from_utf8(out.bytes.clone()).unwrap();
let images = rasters(&text);
assert_eq!(images.len(), 1, "{text}");
let [_, _, xi, data @ .., _, _] = images[0].as_slice() else { panic!("{:?}", images[0]) };
assert!(xi.ends_with(" ] 0 0 8 2 8 2 1 1 0 0 0 1 XI"), "{xi}");
// Each row is a byte: the black pixels are 0 bits.
assert_eq!(data, &["%6996"], "{text}");
let at = text.find("%AI5_File:\n").unwrap();
assert!(text[..at].ends_with("0 0.5 1 0 k\n"), "{text}");
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let read = crate::import(&out.bytes).unwrap().document;
let mut found = vec![];
read.walk(|n| {
if let NodeKind::Image(im) = &n.kind {
found.push((read.image_blob(im).and_then(ImageBlob::coverage), n.extras().colorize.as_deref().cloned()));
}
});
let want: Vec<u8> = mask.iter().map(|&v| 255 - v).collect();
assert_eq!(found, [(Some((8, 2, want)), Some(paint.clone()))]);
// Gray pixels: the color at each pixel's strength, over white.
let mut doc = Document::new(200.0, 100.0);
doc.layers.clear();
let layer = doc.add_layer(Some("Art"));
let tint = colorized_image(&mut doc, (2, 1), vec![0, 128], &Paint::solid(Color::rgb(1.0, 0.0, 0.0)), (10.0, 10.0));
doc.insert(Some(layer), usize::MAX, tint).unwrap();
let out = write(&doc);
let text = String::from_utf8(out.bytes.clone()).unwrap();
let images = rasters(&text);
let [_, _, xi, data @ .., _, _] = images[0].as_slice() else { panic!("{:?}", images[0]) };
assert!(xi.ends_with(" ] 0 0 2 1 2 1 8 3 0 0 0 0 XI"), "{xi}");
assert_eq!(data, &["%FF0000FF8080"], "{text}");
assert_eq!(out.warnings, [IMAGE_ALPHA]);
}
/// An image mask is only for a colorized image the writer draws as the document does: not one
/// with an opacity mask turned on, and not one with more pixels than the writer writes.
#[test]
fn image_masks_are_for_images_the_writer_draws_as_they_are() {
let mut doc = Document::new(200.0, 100.0);
let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0));
let mut n = colorized_image(&mut doc, (2, 1), vec![0, 255], &paint, (10.0, 10.0));
assert!(writes_image_mask(&doc, &n));
let art = shape(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::gray(1.0)), Paint::None);
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, false)));
assert!(!writes_image_mask(&doc, &n));
if let Some(m) = n.extras_mut().mask.as_mut() {
m.disabled = true;
}
assert!(writes_image_mask(&doc, &n));
let big = colorized_image(&mut doc, (8193, 8193), vec![255; 8193 * 8193], &paint, (10.0, 10.0));
assert!(!writes_image_mask(&doc, &big));
}
#[test]
fn a_gradient_fill_and_its_stroke_are_one_object() {
let mut doc = Document::new(100.0, 100.0);
+61 -20
View File
@@ -272,7 +272,11 @@ impl<'a> Writer<'a> {
}
NodeKind::Image(im) => {
self.lock(locked);
self.image(self.doc.image_blob(im), im.width, im.height, im.xf);
let blob = self.doc.image_blob(im);
// A colorize color the renderer draws the image in.
let colorize =
n.extras().colorize.as_deref().filter(|p| matches!(p, Paint::Solid { .. }) && blob.is_some_and(ImageBlob::takes_colorize));
self.image(blob, im.width, im.height, im.xf, colorize);
}
NodeKind::SymbolInstance { symbol, xf } => {
self.warn(LIVE);
@@ -835,7 +839,7 @@ impl<'a> Writer<'a> {
// Colour bitmap glyphs (emoji): their images, which the runs' paint doesn't paint.
for g in &layout.glyphs {
if let Some((image, to_text)) = g.placed_image() {
self.image(Some(&image.blob), image.width, image.height, t.xf * to_text);
self.image(Some(&image.blob), image.width, image.height, t.xf * to_text, None);
}
// COLR glyphs: their layers, as art.
if let Some(art) = g.placed_colour(t.xf) {
@@ -853,8 +857,12 @@ impl<'a> Writer<'a> {
/// `%AI5_EndRaster`, then `F`. §8.4's examples have no `F`; without it, an app reading the file
/// can leave out an image in a clipping group and the art after it. No path is open there, so
/// the `F` paints nothing. `blob` holds the pixels, placed as a grid of `width` × `height`
/// by `xf`.
fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine) {
/// by `xf`, and `colorize` is the solid color the image is colorized with. A colorized image
/// whose pixels are all black or white is written as an image mask (ImageMask 1, §8.1): its
/// color as the fill, then 1-bit samples, a 0 bit for each black pixel, which takes the color,
/// and a 1 bit for each white pixel, which is clear. Another colorized image is written with
/// its color in its pixels.
fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, colorize: Option<&Paint>) {
let flip = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]);
let m = self.to_art * xf * flip;
if !invertible(m) {
@@ -876,25 +884,61 @@ impl<'a> Writer<'a> {
// The object places the image's own pixel grid (its width × height) wherever the file's is.
let fit = Affine::scale_non_uniform(f64::from(width.max(1)) / f64::from(w), f64::from(height.max(1)) / f64::from(h));
let m = self.to_art * xf * fit * flip;
// Over white.
let over = |c: u8, a: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8;
if let Some(paint) = colorize {
let Some((_, _, coverage)) = blob.and_then(ImageBlob::coverage).filter(|(cw, ch, _)| (*cw, *ch) == (w, h)) else {
self.warn(UNDECODED);
return;
};
if coverage.iter().all(|&v| v == 0 || v == 255) {
let stride = (w as usize).div_ceil(8);
let mut bits = vec![0xFF; stride.saturating_mul(h as usize)];
for (i, _) in coverage.iter().enumerate().filter(|(_, v)| **v == 255) {
let (x, y) = (i % w as usize, i / w as usize);
if let Some(byte) = bits.get_mut(y * stride + x / 8) {
*byte &= !(0x80 >> (x % 8));
}
}
self.color(paint, false);
self.raster(m, &format!("0 0 {w} {h} {w} {h} 1 1 0 0 0 1"), &bits);
return;
}
let rgb = paint.color().map_or([0; 3], |c| c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8));
let samples: Vec<u8> = coverage.iter().flat_map(|&a| rgb.map(|c| over(c, a))).collect();
self.warn(IMAGE_ALPHA);
self.raster(m, &format!("0 0 {w} {h} {w} {h} 8 3 0 0 0 0"), &samples);
return;
}
let rgba = img.to_rgba8();
let mut hex = String::with_capacity(rgba.len() / 4 * 7);
hex.push('%');
let mut on_line = 0;
let mut samples = Vec::with_capacity(rgba.len() / 4 * 3);
let mut see_through = false;
for px in rgba.pixels() {
let [r, g, b, a] = px.0;
if a < 255 {
see_through = true;
}
// Over white.
let over = |c: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8;
for c in [over(r), over(g), over(b)] {
let _ = write!(hex, "{c:02X}");
on_line += 2;
if on_line >= HEX_LINE {
hex.push_str("\n%");
on_line = 0;
}
samples.extend([over(r, a), over(g, a), over(b, a)]);
}
if see_through {
self.warn(IMAGE_ALPHA);
}
self.raster(m, &format!("0 0 {w} {h} {w} {h} 8 3 0 0 0 0"), &samples);
}
/// An image's lines (§8.4): `%AI5_File:`, `%AI5_BeginRaster`, matrix `m` as `[ a b c d tx ty ]`
/// and the numbers `operands` with `XI`, `samples` in hex on comment lines of [`HEX_LINE`]
/// digits, `%AI5_EndRaster`, then `F`.
fn raster(&mut self, m: Affine, operands: &str, samples: &[u8]) {
let mut hex = String::with_capacity(samples.len() * 2 + samples.len() / HEX_LINE * 2 + 2);
hex.push('%');
let mut on_line = 0;
for c in samples {
let _ = write!(hex, "{c:02X}");
on_line += 2;
if on_line >= HEX_LINE {
hex.push_str("\n%");
on_line = 0;
}
}
if hex.ends_with('%') {
@@ -902,14 +946,11 @@ impl<'a> Writer<'a> {
} else {
hex.push('\n');
}
if see_through {
self.warn(IMAGE_ALPHA);
}
let [a, b, c, d, e, f] = m.as_coeffs();
let s = &mut self.body;
s.push_str("%AI5_File:\n%AI5_BeginRaster\n[ ");
ps::push_nums(s, &[a, b, c, d, e, f]);
let _ = writeln!(s, "] 0 0 {w} {h} {w} {h} 8 3 0 0 0 0 XI");
let _ = writeln!(s, "] {operands} XI");
s.push_str(&hex);
s.push_str("%AI5_EndRaster\nF\n");
}
+1 -1
View File
@@ -47,7 +47,7 @@ pub use import::{
AiLayers, Imported, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, ai_layers_alone, family_style, import, import_trusting, import_with, is_loss,
layered_ai, layered_ai_from, page,
};
pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai};
pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai, writes_image_mask};
pub use print::{PrintJob, PrintPage, print};
use vectorcraft_doc::Document;
+1
View File
@@ -33,6 +33,7 @@ use crate::{Compatibility, ExportReport, PdfError, PdfOptions, Standard};
mod entry;
mod exporter;
mod images;
mod links;
mod nodes;
mod paint;
mod text;
+11
View File
@@ -79,6 +79,16 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha
// In PDF 1.6 and later files that aren't PDF/X files, a page with a side longer than
// [`MAX_PAGE_SIDE`] is written in larger units; other files have every page in points.
let scales = set.compatibility.has_user_unit() && !set.standard.is_pdfx();
// PDF/X files have no annotations over the art (ISO 15930: only printer's mark and trap
// network annotations, outside the bleed box): objects' URLs aren't written as links there.
let links = !set.standard.is_pdfx();
let mut linked = false;
for layer in doc.layers.iter().filter(|_| !links) {
layer.walk(&mut |n| linked |= n.url().is_some());
}
if linked {
warnings.push(format!("{} files have no links: the objects' URLs aren't clickable", set.standard.label()));
}
let mut units = Vec::with_capacity(pages.len());
let total = pages.len() as u64;
for (written, (i, boxes)) in pages.into_iter().enumerate() {
@@ -107,6 +117,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha
clip: m != r,
marks: art.as_ref(),
negative: false,
links,
};
w.page(&mut ex, &sheet).map_err(|_| PdfError::BadArtboard(i))?;
}
+121
View File
@@ -0,0 +1,121 @@
//! The objects' URLs (Window › Attributes) as link annotations: a rectangle over each linked
//! object's bounds on the page that opens its URL (ISO 32000-1 §12.5.6.5 Link Annotations, with a
//! URI action, §12.6.4.7).
use super::{Affine, Exporter, Node, NodeKind, Rect, krilla};
/// Most links written on one page: the rest are left out with a warning.
pub(super) const MAX_LINKS: usize = 10_000;
/// The warning for the links left out past [`MAX_LINKS`].
pub(super) const TOO_MANY_LINKS: &str = "a page has more linked objects than a PDF page keeps links for: the rest aren't clickable";
/// Does a link open `uri`? Web and mail URLs only, the ones the app's Browser button opens: a URL
/// can come from an imported file, and a `javascript:` or `file:` one has no place in a PDF.
fn opens(uri: &str) -> bool {
let scheme = uri.trim().split_once(':').map_or("", |(s, _)| s);
["http", "https", "mailto"].iter().any(|k| scheme.eq_ignore_ascii_case(k))
}
/// A link to write: the URI it opens, and the area it covers in page space (y down).
pub(super) struct Link {
pub uri: String,
pub rect: Rect,
}
impl Exporter<'_> {
/// The links of the art drawn on a page: each linked object that shows (on a layer that
/// prints, or any layer when non-printing layers are written; not on a template layer), over
/// its bounds within the clipping groups it is in and within `area` (document space, the art
/// drawn), mapped onto the page by `to_page`. A group's link comes before its objects', so an
/// object's own link lies over it. The second value: links were left out past [`MAX_LINKS`].
pub(super) fn links(&self, area: Rect, to_page: Affine) -> (Vec<Link>, bool) {
let mut links = vec![];
let mut more = false;
for layer in &self.doc.layers {
self.link_node(layer, area, to_page, &mut links, &mut more);
}
(links, more)
}
fn link_node(&self, n: &Node, within: Rect, to_page: Affine, links: &mut Vec<Link>, more: &mut bool) {
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return;
}
if let NodeKind::Layer { template, printable, .. } = n.kind
&& (template || !(printable || self.non_printing))
{
return;
}
let bounds = n.visual_bounds_with(&self.symbols).filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()));
if let (Some(uri), Some(b)) = (n.url().filter(|u| opens(u)), bounds) {
let shown = b.intersect(within);
if shown.width() > 0.0 && shown.height() > 0.0 {
let rect = to_page.transform_rect_bbox(shown);
if [rect.x0, rect.y0, rect.x1, rect.y1].iter().any(|v| !v.is_finite()) {
// Off any page a reader can show: no link.
} else if links.len() < MAX_LINKS {
links.push(Link { uri: uri_bytes(uri), rect });
} else {
*more = true;
}
}
}
// What a clipping group holds shows only inside its clipping path's bounds.
let within = match bounds {
Some(b) if n.clips() => b.intersect(within),
None if n.clips() => return,
_ => within,
};
if within.width() <= 0.0 || within.height() <= 0.0 {
return;
}
for child in n.children().into_iter().flatten() {
self.link_node(child, within, to_page, links, more);
}
}
}
/// `uri` as a PDF URI (ISO 32000-1 §12.6.4.7: 7-bit ASCII): spaces, control characters and
/// non-ASCII bytes percent-encoded (RFC 3986 §2.1), leading and trailing spaces dropped.
fn uri_bytes(uri: &str) -> String {
let mut out = String::with_capacity(uri.len());
for b in uri.trim().bytes() {
if b.is_ascii_graphic() {
out.push(char::from(b));
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
/// The annotation of `link`: a borderless rectangle that opens its URI.
pub(super) fn annotation(link: Link) -> Option<krilla::annotation::Annotation> {
let r = link.rect;
let rect = krilla::geom::Rect::from_ltrb(r.x0 as f32, r.y0 as f32, r.x1 as f32, r.y1 as f32)?;
let target = krilla::annotation::Target::Action(krilla::action::LinkAction::new(link.uri.clone()).into());
Some(krilla::annotation::Annotation::new_link(krilla::annotation::LinkAnnotation::new(rect, target), Some(link.uri)))
}
#[cfg(test)]
mod tests {
use super::{opens, uri_bytes};
#[test]
fn only_web_and_mail_urls_become_links() {
for ok in ["https://example.com/a", "HTTP://example.com", "mailto:someone@example.com", " https://example.com "] {
assert!(opens(ok), "{ok}");
}
for refused in ["javascript:alert(1)", "file:///etc/passwd", "smb://host/share", "ms-settings:", "example.com", ""] {
assert!(!opens(refused), "{refused}");
}
}
#[test]
fn uris_are_written_in_ascii() {
assert_eq!(uri_bytes(" https://example.com/a b "), "https://example.com/a%20b");
assert_eq!(uri_bytes("https://example.com/café"), "https://example.com/caf%C3%A9");
assert_eq!(uri_bytes("mailto:a@b.c?subject=x\ny"), "mailto:a@b.c?subject=x%0Ay");
}
}
+11
View File
@@ -51,6 +51,8 @@ pub(crate) struct Sheet<'a> {
pub marks: Option<&'a Node>,
/// Invert the page: paper black, ink clear (a film negative).
pub negative: bool,
/// The objects' URLs are written as links over them ([`super::links`]).
pub links: bool,
}
impl Writer {
@@ -190,6 +192,15 @@ impl Writer {
s.pop();
}
s.finish();
if fits && sheet.links {
let (links, more) = ex.links(r, sheet.view * sheet.place);
for annotation in links.into_iter().filter_map(super::links::annotation) {
page.add_annotation(annotation);
}
if more {
ex.warn(super::links::TOO_MANY_LINKS);
}
}
page.finish();
Ok(())
}
+2
View File
@@ -338,6 +338,8 @@ impl PlannedSheet {
clip: true,
marks: self.marks.as_ref(),
negative: self.negative,
// A printed sheet has no links to click.
links: false,
}
}
}
+1
View File
@@ -27,6 +27,7 @@ mod import_lines;
mod import_options;
mod import_overprint;
mod layers;
mod links;
pub(super) mod live_text;
mod marks;
mod mesh_export;
+119
View File
@@ -0,0 +1,119 @@
//! Objects with a URL (Window › Attributes) export as link annotations over their bounds that
//! open it; hidden ones and PDF/X files have none.
use std::sync::Arc;
use craft_pdf::syntax::Pdf;
use craft_pdf::syntax::object::{Array, Dict, Name};
use vectorcraft_color::Color;
use vectorcraft_doc::{Document, Node, NodeId};
use vectorcraft_geom::{Rect, shapes};
use super::{add, doc, rect_node};
use crate::*;
/// A rectangle over `r` linking to `url`.
fn linked(r: Rect, url: &str) -> Node {
let mut n = rect_node(r, Color::rgb(1.0, 0.0, 0.0));
n.edit_attrs(|a| a.url = url.into());
n
}
/// Each link annotation of each page: its URI and its rectangle (PDF space, y up).
fn links(pdf: &[u8]) -> Vec<Vec<(String, [f32; 4])>> {
let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap();
file.pages()
.iter()
.map(|page| {
let Some(annots) = page.raw().get::<Array<'_>>(b"Annots") else { return vec![] };
annots
.iter::<Dict<'_>>()
.filter(|a| a.get::<Name<'_>>(b"Subtype").is_some_and(|s| s.as_ref() == b"Link"))
.map(|a| {
let action = a.get::<Dict<'_>>(b"A").unwrap();
assert_eq!(action.get::<Name<'_>>(b"S").unwrap().as_ref(), b"URI");
let uri = action.get::<craft_pdf::syntax::object::String<'_>>(b"URI").unwrap().as_bytes().to_vec();
let r: Vec<f32> = a.get::<Array<'_>>(b"Rect").unwrap().iter::<f32>().collect();
(String::from_utf8(uri).unwrap(), [r[0], r[1], r[2], r[3]])
})
.collect()
})
.collect()
}
fn near(a: [f32; 4], b: [f32; 4]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01)
}
#[test]
fn a_linked_object_exports_a_link_over_its_bounds() {
let mut d = doc(200.0, 100.0);
add(&mut d, rect_node(Rect::new(0.0, 0.0, 5.0, 5.0), Color::rgb(0.0, 0.0, 1.0)));
add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/a b"));
for bytes in [export(&d, &PdfOptions::default()).unwrap(), export(&d, &PdfOptions::uncompressed()).unwrap()] {
let pages = links(&bytes);
assert_eq!(pages.len(), 1);
let [(uri, rect)] = pages[0].as_slice() else { panic!("one link: {pages:?}") };
// In ASCII, as a PDF URI is (the space percent-encoded).
assert_eq!(uri, "https://example.com/a%20b");
// y up from the page's bottom edge: 100 − 30 to 100 − 10.
assert!(near(*rect, [10.0, 70.0, 50.0, 90.0]), "{rect:?}");
}
}
#[test]
fn hidden_and_unprinted_objects_have_no_links_and_clipping_trims_them() {
let mut d = doc(200.0, 100.0);
let mut hidden = linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/hidden");
hidden.visible = false;
add(&mut d, hidden);
// Clipped to x 20…40: the link covers only what shows.
let clip = Node::path(NodeId(0), shapes::rectangle(Rect::new(20.0, 0.0, 40.0, 100.0)), Default::default());
let mut group = Node::group(NodeId(0), vec![Arc::new(clip), Arc::new(linked(Rect::new(0.0, 40.0, 200.0, 60.0), "https://example.com/clipped"))]);
group.set_clips(true);
let group = d.reid(&group);
add(&mut d, group);
// Off the artboard: nothing to click.
add(&mut d, linked(Rect::new(300.0, 10.0, 350.0, 30.0), "https://example.com/off"));
let pages = links(&export(&d, &PdfOptions::default()).unwrap());
let [(uri, rect)] = pages[0].as_slice() else { panic!("one link: {pages:?}") };
assert_eq!(uri, "https://example.com/clipped");
assert!(near(*rect, [20.0, 40.0, 40.0, 60.0]), "{rect:?}");
// A layer that doesn't print leaves its links out with its art.
let mut d = doc(200.0, 100.0);
add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/"));
if let vectorcraft_doc::NodeKind::Layer { printable, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
*printable = false;
}
assert_eq!(links(&export(&d, &PdfOptions::default()).unwrap()), vec![Vec::<(String, [f32; 4])>::new()]);
}
#[test]
fn each_page_links_its_own_artboard_objects() {
let mut d = doc(200.0, 100.0);
let mut second = d.artboards[0].clone();
second.id = 2;
second.rect = Rect::new(300.0, 0.0, 400.0, 100.0);
d.artboards.push(second);
add(&mut d, linked(Rect::new(310.0, 20.0, 330.0, 40.0), "mailto:a@example.com"));
let pages = links(&export(&d, &PdfOptions::default()).unwrap());
assert_eq!(pages[0], vec![]);
let [(uri, rect)] = pages[1].as_slice() else { panic!("one link: {pages:?}") };
assert_eq!(uri, "mailto:a@example.com");
assert!(near(*rect, [10.0, 60.0, 30.0, 80.0]), "{rect:?}");
}
#[test]
fn pdfx_files_have_no_links() {
let mut d: Document = doc(200.0, 100.0);
add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/"));
let mut o = PdfOptions::default();
(o.settings.standard, o.settings.compatibility) = (Standard::PdfX4, Standard::PdfX4.version());
o.created = Some(1_700_000_000);
let report = export_with_report(&d, &o).unwrap();
assert_eq!(links(&report.bytes), vec![Vec::<(String, [f32; 4])>::new()]);
assert!(report.warnings.iter().any(|w| w.contains("URLs aren't clickable")), "{:?}", report.warnings);
// Without links, no such warning.
assert!(!export_with_report(&doc(200.0, 100.0), &o).unwrap().warnings.iter().any(|w| w.contains("URLs")));
}
+4 -1
View File
@@ -236,7 +236,10 @@ impl Renderer {
bounds = fx.spread(before, space.line);
let outline = image_outline.as_ref().map(|g| (g, FillRule::NonZero)).or(content.outline);
match fx {
RasterFx::GaussianBlur { radius } => effects::pixel::gaussian_rgba(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px),
RasterFx::GaussianBlur { radius, linear } => {
let blur = if *linear { effects::pixel::gaussian_rgba_linear } else { effects::pixel::gaussian_rgba };
blur(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px)
}
RasterFx::Feather { radius } => {
effects::pixel::gaussian_rgba(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px);
if let Some((g, rule)) = outline {
+1 -1
View File
@@ -74,7 +74,7 @@ pub(super) fn hard_edged(chain: &[&RasterFx], px: f64) -> bool {
/// document's raster grid lines `line` apart; `None` when anywhere in the object.
pub(super) fn looks_around(fx: &RasterFx, line: f64) -> Option<f64> {
match fx {
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } => Some(1.5 * radius),
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } => Some(1.5 * radius),
RasterFx::Pixel(p) => p.reach(line),
RasterFx::Rasterize(r) => Some(r.reach()),
_ => Some(0.0),
+1 -1
View File
@@ -691,7 +691,7 @@ impl Renderer {
// The content itself (blurred / feathered / filtered), on its pixels: a filter layer's blur
// works on a coarser grid tied to the canvas, so the blurred art shifted by up to a pixel
// and looked blocky as the view moved by parts of a pixel (#755).
let blurs = rfx.iter().any(|fx| matches!(fx, RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } if *radius > 0.0));
let blurs = rfx.iter().any(|fx| matches!(fx, RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } if *radius > 0.0));
if blurs || rfx.iter().any(|fx| matches!(fx, RasterFx::Pixel(_) | RasterFx::Rasterize(_))) {
self.pixel_content(ctx, f, content, rfx, paint);
} else {
+1 -1
View File
@@ -668,7 +668,7 @@ impl Rules<'_> {
RasterFx::InnerGlow { opacity, blur, color, center: false, .. } if !text => {
shadows.push(format!("inset 0 0 {} {}", self.len(blur), color_css(&color, opacity)))
}
RasterFx::GaussianBlur { radius } => filter = Some(format!("blur({})", self.len(radius / 2.0))),
RasterFx::GaussianBlur { radius, .. } => filter = Some(format!("blur({})", self.len(radius / 2.0))),
RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => art.unsupported("inner glows or feathering"),
RasterFx::Pixel(_) | RasterFx::Rasterize(_) => art.unsupported("pixel effects"),
}
+4 -1
View File
@@ -601,7 +601,10 @@ impl Writer<'_> {
"<feGaussianBlur in=\"SourceAlpha\" stdDeviation=\"{}\" result=\"soft\"/><feComposite in=\"SourceGraphic\" in2=\"soft\" operator=\"in\" result=\"f\"/><feComposite in=\"f\" in2=\"SourceAlpha\" operator=\"in\"/>",
sd(*radius)
),
RasterFx::GaussianBlur { radius } => format!("<feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"{}\"/>", sd(*radius)),
RasterFx::GaussianBlur { radius, linear } => {
let space = if *linear { " color-interpolation-filters=\"linearRGB\"" } else { "" };
format!("<feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"{}\"{space}/>", sd(*radius))
}
RasterFx::Pixel(_) | RasterFx::Rasterize(_) => continue,
};
// Filters composite normally: a shadow's or glow's other blend mode is recorded for import.
+4
View File
@@ -48,6 +48,7 @@ mod css_transform;
mod depth;
mod files;
mod fx;
mod linear_rgb;
mod spread;
mod symbol_units;
mod text;
@@ -150,6 +151,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul
slots,
patterns: HashMap::new(),
midpoints: midpoint_stops(&xml),
linear_rgb: linear_rgb::linear_rgb_ids(&xml, &tree),
labels: labels(&xml),
hidden: found.hidden,
uses: found.uses,
@@ -299,6 +301,8 @@ struct Importer {
patterns: HashMap<usize, String>,
/// Midpoint stops by gradient id (see [`midpoint_stops`]).
midpoints: HashMap<String, Vec<Option<f32>>>,
/// Ids of the gradients mixed in linear light (see [`linear_rgb::linear_rgb_ids`]).
linear_rgb: HashSet<String>,
/// Object names by element id (see [`labels`]).
labels: HashMap<String, String>,
/// Ids of the undisplayed objects shown for usvg ([`prepass`]).
+3 -1
View File
@@ -347,7 +347,9 @@ pub(super) fn effects(filters: &[Arc<Filter>], ts: Affine, blends: &HashMap<Stri
let paint = |c: Color, o: f32| (c.to_hex(), num(o as f64 * 100.0));
let (id, params) = match eval(f, k)? {
V::Graphic => continue,
V::Blurred(sd, _) => ("blur.gaussian", json!({ "radius": blur(sd) })),
// SVG blurs in linear light unless the filter asks for sRGB (`color-interpolation-filters`).
V::Blurred(sd, true) => ("blur.gaussian", json!({ "radius": blur(sd), "linear": true })),
V::Blurred(sd, false) => ("blur.gaussian", json!({ "radius": blur(sd) })),
V::Feathered(sd) => ("stylize.feather", json!({ "radius": blur(sd) })),
V::Stack(layers) => match layers.as_slice() {
[V::Paint { shape, color, opacity, clipped: false }, V::Graphic] if !shape.inverted => {
+4 -2
View File
@@ -104,9 +104,10 @@ impl Importer {
}
}
/// A gradient's stops, midpoints restored.
/// A gradient's stops, midpoints restored, and mixed in linear light when it asks for that.
fn stops(&self, g: &usvg::BaseGradient) -> Vec<GradientStop> {
gradient_stops(g, self.midpoints.get(g.id()).map(Vec::as_slice))
let stops = gradient_stops(g, self.midpoints.get(g.id()).map(Vec::as_slice));
if self.linear_rgb.contains(g.id()) { super::linear_rgb::bake(stops) } else { stops }
}
/// The object name for an element id: its label (see [`labels`]), else the id itself.
@@ -728,6 +729,7 @@ mod tests {
slots: TextSlots::default(),
patterns: HashMap::new(),
midpoints: HashMap::new(),
linear_rgb: HashSet::new(),
labels: HashMap::new(),
hidden: HashSet::new(),
uses: HashMap::new(),
+170
View File
@@ -0,0 +1,170 @@
//! Gradients drawn with `color-interpolation="linearRGB"` (SVG 1.1 §11.7.1,
//! <https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationProperty>): their stops mix in
//! linear light, which a document gradient (mixed in display RGB) shows through extra stops.
use super::{Color, GradientStop, HashMap, HashSet, css, roxmltree};
use vectorcraft_color::cms::lab::{linear_to_srgb, srgb_to_linear};
/// How far (display RGB, 0..1) the straight line between neighbouring baked stops may stray from
/// the linear-light mix: under half a colour level.
const TOLERANCE: f32 = 0.4 / 255.0;
/// Most times a span between two stops is halved to keep within [`TOLERANCE`].
const MAX_DEPTH: u32 = 8;
/// Most stops a baked gradient has: a file with very many stops keeps the rest of its spans as
/// they are rather than growing without bound.
pub(super) const MAX_STOPS: usize = 4096;
/// The ids (as usvg names them) of the gradients whose `color-interpolation` is `linearRGB`.
///
/// usvg gives a gradient used by several objects a made-up id (`linearGradient2`…) for each user
/// but the last; those are found by their stops and geometry, matching an original gradient's
/// only when no other original gradient with the same stops and geometry interpolates otherwise.
pub(super) fn linear_rgb_ids(xml: &roxmltree::Document, tree: &usvg::Tree) -> HashSet<String> {
if !xml.input_text().contains("linearRGB") {
return HashSet::new();
}
let styles = css::Styles::new(xml);
let mut linear = HashSet::new();
let mut named = HashSet::new();
for g in xml.descendants().filter(|n| matches!(n.tag_name().name(), "linearGradient" | "radialGradient")) {
let Some(id) = g.attribute("id") else { continue };
named.insert(id);
if styles.prop(g, "color-interpolation").as_deref() == Some("linearRGB") {
linear.insert(id.to_string());
}
}
if linear.is_empty() {
return linear;
}
let gradients = || {
let lin = tree.linear_gradients().iter().map(|g| (g.id(), signature(g, &[g.x1(), g.y1(), g.x2(), g.y2()])));
let rad = tree.radial_gradients().iter().map(|g| (g.id(), signature(g, &[g.cx(), g.cy(), g.r().get(), g.fx(), g.fy(), g.fr().get()])));
lin.chain(rad)
};
// Each original gradient's look → whether all the originals that look so are linearRGB.
let mut by_look: HashMap<Vec<u32>, bool> = HashMap::new();
for (id, sig) in gradients().filter(|(id, _)| named.contains(id)) {
let is_linear = linear.contains(id);
by_look.entry(sig).and_modify(|v| *v &= is_linear).or_insert(is_linear);
}
let copies: Vec<String> =
gradients().filter(|(id, sig)| !named.contains(id) && by_look.get(sig) == Some(&true)).map(|(id, _)| id.to_string()).collect();
linear.extend(copies);
linear
}
/// What tells two usvg gradients apart but for their id, units and transform (what usvg changes
/// on the copies it makes): their geometry `geom`, spread method and stops.
fn signature(g: &usvg::BaseGradient, geom: &[f32]) -> Vec<u32> {
let spread = match g.spread_method() {
usvg::SpreadMethod::Pad => 0,
usvg::SpreadMethod::Reflect => 1,
usvg::SpreadMethod::Repeat => 2,
};
let mut sig: Vec<u32> = geom.iter().map(|v| v.to_bits()).collect();
sig.push(spread);
for s in g.stops() {
let c = s.color();
sig.extend([s.offset().get().to_bits(), u32::from_be_bytes([0, c.red, c.green, c.blue]), s.opacity().get().to_bits()]);
}
sig
}
/// `stops`, mixed in linear light: between each two stops, stops where the display-RGB line
/// strays from the linear-light mix (opacity still mixes evenly). Spans with a moved midpoint
/// (only our own export writes those, never with linearRGB) keep their midpoint unbaked.
pub(super) fn bake(stops: Vec<GradientStop>) -> Vec<GradientStop> {
let mut out: Vec<GradientStop> = Vec::with_capacity(stops.len());
let mut it = stops.into_iter().peekable();
while let Some(a) = it.next() {
let next = it.peek().cloned();
out.push(a.clone());
let Some(b) = next else { break };
if b.offset <= a.offset || (a.midpoint - 0.5).abs() > 1e-6 || a.color.to_rgb() == b.color.to_rgb() {
continue;
}
let mut ts = Vec::new();
steps(&a.color, &b.color, (0.0, 1.0), 1, &mut ts);
let room = MAX_STOPS.saturating_sub(out.len() + it.len());
for t in ts.into_iter().take(room) {
let opacity = a.opacity + (b.opacity - a.opacity) * t;
out.push(GradientStop { opacity, ..GradientStop::new(a.offset + (b.offset - a.offset) * t, mix(&a.color, &b.color, t)) });
}
}
out
}
/// `a` and `b` mixed at `t` (0..1) in linear light, as display RGB.
fn mix(a: &Color, b: &Color, t: f32) -> Color {
let (p, q) = (a.to_rgb(), b.to_rgb());
let ch = |k: usize| {
let (x, y) = (srgb_to_linear(p[k]), srgb_to_linear(q[k]));
let v = linear_to_srgb(x + (y - x) * t);
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
};
Color::rgb(ch(0), ch(1), ch(2))
}
/// The mix positions (after `t0`, before `t1`) between which display RGB mixed straight stays
/// within [`TOLERANCE`] of the linear-light mix of `a` and `b`, in order.
fn steps(a: &Color, b: &Color, (t0, t1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
let at = |t: f32| mix(a, b, t).to_rgb();
let (c0, c1) = (at(t0), at(t1));
let stray = [0.25, 0.5, 0.75]
.into_iter()
.flat_map(|u: f32| {
let c = at(t0 + (t1 - t0) * u);
(0..3).map(move |k| (c0[k] + (c1[k] - c0[k]) * u - c[k]).abs())
})
.fold(0.0, f32::max);
if depth <= MAX_DEPTH && stray > TOLERANCE {
let m = (t0 + t1) / 2.0;
steps(a, b, (t0, m), depth + 1, out);
out.push(m);
steps(a, b, (m, t1), depth + 1, out);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(stops: &[GradientStop], x: f32) -> [f32; 3] {
vectorcraft_color::Gradient::new(vectorcraft_color::GradientKind::Linear, stops.to_vec()).sample(x).0.to_rgb()
}
#[test]
fn black_to_white_is_brighter_mid_way() {
let baked = bake(vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]);
assert!(baked.len() > 2 && baked.len() < 300, "{}", baked.len());
// A balanced linear-light mix of black and white encodes to about 188/255.
let mid = sample(&baked, 0.5)[0] * 255.0;
assert!((mid - 188.0).abs() < 1.0, "{mid}");
for i in 0..=100 {
let x = i as f32 / 100.0;
let want = linear_to_srgb(x);
assert!((sample(&baked, x)[0] - want).abs() < 1.0 / 255.0, "at {x}");
}
assert!(baked.windows(2).all(|w| w[0].offset <= w[1].offset));
}
#[test]
fn equal_colours_and_moved_midpoints_stay_as_they_are() {
let same = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::BLACK)];
assert_eq!(bake(same.clone()), same);
let moved = vec![GradientStop { midpoint: 0.3, ..GradientStop::new(0.0, Color::BLACK) }, GradientStop::new(1.0, Color::WHITE)];
assert_eq!(bake(moved.clone()), moved);
}
#[test]
fn opacity_mixes_evenly_and_the_stop_count_is_capped() {
let a = GradientStop { opacity: 0.0, ..GradientStop::new(0.0, Color::BLACK) };
let baked = bake(vec![a, GradientStop::new(1.0, Color::WHITE)]);
assert!(baked.iter().all(|s| (s.opacity - s.offset).abs() < 1e-5));
let many: Vec<GradientStop> =
(0..3000).map(|i| GradientStop::new(i as f32 / 2999.0, if i % 2 == 0 { Color::BLACK } else { Color::WHITE })).collect();
let baked = bake(many);
assert_eq!(baked.len(), MAX_STOPS);
assert_eq!(baked.last().map(|s| s.offset), Some(1.0), "every original stop is kept");
}
}
+61
View File
@@ -100,3 +100,64 @@ fn midpoints_come_back() {
assert!((g.gradient.stops[0].midpoint - 0.25).abs() < 1e-6);
assert!((g.gradient.stops[1].midpoint - 0.5).abs() < 1e-6);
}
/// The gradient fills of every path `svg` imports to, in order.
fn imported_gradients(svg: &str) -> Vec<Gradient> {
fn walk(n: &Node, out: &mut Vec<Gradient>) {
if let Paint::Gradient(g) = n.appearance.fill_paint() {
out.push(g.gradient.clone());
}
for c in n.children().into_iter().flatten() {
walk(c, out);
}
}
let d = import(svg).unwrap();
let mut out = vec![];
for l in &d.layers {
walk(l, &mut out);
}
out
}
/// SVG 1.1 §11.7.1 (https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationProperty):
/// `color-interpolation="linearRGB"` mixes a gradient's stops in linear light (#5878).
#[test]
fn linear_rgb_gradients_mix_in_linear_light() {
let svg = |interp: &str| {
format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
<defs><linearGradient id="g" color-interpolation="{interp}"><stop stop-color="black"/><stop offset="1" stop-color="white"/></linearGradient></defs>
<rect width="200" height="200" fill="url(#g)"/></svg>"#
)
};
let mid = |g: &Gradient| g.sample(0.5).0.to_rgb()[0] * 255.0;
let linear = imported_gradients(&svg("linearRGB"));
assert_eq!(linear.len(), 1);
assert!(linear[0].stops.len() > 2);
// A balanced linear-light mix of black and white encodes to about 188/255.
assert!((mid(&linear[0]) - 188.0).abs() < 1.0, "{}", mid(&linear[0]));
let srgb = imported_gradients(&svg("sRGB"));
assert_eq!(srgb[0].stops.len(), 2);
assert!((mid(&srgb[0]) - 127.5).abs() < 1.0, "{}", mid(&srgb[0]));
}
/// The property inherits and cascades; a gradient several objects share (which usvg copies) is
/// mixed in linear light on every one of them, and one asking for sRGB with the same stops isn't.
#[test]
fn linear_rgb_inherits_cascades_and_holds_for_every_user() {
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="100">
<style>.lin { color-interpolation: linearRGB }</style>
<defs style="color-interpolation: linearRGB">
<linearGradient id="a"><stop stop-color="black"/><stop offset="1" stop-color="white"/></linearGradient>
<linearGradient id="b" color-interpolation="sRGB"><stop stop-color="red"/><stop offset="1" stop-color="blue"/></linearGradient>
</defs>
<linearGradient id="c" class="lin"><stop stop-color="red"/><stop offset="1" stop-color="lime"/></linearGradient>
<rect width="50" height="50" fill="url(#a)"/><rect x="60" width="80" height="50" fill="url(#a)"/>
<rect x="150" width="80" height="50" fill="url(#a)"/><rect x="240" width="50" height="50" fill="url(#b)"/>
<rect x="300" width="50" height="50" fill="url(#c)"/></svg>"#;
let counts: Vec<usize> = imported_gradients(svg).iter().map(|g| g.stops.len()).collect();
assert_eq!(counts.len(), 5);
assert!(counts[..3].iter().all(|&n| n > 2), "{counts:?}");
assert_eq!(counts[3], 2, "{counts:?}");
assert!(counts[4] > 2, "{counts:?}");
}
+40 -2
View File
@@ -239,7 +239,7 @@ fn a_figma_blurred_shape_filter_becomes_gaussian_blur() {
assert!(w.is_empty(), "{w:?}");
let fx = effects(&d);
assert_eq!(fx.len(), 1);
assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0})));
assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0, "linear": true})));
}
#[test]
@@ -274,7 +274,7 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() {
assert!(w.is_empty(), "{w:?}");
let fx = effects(&d);
assert_eq!(fx.len(), 1);
assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0})));
assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0, "linear": true})));
// In a scaled group, the radius scales too.
let (d, _) = open(
r##"<defs><filter id="b"><feGaussianBlur stdDeviation="3"/></filter></defs><g transform="scale(2)"><rect width="30" height="20" filter="url(#b)"/></g>"##,
@@ -282,6 +282,44 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() {
assert_eq!(effects(&d)[0].params["radius"], json!(12.0));
}
/// `color-interpolation-filters` (SVG 1.1 §15.7.6, initially linearRGB:
/// https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty) picks whether the
/// blur mixes colours in linear light; sRGB, on the primitive or the filter, keeps them as they
/// are (#5877).
#[test]
fn a_gaussian_blur_keeps_its_colour_space() {
let blur = |filter: &str, primitive: &str| {
let (d, w) = open(&format!(
r##"<defs><filter id="b"{filter}><feGaussianBlur stdDeviation="10"{primitive}/></filter></defs><rect width="100" height="200" filter="url(#b)"/>"##
));
assert!(w.is_empty(), "{w:?}");
effects(&d)[0].params.clone()
};
let linear = json!({"radius": 20.0, "linear": true});
let srgb = json!({"radius": 20.0});
assert_eq!(blur("", r#" color-interpolation-filters="linearRGB""#), linear);
assert_eq!(blur("", ""), linear, "linearRGB is the initial value");
assert_eq!(blur("", r#" color-interpolation-filters="sRGB""#), srgb);
assert_eq!(blur(r#" color-interpolation-filters="sRGB""#, ""), srgb, "inherited from the filter");
// Export writes the space back on the blur, so it survives a round trip.
let (d, _) =
open(r##"<defs><filter id="b"><feGaussianBlur stdDeviation="10"/></filter></defs><rect width="100" height="200" filter="url(#b)"/>"##);
let svg = export(&d, &ExportOptions::default());
assert!(svg.contains(r#"color-interpolation-filters="linearRGB"/>"#), "{svg}");
assert_eq!(effects(&import(&svg).unwrap())[0].params, linear);
// Drawn, black beside white meets as resvg (which blurs in either space) draws it.
for space in ["linearRGB", "sRGB"] {
let source = format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><defs><filter id="f" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="10" color-interpolation-filters="{space}"/></filter></defs><g filter="url(#f)"><rect width="100" height="200"/><rect x="100" width="100" height="200" fill="white"/></g></svg>"##
);
let (ours, theirs) = (render_artboard(&import(&source).unwrap()), resvg_render(&source, 200, 200));
for x in [95, 99, 100, 105] {
let at = 4 * (100 * 200 + x) as usize;
assert!(ours.rgba[at].abs_diff(theirs.rgba[at]) <= 6, "{space} at {x}: {} vs {}", ours.rgba[at], theirs.rgba[at]);
}
}
}
/// The one drop shadow of the only object: (dx, dy, blur, colour, opacity %).
fn shadow(d: &Document) -> (f64, f64, f64, Color, f32) {
let fx = vectorcraft_effects::raster_effects(&effects(d));
+8 -2
View File
@@ -20,24 +20,30 @@ pub fn story(frames: &[&TextObject]) -> Vec<TextRun> {
/// paragraph shares that paragraph with the next frame (its first one): the earlier frame's style
/// wins unless `later_wins[k]` says frame `k`'s first paragraph should (it was just restyled), or
/// the earlier frame's part of the paragraph is empty (its slice ends with a paragraph break).
/// An empty frame that was just restyled keeps its style against unedited empty frames after it.
pub fn story_paras(frames: &[&TextObject], later_wins: &[bool]) -> Vec<ParaStyle> {
let mut out: Vec<ParaStyle> = vec![];
let mut prev_empty_tail = true;
let mut empty_tail_restyled = false;
for (k, f) in frames.iter().enumerate() {
let text = f.plain_text();
let restyled = later_wins.get(k).copied().unwrap_or(false);
let mut styles = f.paragraph_styles().into_iter();
if k > 0
&& let Some(first) = styles.next()
&& (prev_empty_tail || later_wins.get(k).copied().unwrap_or(false))
&& (restyled || (prev_empty_tail && !(text.is_empty() && empty_tail_restyled)))
&& let Some(last) = out.last_mut()
{
*last = first;
}
out.extend(styles);
let text = f.plain_text();
// An empty frame has no paragraph boundary of its own. Keep the preceding frame's
// boundary state so another empty frame cannot replace a paragraph's edited style.
if !text.is_empty() {
prev_empty_tail = text.ends_with('\n') || out.is_empty();
empty_tail_restyled = false;
} else if restyled {
empty_tail_restyled = true;
}
}
out
+33
View File
@@ -163,6 +163,39 @@ fn empty_frames_do_not_replace_an_earlier_paragraph_style() {
assert_eq!(story_paras(&[&first, &restyled_middle, &last], &[false, true, false])[0].justify, Justify::Center);
}
/// When the earlier frame ends with a paragraph break, a restyled empty frame keeps its style
/// against an unedited empty frame after it. An unedited empty frame before it, a frame with
/// text after it, or a restyled frame after it still gives the paragraph its own style.
#[test]
fn a_restyled_empty_frame_keeps_its_style_after_a_paragraph_break() {
let style = |j| ParaStyle { justify: j, ..Default::default() };
let mut first = frame(0.0);
first.runs = vec![TextRun { text: "First\n".into(), style: CharStyle::default(), inline: None }];
first.set_all_paras(style(Justify::Right));
let mut restyled = frame(200.0);
restyled.set_all_paras(style(Justify::Center));
let empty = frame(400.0);
let tail_style = |frames: &[&TextObject], wins: &[bool]| story_paras(frames, wins).last().map(|p| p.justify);
assert_eq!(tail_style(&[&first, &restyled, &empty], &[false, true, false]), Some(Justify::Center));
assert_eq!(tail_style(&[&first, &restyled, &empty, &empty], &[false, true, false, false]), Some(Justify::Center));
// An unedited empty frame before the restyled one gives way to it.
assert_eq!(tail_style(&[&first, &empty, &restyled, &empty], &[false, false, true, false]), Some(Justify::Center));
// A restyled first frame of an empty thread keeps its style as well.
assert_eq!(tail_style(&[&restyled, &empty, &empty], &[true, false, false]), Some(Justify::Center));
// Without an edit, the last empty frame still gives the empty paragraph its style.
assert_eq!(tail_style(&[&first, &restyled, &empty], &[false, false, false]), Some(Justify::Left));
// A later frame with text still gives the paragraph it holds its style.
let mut with_text = empty.clone();
with_text.runs = vec![TextRun { text: "Tail".into(), style: CharStyle::default(), inline: None }];
assert_eq!(tail_style(&[&first, &restyled, &with_text], &[false, true, false]), Some(Justify::Left));
// A later restyled frame wins over the earlier one.
let mut right = empty.clone();
right.set_all_paras(style(Justify::Right));
assert_eq!(tail_style(&[&first, &restyled, &right], &[false, true, true]), Some(Justify::Right));
}
/// Numbered list paragraphs count on from one frame to the next: the second frame's first
/// whole paragraph takes the next number. A paragraph split between the frames has its number
/// in the first frame only, and the paragraph after it takes the next number.
+13 -9
View File
@@ -396,8 +396,13 @@ fn hit_spine_handle(cx: &ToolContext, sel: (NodeId, usize), p: Point, tol: f64)
/// Anchor `sel.1` of blend `sel.0`'s spine.
fn spine_anchor(cx: &ToolContext, (id, ai): (NodeId, usize)) -> Option<vectorcraft_geom::Anchor> {
spine_path(cx, id)?.subpaths.first()?.anchors.get(ai).copied()
}
/// Blend `id`'s spine, built once for callers that look up several of its points.
fn spine_path(cx: &ToolContext, id: NodeId) -> Option<PathData> {
match &cx.doc.node(id)?.kind {
NodeKind::Blend { children, spec } => vectorcraft_doc::live::blend_spine(children, spec)?.0.subpaths.first()?.anchors.get(ai).copied(),
NodeKind::Blend { children, spec } => Some(vectorcraft_doc::live::blend_spine(children, spec)?.0),
_ => None,
}
}
@@ -897,7 +902,9 @@ impl Tool for DirectSelectionTool {
}
let q = from + move_delta(start, p, ev.mods.shift, cx.constrain_angle);
let mut params = json!({"id": id.0, "anchor": anchor, "x": q.x, "y": q.y});
let with: Vec<usize> = self.spine_more.iter().copied().filter(|a| spine_anchor(cx, (id, *a)).is_some()).collect();
let spine = spine_path(cx, id);
let count = spine.as_ref().and_then(|sp| sp.subpaths.first()).map_or(0, |sp| sp.anchors.len());
let with: Vec<usize> = self.spine_more.iter().copied().filter(|a| *a < count).collect();
if !with.is_empty() {
params["with"] = json!(with);
}
@@ -1164,7 +1171,9 @@ impl DirectSelectionTool {
/// The clicked spine point, filled, with its handles.
fn spine_overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let Some(sel) = self.spine.filter(|(id, _)| cx.selection.contains(*id)) else { return vec![] };
let Some(a) = spine_anchor(cx, sel) else { return vec![] };
let Some(spine) = spine_path(cx, sel.0) else { return vec![] };
let Some(points) = spine.subpaths.first().map(|sp| &sp.anchors) else { return vec![] };
let Some(a) = points.get(sel.1).copied() else { return vec![] };
let color = cx.doc.layer_color(sel.0);
let mut out = vec![];
for h in [a.h_in, a.h_out].into_iter().filter(|h| h.distance(a.p) > 1e-6) {
@@ -1172,12 +1181,7 @@ impl DirectSelectionTool {
out.push(Overlay::Handle { p: h, color });
}
out.push(Overlay::Anchor { p: a.p, color, filled: true, size: 5.0 });
out.extend(self.spine_more.iter().filter_map(|i| spine_anchor(cx, (sel.0, *i))).map(|m| Overlay::Anchor {
p: m.p,
color,
filled: true,
size: 5.0,
}));
out.extend(self.spine_more.iter().filter_map(|i| points.get(*i)).map(|m| Overlay::Anchor { p: m.p, color, filled: true, size: 5.0 }));
out
}
}
+1
View File
@@ -707,6 +707,7 @@ fn run_ui_part8(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
}
"ui.tileEdgeColor" => crate::dialogs::tile_edge_color::open(app),
"ui.layerOptions" => crate::dialogs::layer_options::open(app, p),
"ui.rename" => crate::panels::layers::rename(app, p),
"ui.newLayer" => crate::dialogs::layer_options::open_new(app, p),
"ui.newArtboard" => crate::dialogs::artboard_options::open_new(app),
"ui.layersPanelOptions" => crate::dialogs::layers_panel_options::open(app),
+6
View File
@@ -855,6 +855,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. OK runs layer.setProps (one undo step); for several rows it sends only the fields set in the dialog",
),
(
"ui.rename",
"Rename",
"",
"{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, or a row the panel's search, filter or Show Layers Only hides, is an error and nothing opens → {id, name}",
),
(
"ui.newLayer",
"New Layer Options…",
+55 -1
View File
@@ -250,7 +250,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if let Some(id) = located {
open_around(app, &doc, &[id]);
}
let reveal = located.or(reveal);
// A row Rename (`ui.rename`) opened the name field of comes into view first.
let renamed = ui.data_mut(|d| d.remove_temp::<NodeId>(key("rename-reveal")));
let reveal = renamed.or(located).or(reveal);
let Some(st) = app.session.active() else { return };
let list = rows_of_doc(ui, st, &app.ui.layers_panel, &query, &app.ui.layers_filter);
let view = View {
@@ -377,6 +379,58 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
see_selection(app, ui, selected);
}
/// The search typed into the Layers panel's Search All field, as the panel matches it.
fn search_query(ctx: &egui::Context) -> String {
ctx.data(|d| d.get_temp::<String>(egui::Id::unique("layers-search"))).unwrap_or_default().trim().to_lowercase()
}
/// `ui.rename {id?}`: open the Layers panel's name field on the row of layer, group or object
/// `id`, as double-clicking the row's name does: Enter renames it (`layer.setProps`, one undo
/// step), Escape leaves the name as it was. Without `id`, the row Rename names is the Layers
/// panel's highlighted row when a row was clicked last, else the one selected object or group,
/// else the one highlighted row, else the current layer. Several of them, or a row the panel's
/// search, filter or Show Layers Only leaves out, is an error that opens nothing.
pub fn rename(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("the Layers panel is not shown")?;
let st = app.session.active().ok_or("no document open")?;
let one = |ids: &[NodeId]| match ids {
[id] => Ok(*id),
_ => Err("select one layer, group or object to rename".to_string()),
};
let id = match p.get("id") {
Some(v) => {
let id = NodeId(v.as_u64().ok_or_else(|| format!("`id` is an object id, not {v}"))?);
st.doc.node(id).map(|_| id).ok_or("no such layer or object")?
}
None => {
let rows = st.highlighted_rows();
let selected = &st.selection.objects;
let rows_first = super::has_row_keys(&ctx, ROW_KEYS) || selected.is_empty();
if rows_first && !rows.is_empty() {
one(&rows)?
} else if !selected.is_empty() {
one(selected)?
} else {
st.current_layer().ok_or("no layer to rename")?
}
}
};
let doc = st.doc.clone();
let node = doc.node(id).ok_or("no such layer or object")?;
if !listed_when_opened(&doc, &st.layers_open, &app.ui.layers_panel, &search_query(&ctx), &app.ui.layers_filter, id) {
return Err("the Layers panel's search, filter or Show Layers Only hides its row".into());
}
let name = node.identify_label(app.session.prefs.identify_objects_by == "xmlId");
crate::panel_docking::reveal_panel(app, "layers")?;
open_around(app, &doc, &[id]);
ctx.data_mut(|d| {
d.insert_temp(rename_id(), (id.0, name.clone()));
d.insert_temp(key("rename-reveal"), id);
});
ctx.request_repaint();
Ok(json!({ "id": id.0, "name": name }))
}
/// Open the layers and groups around rows `ids`.
fn open_around(app: &mut VectorcraftApp, doc: &Document, ids: &[NodeId]) {
let around: Vec<NodeId> =
+60
View File
@@ -469,6 +469,66 @@ fn shift_enter_renames_a_layer_and_keeps_the_field_open() {
assert!(ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())).is_none(), "and closes the field");
}
/// Rename (`ui.rename`, F2) opens the name field on the selected object's row, as a
/// double-click on the name does: Enter renames it in one undo step.
#[test]
fn rename_opens_the_name_field_of_the_selected_object() {
let (mut app, _, [a, _]) = two_rects();
let ctx = egui::Context::default();
app.ui_ctx = Some(ctx.clone());
let name = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(a).unwrap().display_name();
let before = name(&app);
app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let opened = app.run("ui.rename", json!({})).unwrap();
assert_eq!(opened, json!({"id": a.0, "name": before}));
assert_eq!(ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())), Some((a.0, before.clone())), "the field opens on its row");
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
frame(&mut app, &ctx, vec![], false);
frame(&mut app, &ctx, vec![], false);
assert!(ctx.memory(|m| m.has_focus(rename_id().with("field"))), "with the keyboard");
frame(&mut app, &ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text("Sun".into())], false);
frame(&mut app, &ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], false);
frame(&mut app, &ctx, vec![], false);
assert_eq!(name(&app), "Sun");
app.session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(name(&app), before, "one undo step");
}
/// Rename (`ui.rename`) has no default key, F2 being free: it is listed in Keyboard Shortcuts,
/// where a key can be assigned to it.
#[test]
fn rename_has_no_default_key() {
use crate::shortcut_editor::{command_for_key, default_command_shortcut};
crate::shortcut_editor::sync(&crate::state::UiState::default());
assert_eq!(default_command_shortcut("ui.rename"), None);
assert_eq!(command_for_key("F2"), None);
let (mut app, _, _) = two_rects();
let listed = app.run("shortcuts.list", json!({"query": "ui.rename"})).unwrap();
let rows: Vec<_> = listed.as_array().expect("rows").iter().map(|r| r["label"].clone()).collect();
assert_eq!(rows, [json!("Rename")], "Keyboard Shortcuts lists it");
}
/// Without a selection Rename names the current layer; it refuses several objects and a row the
/// panel doesn't list, and opens nothing then.
#[test]
fn rename_names_the_current_layer_and_refuses_several_or_hidden_rows() {
let (mut app, layer, [a, b]) = two_rects();
let ctx = egui::Context::default();
app.ui_ctx = Some(ctx.clone());
let open = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())).map(|r| r.0);
assert_eq!(app.run("ui.rename", json!({})).unwrap()["id"], json!(layer.0), "nothing selected: the current layer");
ctx.data_mut(|d| d.remove::<(u64, String)>(rename_id()));
app.session.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
assert!(app.run("ui.rename", json!({})).is_err(), "two objects");
assert_eq!(open(&ctx), None);
app.ui.layers_panel.layers_only = true;
assert!(app.run("ui.rename", json!({"id": a.0})).is_err(), "Show Layers Only lists no object rows");
assert_eq!(open(&ctx), None);
assert!(app.run("ui.rename", json!({"id": 999_999})).is_err(), "no such object");
assert_eq!(app.run("ui.rename", json!({"id": layer.0})).unwrap()["id"], json!(layer.0));
assert_eq!(open(&ctx), Some(layer.0));
}
#[test]
fn an_open_rename_does_not_follow_into_another_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+3 -1
View File
@@ -370,7 +370,9 @@ pub fn entries() -> &'static [Entry] {
is_tool: false,
}));
for (id, label, sc, params) in menus::UI_COMMANDS {
if !seen.insert(id) || (sc.is_empty() && !params.starts_with("{}") && !params.starts_with("{path")) {
// Rename has no default key, and a key press names the selection: it needs no `id`.
let key_runs_it = !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || *id == "ui.rename";
if !seen.insert(id) || !key_runs_it {
continue;
}
v.push(Entry { key: id.to_string(), label: label.to_string(), group: id_group(id), is_tool: false });
+9 -4
View File
@@ -1,6 +1,6 @@
# File format parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (`.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x)
Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`,
`OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public
@@ -82,7 +82,9 @@ private editing data. VectorCraft:
PostScript form, from the published *Adobe Illustrator File Format Specification* version 7.0
([PRONOM fmt/423](https://www.nationalarchives.gov.uk/PRONOM/fmt/423)), which apps reading `.ai` open with its
structure (#868). It keeps layers (names, order, visibility, lock), groups, compound paths, clipping groups,
solid colours, linear and radial gradients and RGB images. The format has one artboard: each artboard chosen in
solid colours, linear and radial gradients and RGB images. A colorized image whose pixels are all black or white
is written as a 1-bit image mask (ImageMask 1) in its color, with its white pixels clear, and opens colorized
again; other colorized images are flattened or omitted as the Transparent Images setting below says. The format has one artboard: each artboard chosen in
the options dialog's artboard picker (thumbnails to check, default all) is a file of its own,
`{name}-{artboard}.ai` when there are several. It has no transparency: objects are written opaque, and images
with see-through pixels, opacity or a blending mode are flattened (an opaque image of themselves and the art
@@ -141,7 +143,7 @@ private editing data. VectorCraft:
### Illustrator's private editing data
the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing) or Pucker & Bloat at 0 comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked. Twist as the only effect is read the same way on an unstroked path or compound path whose segments are all straight. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), dashes aligned to corners, a brush other than a Calligraphic one, or a Calligraphic brush with settings of its own or an angle that follows the path comes in as its drawn look (a group named after it). A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372). A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random.Line truncated
the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing) or Pucker & Bloat at 0 comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked. Twist as the only effect is read the same way on an unstroked path or compound path whose segments are all straight. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), dashes aligned to corners, a brush other than a Calligraphic one, or a Calligraphic brush with settings of its own or an angle that follows the path comes in as its drawn look (a group named after it). A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372). A Calligraphic brush's Pressure,Line truncated
## Format by format
@@ -150,7 +152,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri
| VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) |
| Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) |
| Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus |
| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) |
| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) |
| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) |
| PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` |
| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) |
@@ -189,6 +191,9 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri
| Date | Change | Summary |
|---|---|---|
| 2026-11-06 | minor | SVG import: a Gaussian blur keeps the colour space its filter asks for with `color-interpolation-filters` (initially `linearRGB`, SVG 1.1 §15.7.6): a linear-light blur becomes Gaussian Blur with the new `linear` parameter, which blurs the colours in linear light (black beside white meets at about 188/255 instead of 128), and SVG export writes it back on the `feGaussianBlur` (#5877). Blurs that ask for sRGB, and the blurs our own export writes, are as before. CSS export still writes `blur()`. Tests `pixel::tests::linear_light_blur_mixes_light_not_values` (crate `vectorcraft-effects`), `import_live::a_gaussian_blur_keeps_its_colour_space` (crate `vectorcraft-svg`); scores unchanged |
| 2026-11-06 | minor | PDF export and PDF-compatible `.ai` saves write each object's URL (Attributes panel) as a link annotation with a URI action (web and mail URLs only) over the bounds of the object that shows, trimmed by its clipping groups (ISO 32000-1, 12.5.6.5 and 12.6.4.7); hidden objects, layers that don't print and prints have none, and PDF/X files leave them out with a warning (#5785). Own-fixture tests in `tests::links`; PDF import doesn't read links back as URLs yet; scores unchanged |
| 2026-11-06 | minor | SVG import: a gradient with `color-interpolation="linearRGB"` (on it, inherited, or from a style sheet) mixes its stops in linear light, as SVG 1.1 §11.7.1 asks: the document gradient gets extra stops wherever display-RGB mixing would stray by half a colour level or more, so black to white is about 188/255 mid-way instead of 128 (#5878). A gradient several objects share is mixed so on every one. Opacity still mixes evenly; at most 4096 stops per gradient. Tests `import::linear_rgb`, `gradients::linear_rgb_*` (crate `vectorcraft-svg`); scores unchanged |
| 2026-11-05 | minor | `.ai` import (#372): a path with a Calligraphic brush comes in as the path with the brush on its stroke (its weight scales the brush) when its art style's brush settings are the brush's own and its angle is on the page, else as its drawn look; a Calligraphic brush's Tilt, Bearing and Rotation codes come in as those channels instead of Random. Checked against a user's file of 6D Art Pen strokes (used locally, not committed); synthetic tests in `import::ai::tests` |
| 2026-11-05 | minor | PDF import: the stops of an axial or radial shading in a DeviceN space of one spot ink and process plates link to the ink's swatch and keep the plates (`GradientStop.plates` in the native format); PDF and EPS export write them in a DeviceN space again (#3235) |
| 2026-11-04 | minor | Raster/PSD export uses document resolution unless ppi or scale is supplied; CLI run/convert accept --ppi. Synthetic engine, CLI and MCP regressions cover dimensions and override precedence; scores and hours unchanged. |
+8 -3
View File
@@ -879,7 +879,9 @@ document, takes the PDF options and keeps its path when reopened, so Save writes
without giving the document a path. `options: {aiVersion: "7"}` writes legacy `.ai` files of version 7 instead (the
PostScript form, which keeps layers, groups, compound paths and clipping groups in apps that read it), one per artboard
of `range` (default all; `{name}-{artboard}.ai` when several, listed in the result's `files`), with
`transparentImages: "flatten"` (default) or `"omit"` for images with see-through pixels, opacity or a blending mode,
`transparentImages: "flatten"` (default) or `"omit"` for images with see-through pixels, opacity, a blending mode
or a colorize color (except a colorized image of black and white pixels, which is written as a 1-bit image mask in
its color with its white pixels clear),
`hiddenObjects: "layer"` (default: a hidden layer of each layer's hidden objects), `"omit"` or `"visible"`, and
`outlineText: true` to write type as outlines instead of text objects. Type with rotated characters (Character
Rotation) is always written as outlines, which keep the rotation; without `outlineText: true` this gives the warning "type with rotated characters is
@@ -4508,7 +4510,7 @@ row's files in a sub-folder (its size or format, or its own `folder`; `folders:
sub-folders) replaces the rows, and `settings: {png: {…}, jpg: {…}, svg: {…}, pdf: {preset}}` gives every row of a
format its options. On every platform, `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters from a
prefix, a suffix, a name pattern or an item's name become `-` in file and folder names, a folder name ends without
periods or spaces, and a Windows device name (`CON`, `PRN`, `AUX`, `NUL`, `COM1` to `COM9`, `LPT1` to `LPT9`) that
periods or spaces, and a Windows device name (`CON`, `PRN`, `AUX`, `NUL`, `COM1` to `COM9`, `COM¹` to `COM³`, `LPT1` to `LPT9`, `LPT¹` to `LPT³`) that
is the whole name or comes before its first period gets a `-` after it (`CON-.png`). When a row's file would take a
name another row's file already has, compared without case (two PNG rows with different backgrounds and no suffix),
the later file is written as `-2`, `-3`… (`Artboard-1-2.png`) and listed under that name in `files`; two identical
@@ -5718,7 +5720,10 @@ spaceBefore, spaceAfter, hyphenate, mojikumi, burasagari, direction, leadingMode
touches (a caret, `start == end`, touches its paragraph). Without a range they change every paragraph of the
targeted objects, as before. With a range, the character attributes of `text.setStyle` and `text.setFormat` style
that range of characters. When every paragraph that `text.tabs.set` or `text.tabs.clear` targets already has those
stops, the command changes nothing and records no undo step. `text.tabs.get {start?}` and `paraStyle.new` / `paraStyle.redefine {id, start?}` read the
stops, the command changes nothing and records no undo step. `text.tabs.set` rejects a supplied `align`, `leader`, or
`alignOn` value that is not a string, and an empty `alignOn` value.
`text.tabs.get {start?}` and `paraStyle.new` / `paraStyle.redefine {id, start?}` read the
paragraph at `start`; `paraStyle.list` counts paragraphs as uses, and `charStyle.list` counts runs; both count the type in
the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes. `charStyle.unused` and
`paraStyle.unused` (Select All Unused in the Character Styles and Paragraph Styles panel menus) list the styles with no
+7 -1
View File
@@ -1,6 +1,6 @@
# Parity with Adobe Illustrator
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026)
## Feature submission evidence
@@ -1175,6 +1175,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- PDF export and print composition use the optional shared guarded writer ([pdf-backend.md](pdf-backend.md)); app drawing and output policy and desktop printer submission remain in their existing layers. The shared reader keeps the app-owned import adapter; synthetic tests cover layer and overprint state across windows, long operands, inline images, failed decoding, document limits and incomplete tails. Empty and populated metadata key presence is regression-tested, and CI checks the immutable backend source.
Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`).
A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. The stops of an axial or radial shading in a DeviceN space that mixes one spot ink with process plates (a spot ink over a constant cyan, for example) link to the ink's swatch at its tint and keep the process plates, and PDF and EPS (Level 3) export write those stops in a DeviceN space of the ink and those plates, so the spot plate is not lost (#3235, `import_color::a_device_n_gradient_of_a_spot_ink_over_a_process_plate_keeps_both_inks`). Solid fills that mix a spot ink with process plates, and stops that mix several spot inks, still import as RGB, with the spot inks kept as swatches.
A `.ai` or EPS opened from its editing data keeps both swatches when a pattern's name, or a named color's, is also another swatch's: a pattern's swatch named as a default swatch, a named color or a palette color becomes "Name 2", and a named color named as a gradient or pattern swatch of the palette becomes "Name 2", with the fills, strokes and gradient stops linked to it following it (`ai::tests::a_pattern_swatch_named_as_another_swatch_is_numbered`, `ai::tests::a_color_named_as_a_palette_gradient_or_pattern_is_numbered`).
PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning. A Perceptual gradient of spot inks is written as a Separation or DeviceN shading of the stops on its curve; a dithered gradient fill, and a Perceptual gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, are written as images in process colors, with a warning. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`).
PDF export writes a spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4) as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients, colorized images and Lab alternates; Registration still prints on every plate (`pdf/src/tests/output.rs`).
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604).
@@ -1669,6 +1670,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Plug-ins › Color Effects › Create Swatch Legend… (`addon.color.swatchLegend`) opens a dialog (columns, chip size, gap, values, selected swatches only, with a preview) and draws a chip per colour swatch (the selected ones, else all) filled with and linked to its swatch, labelled with its name and values (HEX, RGB, CMYK, Lab or Grayscale; by default its own model; spot swatches marked), black on light chips and white on dark ones, in a grid of chosen columns, chip size and spacing, as one selected group in one undo step (#4919). Tests: `cmd::addons::color::legend::tests` (engine), `addons::color::legend::tests::create_swatch_legend_opens_its_dialog_previews_and_runs_on_ok` (ui-egui).
## Stroke Weight Up and Down shortcuts (2026-11-06)
Cmd/Ctrl+Alt+. (`stroke.weightUp`) and Cmd/Ctrl+Alt+, (`stroke.weightDown`) raise and lower the weight of each selected stroke from its own weight, with the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) names: a quarter unit of Units › Stroke at a time up to one unit, whole units above it, no lower than a quarter unit and no higher than 1000 pt. Type steps its stroked characters; objects without a stroke are left alone; with nothing selected the weight of the next object drawn steps. Each press is one undo step (#5797). Evidence: `tests::strokeux::stroke_weight_up_and_down_step_each_selected_stroke`, `stroke_weight_up_with_nothing_selected_sets_up_new_art`, `cmd::stroke::tests::weight_steps_follow_units_and_stop_at_their_bounds`. Scores unchanged.
## Keyboard shortcuts for Effect menu items (2026-11-01)
Edit › Keyboard Shortcuts lists every item of the Effect menu under its menu path (Effect › Distort & Transform › Transform…) and gives each one a shortcut of its own (stored as `effect:<id>`; they all run `effect.dialog {effect}`, or `effect.apply` for an effect without options, so a shortcut on the command alone couldn't tell them apart). The menu shows the shortcut, and pressing it opens that effect's dialog for the selection (#3296). Test: `shortcuts::tests::an_effect_menu_item_takes_a_shortcut_of_its_own`.
@@ -1697,6 +1702,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s
| Date | Change | Summary |
|---|---|---|
| 2026-11-06 | minor | Stroke Weight Up and Down (Cmd/Ctrl+Alt+. and ,) step each selected stroke's weight (#5797); evidence added; scores unchanged. |
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-06 | minor | Properties in Edit Artboards: a Transform section (reference point, X, Y, W, H, preset, orientation, Move and Scale Artwork) above the Artboards section (name, Artboard Options, Fill), X and Y of the shared reference point (#5219); evidence updated; scores unchanged. |
| 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields; a click still opens the panel (#4088); evidence updated; scores unchanged. |
+6 -1
View File
@@ -38,6 +38,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
| Date | Change | Summary |
|---|---|---|
| 2026-11-06 | minor | Rename (`ui.rename`, no default key) opens the Layers panel's name field on the selected layer, group or object's row, as double-clicking its name does; a key can be assigned in Keyboard Shortcuts (#5324, a VectorCraft addition); scores and estimates unchanged |
| 2026-11-06 | minor | Properties panel in Edit Artboards (Shift+O): a Transform section with the shared reference point, X, Y, W and H, the preset and orientation, and Move and Scale Artwork with Artboard, above the Artboards section with the name, Artboard Options and Fill (#5219); scores and estimates unchanged |
| 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: and the Properties panel's Stroke, links to their panels, scrub the field after them as other labels do; a click still opens the panel (#4088); scores and estimates unchanged |
| 2026-11-05 | minor | Direct Selection: Shift-click picks several points of a blend's spine and dragging one moves them all, with the key objects on them, in one undo step (#5285); scores and estimates unchanged |
@@ -305,7 +306,7 @@ Cmd/Ctrl+/ (`appearance.addFill`) and Cmd/Ctrl+Alt+/ (`appearance.addStroke`) ad
selected objects, as the Appearance panel's Add New Fill and Add New Stroke buttons do.
~110 distinct modified shortcuts on menu commands plus single-key tool shortcuts for the default toolbar
(`crates/tools/src/catalog.rs`), a shortcut editor with chords, and saved sets. Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, and Cmd/Ctrl+L still adds a layer without the dialog. F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does. Not yet diffed item by item
(`crates/tools/src/catalog.rs`), a shortcut editor with chords, and saved sets. Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, and Cmd/Ctrl+L still adds a layer without the dialog. F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does. Rename (`ui.rename`, in the shortcut editor with no default key; a VectorCraft addition, #5324) opens the Layers panel's name field on the selected layer, group or object's row, as double-clicking its name does: Enter renames it in one undo step and Escape keeps the name; several selected objects, or a row the panel's search, filter or Show Layers Only hides, is refused with a message. Not yet diffed item by item
against Illustrator's published default shortcut list; estimated ~70% of it. Remaining: other panel shortcuts,
the type shortcuts (tracking/kerning/leading/baseline steps with Alt/Shift), and selection shortcuts in the
Layers panel. The shortcut editor also lists the commands that are in no menu but run without parameters (Edit › Duplicate,
@@ -313,6 +314,9 @@ panel-menu commands such as Break Link to Symbol), so they can be given shortcut
Align panel's Align Objects, Distribute Objects and Distribute Spacing rows under Align, with no default shortcut, and a
shortcut set there runs what a click on the button runs, with the panel's Align To choice and Distribute Spacing value. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661).
Cmd/Ctrl+Alt+. (`stroke.weightUp`, Stroke Weight Up) and Cmd/Ctrl+Alt+, (`stroke.weightDown`, Stroke Weight Down), the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) gives them, step the weight of each selected stroke from its own weight: by a quarter unit of Units › Stroke up to one
unit, then by whole units, down to a quarter unit; with nothing selected they step the weight of the next object drawn (#5797).
Cmd/Ctrl+Alt+N (`file.newWithoutDialog`, New Without Dialog in the shortcut editor) makes a document with the
settings the New Document dialog opens on (the first Recent entry, or the Print category's Letter while Recent is
empty), without opening the dialog.
@@ -468,6 +472,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development
| Date | Change | Summary |
|---|---|---|
| 2026-11-05 | minor | View › Zoom to Selection after Fit All in Window, with the default shortcut Cmd/Ctrl+Shift+0 (#5601; a VectorCraft addition); scores and estimates unchanged |
| 2026-11-06 | minor | Keyboard shortcuts: Cmd/Ctrl+Alt+. and Cmd/Ctrl+Alt+, (Stroke Weight Up and Down) step each selected stroke's weight, or the next object drawn's (#5797); scores and estimates unchanged |
| 2026-11-06 | minor | Properties: Quick Actions has Repeat Options for one selected radial, grid or mirror repeat, opening Object › Repeat › Options with its values (#5181); scores and estimates unchanged |
| 2026-11-06 | minor | Control bar: with type selected, a Paragraph: link (the Paragraph panel in a popover) and the Align left, Align center and Align right buttons follow the Character controls; the bar leaves them out from its right end when short of room, after X/Y/W/H and the Align buttons (#5372); scores and estimates unchanged |
| 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. |