Merge remote-tracking branch 'origin/main' into HEAD

# Conflicts:
#	ROADMAP.md
This commit is contained in:
bflatastic
2026-10-10 01:56:46 +07:00
93 changed files with 5127 additions and 383 deletions
+37
View File
@@ -0,0 +1,37 @@
name: Affinity 3 corpus
on:
push:
branches: [main]
paths: ["crates/**", "xtask/**", "Cargo.toml", "Cargo.lock", ".github/workflows/affinity-corpus.yml"]
pull_request:
paths: ["crates/**", "xtask/**", "Cargo.toml", "Cargo.lock", ".github/workflows/affinity-corpus.yml"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: affinity-corpus-${{ github.ref }}
cancel-in-progress: true
jobs:
affinity3:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
AFFINITY_CORPUS_REQUIRED: "1"
CARGO_PROFILE_DEV_DEBUG: "0"
CARGO_PROFILE_TEST_DEBUG: "0"
steps:
- uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
toolchain: "1.95"
- name: Fetch pinned and checksum-verified corpus
run: cargo xtask corpus --affinity
- name: Parse every file and freeze actual Affinity 3 feature retention
run: cargo test -p vectorcraft-affinity --all-features -- --nocapture
- name: Check every artboard, native save, SVG, PDF and PSD exports
run: cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
Generated
+14
View File
@@ -2553,6 +2553,15 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "objc2-core-text"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
@@ -4323,6 +4332,8 @@ dependencies = [
"muda",
"objc2 0.6.4",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-core-text",
"objc2-foundation 0.3.2",
"rfd",
"serde_json",
@@ -4341,6 +4352,7 @@ version = "0.7.0"
dependencies = [
"crc32fast",
"flate2",
"image",
"proptest",
"ruzstd",
]
@@ -4378,6 +4390,8 @@ name = "vectorcraft-cli"
version = "0.7.0"
dependencies = [
"log",
"objc2-core-foundation",
"objc2-core-text",
"serde_json",
"vectorcraft-color",
"vectorcraft-doc",
+4 -2
View File
@@ -190,7 +190,7 @@ For the experimental, unsupported 64-bit Windows 7 build, see [Windows 7 instruc
VectorCraft is under active development. [**ROADMAP.md**](ROADMAP.md) covers what ships today, the
milestones, and honest time-to-parity estimates.
**Where we are (2026-10-07):** roughly 69–75% of Illustrator's features exist and work, and about 40–55% of
**Where we are (2026-10-09):** roughly 69–75% of Illustrator's features exist and work, and about 40–55% of
"a power user can't tell the difference". Everyday vector illustration is close to usable: drawing and path tools,
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, EPS, DXF, EMF/WMF, raster formats and PSD, Print, Package).
@@ -198,7 +198,9 @@ Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their c
and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping
and masks, text and images, with what didn't come in (effects, adjustments, brushes, master pages…) listed in the
import warning; a file whose native data can't be read opens as its embedded preview, saying why. VectorCraft
doesn't write Affinity files. [Scope and limits](crates/affinity/README.md).
doesn't write Affinity files. Current `.af` validation includes 33 pinned files, native save/reload
and every-board SVG/PDF/PSD export, with fixes for Affinity 3 artboards, source-backed JPEGs and text runs.
[Scope and limits](crates/affinity/README.md); [source audit and remaining gaps](docs/affinity-validation.md).
The interface
speaks English, Japanese, Traditional and Simplified Chinese, Spanish, French, Italian, Russian and Ukrainian (and Czech and Brazilian Portuguese in the menus).
The scores are
+15 -13
View File
File diff suppressed because one or more lines are too long
+6
View File
@@ -31,6 +31,12 @@ log = { workspace = true }
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] }
# CoreText's font manager (the desktop app's src/mac_fonts.rs, shared): fonts that apps and font
# managers register from their own folders (#579). Zlib OR Apache-2.0 OR MIT.
[target.'cfg(target_os = "macos")'.dependencies]
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFString", "CFURL"] }
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] }
[dev-dependencies]
vectorcraft-testkit = { workspace = true }
serde_json = { workspace = true }
+8 -2
View File
@@ -9,8 +9,8 @@
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000]
//! ```
// Denied, not forbidden: the DirectWrite font lister shared with the desktop app (Windows) allows
// it for its COM calls, and nothing else may.
// Denied, not forbidden: the font listers shared with the desktop app allow it for their
// DirectWrite (Windows) and CoreText (macOS) calls, and nothing else may.
#![deny(unsafe_code)]
use std::io::Write;
@@ -36,6 +36,10 @@ macro_rules! out {
}};
}
/// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts.
#[cfg(target_os = "macos")]
#[path = "../../vectorcraft/src/mac_fonts.rs"]
mod mac_fonts;
mod perf;
/// The desktop app's DirectWrite font lister, shared: exports and MCP find the same fonts.
#[cfg(all(windows, not(target_vendor = "win7")))]
@@ -104,6 +108,8 @@ fn main() -> ExitCode {
// Before any font lookup: the fonts font services load (#579).
#[cfg(all(windows, not(target_vendor = "win7")))]
system_fonts::install();
#[cfg(target_os = "macos")]
mac_fonts::install();
let args: Vec<String> = std::env::args().skip(1).collect();
let r = match args.first().map(String::as_str) {
Some("mcp") => mcp(&args[1..]),
+5
View File
@@ -51,6 +51,11 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit, muda and rfd.
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSNotification", "NSOperation", "NSString", "NSURL"] }
block2 = "0.6"
# CoreText's font manager (src/mac_fonts.rs): fonts that apps and font managers register from their
# own folders (#579). Zlib OR Apache-2.0 OR MIT; objc2-core-foundation already comes with
# objc2-foundation.
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFString", "CFURL"] }
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] }
[build-dependencies]
# Icon + VERSIONINFO for vectorcraft.exe; build.rs only uses it when targeting Windows.
+84
View File
@@ -0,0 +1,84 @@
//! macOS: the font files CoreText's font manager lists, scanned with the font folders
//! (`vectorcraft_text::set_platform_font_files`). The desktop app and `vectorcraft-cli` (exports,
//! MCP) both install it; the CLI shares this file.
//!
//! Apps and font managers can register fonts with the font manager from files in any folder,
//! outside the font folders
//! (<https://developer.apple.com/documentation/coretext/ctfontmanagerregisterfontsforurl(_:_:_:)>).
//! The font manager's list of available fonts holds them
//! (<https://developer.apple.com/documentation/coretext/ctfontmanagercopyavailablefonturls()>), so
//! VectorCraft lists them as it does on Windows (`system_fonts.rs`), reading the files in place
//! (#579).
//!
//! CoreText is a C API with no safe binding, hence the scoped `unsafe_code` allowance.
#![allow(unsafe_code)]
use std::collections::BTreeSet;
use objc2_core_foundation::{CFType, CFURL};
use objc2_core_text::CTFontManagerCopyAvailableFontURLs;
/// The most fonts read from the list (a system has a few thousand faces).
const MAX_FONTS: usize = 1 << 16;
/// Have the font scans read the font files CoreText lists.
pub fn install() {
vectorcraft_text::set_platform_font_files(font_files);
}
/// The files of the fonts available to the app as CoreText lists them now (fonts registered since
/// the last call included).
fn font_files() -> Vec<String> {
// SAFETY: a CoreText call without arguments; it returns a new array.
let list = unsafe { CTFontManagerCopyAvailableFontURLs() };
// SAFETY: the array holds CF objects (CFURLs, as CoreText documents); each one is checked to be
// a CFURL before it is read.
let fonts = unsafe { list.cast_unchecked::<CFType>() };
// Faces of one file (a collection's) name it once.
let files: BTreeSet<String> = fonts
.iter()
.take(MAX_FONTS)
.filter_map(|f| f.downcast::<CFURL>().ok())
// Only file URLs, as in `open_documents.rs` (#433).
.filter(|u| u.scheme().is_some_and(|s| s.to_string().eq_ignore_ascii_case("file")))
.filter_map(|u| u.to_file_path()?.into_os_string().into_string().ok())
.collect();
files.into_iter().collect()
}
#[cfg(test)]
mod tests {
use objc2_core_foundation::CFURL;
use objc2_core_text::{CTFontManagerRegisterFontsForURL, CTFontManagerScope, CTFontManagerUnregisterFontsForURL};
/// CoreText lists the installed fonts, by their files' full paths.
#[test]
fn coretext_lists_the_installed_font_files() {
let files = super::font_files();
assert!(files.iter().all(|f| std::path::Path::new(f).is_absolute()), "{:?}", files.first());
assert!(files.iter().any(|f| f.starts_with("/System/Library/Fonts/")), "{} files, {:?}", files.len(), files.first());
}
/// A font registered with CoreText from another folder, as apps and font managers register
/// fonts, is listed while it is registered.
#[test]
fn fonts_registered_from_other_folders_are_listed() {
let dir = std::env::temp_dir().join(format!("vectorcraft-mac-fonts-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// A space in the name: the URL's escapes are decoded. The bundled serif isn't a font macOS
// installs.
let file = dir.join("Registered Font.ttf");
std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap();
let want = std::fs::canonicalize(&file).unwrap();
let listed = || super::font_files().iter().any(|f| f.ends_with("/Registered Font.ttf") && std::fs::canonicalize(f).is_ok_and(|p| p == want));
assert!(!listed());
let url = CFURL::from_file_path(&file).unwrap();
// SAFETY: a file URL, a scope constant and no error out-parameter.
assert!(unsafe { CTFontManagerRegisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) });
let registered = listed();
// SAFETY: as above.
unsafe { CTFontManagerUnregisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) };
std::fs::remove_dir_all(&dir).unwrap();
assert!(registered);
}
}
+4
View File
@@ -23,6 +23,8 @@ mod control_server;
mod gpu;
mod logging;
#[cfg(target_os = "macos")]
mod mac_fonts;
#[cfg(target_os = "macos")]
mod mac_menu;
#[cfg(target_os = "macos")]
mod open_documents;
@@ -393,6 +395,8 @@ fn main() -> std::process::ExitCode {
// Before the first font scan (the app's start): the fonts font services load (#579).
#[cfg(all(windows, not(target_vendor = "win7")))]
system_fonts::install();
#[cfg(target_os = "macos")]
mac_fonts::install();
let mut control_port: Option<u16> = std::env::var("VECTORCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
+1
View File
@@ -16,6 +16,7 @@ synth = []
[dependencies]
crc32fast = { workspace = true }
flate2 = { workspace = true }
image = { workspace = true }
ruzstd = "0.9"
[dev-dependencies]
+36 -13
View File
@@ -11,7 +11,7 @@ Affinity files.
| Affinity | VectorCraft |
|---|---|
| Pages, Publisher spreads (one or two pages) | artboards, spreads side by side |
| Artboards (`ShpN` with `ABEn`), with name, background fill, any transform | artboards plus a clip group with the background |
| Artboards (legacy `ABEn` or Affinity 3 `phrp`/`aprp`), with name, paint and any transform | artboards plus a clip group with the actual vector outline, background and stroke |
| Layers (`Scop`), groups (`Grup`), pass-through or isolated | layers and sublayers, groups |
| Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | paths (multi-subpath curves fill even-odd) |
| Rectangles with corner radii (relative or absolute), ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids | paths |
@@ -23,9 +23,9 @@ Affinity files.
| Linear, elliptical and radial gradients with Affinity's midpoint bias | gradients (the bias as the midpoint where the blend is half way) |
| Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill | stroke appearance |
| Fill layers (`FRst`) | filled rectangles |
| Artistic and frame text: characters, font family/weight/style, size, tracking, fixed leading, colour, paragraph alignment, first baseline | point type and area type |
| Artistic and frame text: Unicode scalar-indexed runs, stored fallback font, family/weight/style, boolean OpenType features, all caps, size, tracking, fixed leading, colour, paragraph alignment, first baseline | point type and area type |
| Placed images (`ImgN`): the original JPEG/PNG embedded in the file | embedded images |
| Pixel layers (`Rstr`): RGBA 8/16-bit and CMYK 8-bit tiles, cropped to their content | embedded PNG images |
| Pixel layers (`Rstr`): RGBA 8/16-bit and CMYK 8-bit tiles, cropped to their content; source-backed RGBA8 JPEG/PNG tiles with matching dimensions and zero origin | embedded PNG images |
| Embedded documents and symbols (`EmbN`) | the picture Affinity cached of them |
| Opacity, visibility, lock, names, the blend modes VectorCraft has | the same |
@@ -35,7 +35,7 @@ transparency gradients, fill opacity, bitmap fills, master pages, conical gradie
special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner
types other than round, stars with rounded points, several fills or strokes on one object (the
active one is used), outlined or scaled text, text fields such as page numbers, frames with
columns or a curved outline, grey/Lab/32-bit pixels, CMYK pixels (converted to RGB without the
columns or a curved outline, paragraph indents/spacing, mixed paragraph alignments, unsupported font selectors, grey/Lab/32-bit pixels, CMYK pixels (converted to RGB without the
document's profile) and Affinity-only blend modes (Add, Linear Light… as Normal).
When the native document can't be read at all, the engine opens the embedded PNG preview instead,
@@ -78,19 +78,32 @@ of CC0 sample files.
* **Read-only.** Nothing is written in Affinity's format; export waits until someone can check
written files in Affinity itself.
The same reader is shared, as an independent copy, with PhotoCraft's `photocraft-affinity`.
The reader also has an independent copy in PhotoCraft's `photocraft-affinity`.
## Validation
* Unit tests on synthetic containers built by the `synth` feature (stored, zlib and zstd entries,
checksums, budgets, cycles, hostile streams, every truncation) and property tests of random
mutations.
* `cargo xtask corpus --affinity` fetches 22 public CC0/MIT/Apache-2.0 documents, including the
four Affinity 3 `.af` files of [samuel-etver/vector-art](https://github.com/samuel-etver/vector-art)
(CC0), at pinned commits, each checked against `xtask/affinity-corpus.sha256`. `tests/real_files.rs`
parses them; `engine/tests/affinity_corpus.rs` renders each one and compares it with the
thumbnail Affinity saved in it (mean difference 0–4.4 of 255 at the thumbnail's size, with a
ceiling per file).
* `cargo xtask corpus --affinity` fetches 51 public CC0/MIT/Apache-2.0 documents at pinned
commits, SHA-256 verified against `xtask/affinity-corpus.sha256`, with upstream license notices.
Of these, 33 are current `.af`: four CC0 vector illustrations and 28 original Affinity 3.2.3
feature probes plus one separately identified derived regression input from
[SethRobinson/Patchy](https://github.com/SethRobinson/Patchy). Only document data and provenance
notices were inspected, never that project's importer or authoring scripts.
* `tests/real_files.rs` parses every file and freezes the modeled features of all 33 current
`.af` files. Native raster tests compare decoded pixels with independent embedded images;
text tests assert Unicode run boundaries, fallback fonts and feature retention.
* `engine/tests/affinity_corpus.rs` requires editable native import, exact `.vectorcraft`
save/reload, and SVG/PDF/PSD export of every board in all 33 current files. It checks SVG/PDF
dimensions and reimport, and independently decodes PSD merged pixels using the published
specification. These are VectorCraft consistency checks, not independent Affinity PSD oracles.
Saved-thumbnail comparisons cover the existing 22 documents plus nine new representative
fixtures, checking every board; unsupported effects and text layout are not claimed visually
faithful. The Affinity corpus workflow requires the files, so missing fixtures cannot silently
pass CI. Run locally with `AFFINITY_CORPUS_REQUIRED=1` for the same strict gate.
* Synthetic engine regressions cover nested, rotated and curved artboards, negative origins,
multiple spreads and resolution conversion, alongside text recovery and native save/export.
* `engine/tests/import_fuzz.rs` mutates a synthetic native document's stream and archive and checks
that whatever opens also renders and exports; `fuzz/` has `cargo-fuzz` targets for the whole
reader (`container`) and the object stream (`stream`):
@@ -100,6 +113,10 @@ The same reader is shared, as an independent copy, with PhotoCraft's `photocraft
cargo +nightly fuzz run stream -- -max_total_time=600
```
The source audit, licensing decisions and remaining complex-document/font cases are recorded in
[affinity-validation.md](../../docs/affinity-validation.md). Reopening VectorCraft's exports in
Affinity remains an independent validation step that hasn't been done.
What has not been verified: files from Affinity builds or platforms outside the public set, files
written by other applications, rotated or skewed images against Affinity's render, mask polarity
against a render with and without the mask, and anything listed as a warning above. The `synth`
@@ -113,8 +130,14 @@ default (`Limits`), a 64 MiB zstd window, 4096 saved revisions, array lengths no
bytes left, 16 777 216 decoded values per document stream (fields and array elements together, counted before
anything is allocated: a value takes about 40 bytes in memory however few it took in the file; the largest of
those 189 public documents uses 3.3 million), 384 levels of object nesting, 128 levels of layers, 500 000 layers, four million curve
nodes per curve, 64 megapixels per pixel layer (cropped to its content first) and 1024 gradient
stops. Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the
nodes per curve; compound outlines also cap recursion at 128 levels, operand visits at 100 000
and cumulative geometry work at four million, rejecting cycles and partial results on limits.
Pie sweeps normalize finite angles in constant time. Pixel layers are limited to 64 megapixels
(cropped to their content first); gradients to 1024 stops. Text collection is bounded to a
million characters per node before allocation, with a cumulative 16 MiB budget for owned font
names, features and gradient stops. Exhaustion warns and uses default attributes for remaining
text, preserving its characters.
Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the
crate has no panics outside tests.
## Privacy
+2 -2
View File
@@ -337,7 +337,7 @@ fn unpredict(b: &mut [u8], compression: u8) -> Result<(), Error> {
(0x40, _) => byte_delta(b),
(0x80, false) => {
let mut prev = 0u16;
for pair in b.chunks_exact_mut(2) {
for pair in b.as_chunks_mut::<2>().0.iter_mut() {
let v = u16::from_le_bytes([pair[0], pair[1]]).wrapping_add(prev);
pair.copy_from_slice(&v.to_le_bytes());
prev = v;
@@ -349,7 +349,7 @@ fn unpredict(b: &mut [u8], compression: u8) -> Result<(), Error> {
if b.len() == 0x10000 {
let planes = b.to_vec();
let (hi, lo) = planes.split_at(0x8000);
for (i, out) in b.chunks_exact_mut(4).enumerate() {
for (i, out) in b.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let (Some(h), Some(l)) = (hi.get(2 * i..2 * i + 2), lo.get(2 * i..2 * i + 2)) else {
return Err(Error::Malformed("tile size"));
};
+88 -7
View File
@@ -6,15 +6,77 @@ use crate::stream::{ObjId, Tag, Value};
/// Nodes per curve object.
const MAX_NODES: usize = 4_000_000;
/// A shared-object stream is bounded, but a compound graph can expand exponentially. Count
/// each visit and each curve record / generated contour / transformed segment across the whole
/// outline, including repeated references. Match the document reader's nesting limit.
const MAX_OUTLINE_DEPTH: usize = 128;
const MAX_OUTLINE_VISITS: usize = 100_000;
struct OutlineBudget {
active: Vec<ObjId>,
visits: usize,
work: usize,
failed: bool,
}
impl OutlineBudget {
fn fail(&mut self, r: &mut Reader, warning: &'static str) -> Option<()> {
if !self.failed {
r.warn(warning);
}
self.failed = true;
None
}
fn spend(&mut self, r: &mut Reader, work: usize) -> Option<()> {
if work > self.work {
return self.fail(r, "compound outlines exceeding the geometry work limit");
}
self.work -= work;
Some(())
}
fn path(&mut self, r: &mut Reader, path: &Path) -> Option<()> {
for subpath in &path.subpaths {
self.spend(r, 1)?;
self.spend(r, subpath.segments.len())?;
}
Some(())
}
}
/// The node-space outline of a curve, shape or compound node, and whether it fills even-odd.
/// Instances (master-page or symbol copies) take the geometry of their master.
pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> {
let mut budget = OutlineBudget { active: Vec::new(), visits: MAX_OUTLINE_VISITS, work: MAX_NODES, failed: false };
bounded_outline(r, id, class, world, &mut budget)
}
fn bounded_outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine, budget: &mut OutlineBudget) -> Option<(Path, bool)> {
if budget.active.contains(&id) {
budget.fail(r, "a compound outline that contains itself")?;
}
if budget.active.len() >= MAX_OUTLINE_DEPTH {
budget.fail(r, "compound outlines nested deeper than 128 levels")?;
}
if budget.visits == 0 {
budget.fail(r, "compound outlines exceeding the operand visit limit")?;
}
budget.visits -= 1;
budget.active.push(id);
let result = outline_inner(r, id, class, world, budget);
// The popped value is our own stack marker, and is no longer needed.
let _ = budget.active.pop();
result
}
fn outline_inner(r: &mut Reader, id: ObjId, class: Tag, world: Affine, budget: &mut OutlineBudget) -> Option<(Path, bool)> {
let s = r.s;
match &class.0.to_be_bytes() {
b"PCrv" | b"TxtC" => {
let crvs = s.obj(id, b"Crvs").or_else(|| s.obj(id, b"MCrM").and_then(|m| s.obj(m, b"Crvs")))?;
let path = curves(r, crvs)?;
let path = curves(r, crvs, budget)?;
budget.path(r, &path)?;
let multi = path.subpaths.len() > 1;
Some((path, multi))
}
@@ -29,8 +91,24 @@ pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> O
if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) {
r.warn("compound shapes that intersect or exclude (imported as add)");
}
if let Some((p, _)) = outline(r, c, class, local.then(world)) {
path.subpaths.extend(p.transformed(local).subpaths);
let child_world = local.then(world);
if !child_world.is_finite() {
budget.fail(r, "a compound operand with an invalid transform")?;
}
if let Some((mut p, _)) = bounded_outline(r, c, class, child_world, budget) {
// Charge before transforming or extending. Transform the owned path in place
// so nested compounds do not make an additional copy of every contour.
budget.path(r, &p)?;
for subpath in &mut p.subpaths {
subpath.start = local.apply(subpath.start);
for segment in &mut subpath.segments {
*segment = segment.map(|point| local.apply(point));
}
}
path.subpaths.extend(p.subpaths);
} else if budget.failed {
// Never present a partial compound as complete after a cycle or budget limit.
return None;
}
}
Some((path, true))
@@ -44,7 +122,9 @@ pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> O
}
};
let b = s.floats::<4>(box_owner, b"ShpB")?;
crate::shapes::shape(r, shape, b, world).map(|p| (p, false))
let path = crate::shapes::shape(r, shape, b, world)?;
budget.path(r, &path)?;
Some((path, false))
}
}
}
@@ -53,7 +133,7 @@ pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> O
/// A record is (f64 x, f64 y, u8 kind, u8 role): role 0 is an anchor, 1 the out-handle of the
/// anchor before it, 2 the in-handle of the anchor after it. A closed subpath repeats its first
/// anchor at the end. `CnrD` live corners are rounded on the stored polyline.
pub(crate) fn curves(r: &mut Reader, crvs: ObjId) -> Option<Path> {
fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option<Path> {
let s = r.s;
let data = s.obj(crvs, b"Data")?;
let mut fields = s.positional(data);
@@ -62,6 +142,7 @@ pub(crate) fn curves(r: &mut Reader, crvs: ObjId) -> Option<Path> {
Value::UInt(n) => usize::try_from(*n).ok()?,
_ => return None,
};
budget.spend(r, count)?;
let corners = s.obj(crvs, b"CnrD").and_then(|c| corner_radii(s.positional(c).collect()));
let mut path = Path::default();
let mut seen = 0usize;
@@ -73,9 +154,9 @@ pub(crate) fn curves(r: &mut Reader, crvs: ObjId) -> Option<Path> {
let Value::Array(records) = fields.next()? else { return None };
seen = seen.checked_add(records.len())?;
if seen > MAX_NODES {
r.warn("curves with more than four million nodes");
return None;
budget.fail(r, "curves with more than four million nodes")?;
}
budget.spend(r, records.len())?;
let anchors = anchors(records)?;
let radii = if index == 0 { corners.as_ref() } else { None };
if let Some(sp) = subpath(&anchors, closed, radii) {
+30 -6
View File
@@ -172,6 +172,9 @@ pub struct TextRun {
/// CSS weight (400 regular, 700 bold).
pub weight: i64,
pub italic: bool,
/// Boolean OpenType feature overrides, as tags or `-tag` for disabled features.
pub features: Vec<String>,
pub all_caps: bool,
/// Font size in document pixels, before the node's transform.
pub size: f64,
/// Tracking in em.
@@ -223,10 +226,16 @@ pub enum Kind {
/// Layer container (`Scop`).
Layer,
Group,
/// Artboard: a rectangle that clips its children; `background` paints behind them.
/// Artboard: an export rectangle and vector outline that clips its children.
/// `background` paints behind them, and `strokes` over them.
Artboard {
rect: Rect,
/// Actual clipping outline in document pixels. The artboard's export rectangle is its
/// bounding box, but a rotated or non-rectangular board still clips to this outline.
path: Path,
even_odd: bool,
background: Vec<Paint>,
strokes: Vec<Stroke>,
},
/// Curve, parametric shape or compound shape: an outline with its fills and strokes.
/// Children of a shape are clipped by its outline (painted over its fills, under its strokes).
@@ -436,7 +445,10 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
b"Scop" => Kind::Layer,
b"Grup" => Kind::Group,
b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => {
if class == Tag::of(b"ShpN") && s.bool(id, b"ABEn") == Some(true) {
// Affinity 3.2.3's two-board public fixture marks board shapes with an `aprp`
// property object in `phrp`, while older documents use `ABEn`. Ordinary shapes
// in that fixture have neither. See the pinned corpus and validation audit.
if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) {
return Ok(self.artboard(id, world));
}
let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else {
@@ -523,12 +535,15 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
fn artboard(&mut self, id: ObjId, world: Affine) -> Kind {
let s = self.s;
let b = s.floats::<4>(id, b"ShpB").map(rect).unwrap_or(Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 });
let Some(b) = s.floats::<4>(id, b"ShpB").map(rect).filter(|b| b.x1 > b.x0 && b.y1 > b.y0) else {
self.warn("an artboard without valid bounds (its children are kept without clipping)");
return Kind::Unsupported;
};
let corners =
[Point { x: b.x0, y: b.y0 }, Point { x: b.x1, y: b.y0 }, Point { x: b.x1, y: b.y1 }, Point { x: b.x0, y: b.y1 }].map(|p| world.apply(p));
let [a, b2, c, d, ..] = world.0;
if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 {
self.warn("a rotated or flipped artboard (imported at its bounding box)");
self.warn("a rotated or flipped artboard (export bounds are its bounding box; artwork keeps its outline)");
}
let xs = corners.map(|p| p.x);
let ys = corners.map(|p| p.y);
@@ -538,8 +553,17 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
};
let background = paint::fills(self, id, world, b"BFFl");
Kind::Artboard { rect, background }
if ![rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) || rect.x1 <= rect.x0 || rect.y1 <= rect.y0 {
self.warn("an artboard with an invalid transformed size (its children are kept without clipping)");
return Kind::Unsupported;
}
let class = s.class(id).unwrap_or(Tag::of(b"ShpN"));
let (path, even_odd) = crate::geometry::outline(self, id, class, world).unwrap_or_else(|| {
self.warn("an artboard whose outline could not be read (clipped to its rectangle)");
(Path { subpaths: vec![crate::shapes::rectangle(b.x0, b.y0, b.x1, b.y1)] }, false)
});
let (background, strokes) = paint::node_paint(self, id, world);
Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes }
}
}
+1 -1
View File
@@ -129,7 +129,7 @@ const MAX_STOPS: usize = 1024;
fn floats(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Floats(f) => Some(f.clone()),
Value::Bytes(b) if b.len() % 4 == 0 => Some(b.chunks_exact(4).map(|c| f64::from(f32::from_le_bytes([c[0], c[1], c[2], c[3]]))).collect()),
Value::Bytes(b) if b.len() % 4 == 0 => Some(b.as_chunks::<4>().0.iter().map(|c| f64::from(f32::from_le_bytes(*c))).collect()),
_ => None,
}
}
+2 -5
View File
@@ -94,11 +94,8 @@ pub fn preview(bytes: &[u8]) -> Result<Preview<'_>, Error> {
}
image_data = true;
}
b"IEND" => {
if !image_data {
return Err(Error::Malformed("PNG has no image data"));
}
}
b"IEND" if !image_data => return Err(Error::Malformed("PNG has no image data")),
b"IEND" => {}
_ if kind.first().is_some_and(u8::is_ascii_uppercase) => {
return Err(Error::Unsupported("unknown critical PNG chunk"));
}
+175 -4
View File
@@ -13,6 +13,11 @@ const MAX_PIXELS: u64 = 64 << 20;
const TILE: usize = 256;
const TILE_BYTES: usize = TILE * TILE;
struct CachedPixels {
tiles: HashMap<String, Vec<u8>>,
source: Option<(usize, Vec<u8>)>,
}
pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result<Option<Image>, Error> {
let s = r.s;
let Some(bitmap) = s.obj(id, b"Bitm") else {
@@ -53,7 +58,9 @@ pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result<Opt
)
})
.unwrap_or((0, 0, width, height));
if s.field(bitmap, b"Bckg").is_some() && has_tiles && !s.is(id, b"ImgN") {
let source_tiles_only =
(1..=4).all(|c| matches!(s.field(bitmap, &tag(b"Sta", c)), Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|v| *v == Value::UInt(5))));
if s.field(bitmap, b"Bckg").is_some() && has_tiles && !source_tiles_only && !s.is(id, b"ImgN") {
r.warn("edited placed images use their stored pixels");
}
decode(r, bitmap, crop, world)
@@ -118,7 +125,27 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi
}
};
let mut planes = Vec::with_capacity(channels);
let mut cache = HashMap::new();
// Current .af documents can keep level-zero tiles in their embedded JPEG/PNG instead of
// duplicating the pixels. State 5 is checked in the public Patchy embedded-jpeg fixture.
// Support only the observed, same-size RGBA8 image with a zero bitmap origin; other
// representations still receive the existing loss warning rather than guessing a mapping.
let needs_source = (1..=channels).any(|c| matches!(s.field(bitmap, &tag(b"Sta", c)), Some(Value::Array(a)) if a.contains(&Value::UInt(5))));
let source = if needs_source && format == Some(0) && s.int(bitmap, b"LInf") == Some(0) && s.int(bitmap, b"TInf") == Some(0) {
if let Some(name) = s.entry(bitmap, b"Bckg") {
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
match original(r, name).and_then(|bytes| source_pixels(&bytes, width, height)) {
Ok(pixels) => Some((width as usize, pixels)),
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
Err(_) => None,
}
} else {
None
}
} else {
None
};
let mut cache = CachedPixels { tiles: HashMap::new(), source };
for c in 1..=channels {
planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), &mut cache)?);
}
@@ -131,7 +158,7 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi
f64::from(p.get(i).copied().unwrap_or(0)) / 255.0
}
};
for (i, px) in rgba.chunks_exact_mut(4).enumerate() {
for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let v: Vec<f64> = planes.iter().map(|p| sample(p, i)).collect();
let (r2, g, b, a) = if channels == 1 {
(v[0], v[0], v[0], 1.0)
@@ -158,6 +185,39 @@ fn original(r: &mut Reader, name: &str) -> Result<Vec<u8>, Error> {
}
}
/// Decode the source under the same pixel budget as tiled layers, checking its actual
/// dimensions before allocating decoded pixels. Only JPEG and PNG sources are supported.
fn source_pixels(bytes: &[u8], width: u32, height: u32) -> Result<Vec<u8>, Error> {
use image::{ImageFormat, ImageReader};
use std::io::Cursor;
if u64::from(width) * u64::from(height) > MAX_PIXELS {
return Err(Error::Limit("embedded image pixels"));
}
let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| Error::Malformed("embedded image format"))?;
if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png)) {
return Err(Error::Unsupported("embedded source pixel format"));
}
let dimensions = ImageReader::new(Cursor::new(bytes))
.with_guessed_format()
.map_err(|_| Error::Malformed("embedded image format"))?
.into_dimensions()
.map_err(|_| Error::Malformed("embedded image dimensions"))?;
if dimensions != (width, height) || width == 0 || height == 0 {
return Err(Error::Malformed("embedded source and bitmap dimensions differ"));
}
let mut limits = image::Limits::default();
limits.max_image_width = Some(width);
limits.max_image_height = Some(height);
limits.max_alloc = Some(MAX_PIXELS * 8);
reader.limits(limits);
let decoded = reader.decode().map_err(|e| match e {
image::ImageError::Limits(_) => Error::Limit("embedded image decoding"),
_ => Error::Malformed("embedded image decoding"),
})?;
Ok(decoded.into_rgba8().into_raw())
}
fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] {
[prefix[0], prefix[1], prefix[2], b'0' + c as u8]
}
@@ -169,8 +229,9 @@ fn plane(
c: usize,
bps: usize,
(x0, y0, w, h): (u32, u32, u32, u32),
cache: &mut HashMap<String, Vec<u8>>,
cache: &mut CachedPixels,
) -> Result<Vec<u8>, Error> {
let CachedPixels { tiles: cache, source } = cache;
let s = r.s;
let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
@@ -219,6 +280,13 @@ fn plane(
None
}
5 => {
if let Some((source_width, pixels)) = source.as_ref() {
let (ox, oy) = (tx * TILE, ty * TILE);
copy(&mut out, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| {
pixels.get(((oy + y) * source_width + ox + x) * 4 + c - 1).copied().unwrap_or(0)
});
continue;
}
r.warn("pixel layers drawn from an embedded image (left empty)");
None
}
@@ -241,3 +309,106 @@ fn copy(out: &mut [u8], row: usize, (bx0, py0, bx1, py1): (usize, usize, usize,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Kind;
use crate::synth::{self, F, Method, tag};
fn png() -> Vec<u8> {
let pixels = image::RgbaImage::from_fn(300, 2, |x, y| image::Rgba([(x % 251) as u8, (y * 31) as u8, 77, 255]));
let mut bytes = std::io::Cursor::new(Vec::new());
pixels.write_to(&mut bytes, image::ImageFormat::Png).unwrap();
bytes.into_inner()
}
/// An original synthetic mixed source/cache bitmap. It exercises reader recovery,
/// not a claim that Affinity itself accepts the synthetic container.
fn fixture(source: &[u8], origin: i32) -> Vec<u8> {
let mut bitmap = vec![
(tag(b"Frmt"), F::Enum(0, 0)),
(tag(b"BmpW"), F::I32(300)),
(tag(b"BmpH"), F::I32(2)),
(tag(b"LInf"), F::I32(origin)),
(tag(b"TInf"), F::I32(0)),
(tag(b"Bckg"), F::Entry("c/1".into())),
];
for c in 1..=4 {
bitmap.push((tag(&super::tag(b"TWi", c)), F::I32(2)));
bitmap.push((tag(&super::tag(b"THi", c)), F::I32(1)));
bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(vec![5, 4])));
bitmap.push((
tag(&super::tag(b"Idx", c)),
F::Shared(vec![F::Def(c as u32, vec![tag(b"Blck")], vec![(tag(b"Data"), F::Entry(format!("d/{c}")))])]),
));
}
let mut crop = vec![0x17];
crop.extend(tag(b"BitR").0.to_le_bytes());
crop.extend([250i32, 0, 270, 2].into_iter().flat_map(i32::to_le_bytes));
let raster = F::Def(
10,
vec![tag(b"Rstr")],
vec![
(tag(b"Bitm"), F::Obj(tag(b"DyBm"), bitmap)),
(tag(b"BitR"), F::Raw(crop)),
(tag(b"Xfrm"), F::F64s(vec![0.0, -2.0, 10.0, 2.0, 0.0, 20.0])),
],
);
let spread = F::Def(11, vec![tag(b"Sprd")], vec![(tag(b"Chld"), F::Shared(vec![raster]))]);
let doc = synth::stream(&[(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]);
let mut blob = vec![0x2d];
blob.extend(tag(b"Data").0.to_le_bytes());
blob.extend((source.len() as u32).to_le_bytes());
blob.extend(source);
let block = synth::stream(&[(tag(b"Data"), F::Raw(blob))]);
let tiles: Vec<_> = [200u8, 10, 30, 255].into_iter().map(|v| vec![v; TILE_BYTES]).collect();
synth::container(
&[
("doc.dat", &doc, Method::Zlib),
("c/1", &block, Method::Zlib),
("d/1", &tiles[0], Method::Zlib),
("d/2", &tiles[1], Method::Zlib),
("d/3", &tiles[2], Method::Zlib),
("d/4", &tiles[3], Method::Zlib),
],
None,
)
}
#[test]
fn source_tiles_and_cached_edits_survive_crop_rotation_and_tile_boundaries() {
let doc = crate::read(&fixture(&png(), 0), crate::Limits::default()).unwrap();
assert_eq!(doc.warnings, ["edited placed images use their stored pixels"]);
let Kind::Image(image) = &doc.spreads[0].nodes[0].kind else { panic!() };
assert_eq!((image.width, image.height), (20, 2));
assert_eq!(image.transform, Affine([0.0, 2.0, -2.0, 0.0, 10.0, 520.0]));
let Pixels::Rgba8(pixels) = &image.pixels else { panic!() };
for y in 0..2 {
for x in 0..20 {
let expected = if x + 250 < 256 { [((x + 250) % 251) as u8, (y * 31) as u8, 77, 255] } else { [200, 10, 30, 255] };
assert_eq!(&pixels[(y * 20 + x) * 4..(y * 20 + x + 1) * 4], &expected);
}
}
}
#[test]
fn unreadable_sources_and_unknown_origins_preserve_cached_edits_and_warn() {
for bytes in [fixture(b"invalid image", 0), fixture(&png(), 1)] {
let doc = crate::read(&bytes, crate::Limits::default()).unwrap();
assert!(doc.warnings.iter().any(|w| w == "pixel layers drawn from an embedded image (left empty) (4×)"));
let Kind::Image(image) = &doc.spreads[0].nodes[0].kind else { panic!() };
let Pixels::Rgba8(pixels) = &image.pixels else { panic!() };
assert_eq!(&pixels[..4], &[0, 0, 0, 0]);
assert_eq!(&pixels[6 * 4..7 * 4], &[200, 10, 30, 255]);
}
}
#[test]
fn embedded_source_dimensions_and_pixel_budget_are_checked_before_decode() {
let bytes = png();
assert!(matches!(source_pixels(&bytes, 299, 2), Err(Error::Malformed(_))));
assert!(matches!(source_pixels(&bytes, u32::MAX, u32::MAX), Err(Error::Limit(_))));
assert_eq!(source_pixels(&bytes, 300, 2).unwrap().len(), 300 * 2 * 4);
}
}
+14 -6
View File
@@ -115,13 +115,21 @@ pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) ->
}))?
}
b"ShPi" => {
let start = num(r, shape, b"AngS").unwrap_or(0.0);
let mut end = num(r, shape, b"AngE").unwrap_or(TAU);
while end < start {
end += TAU;
}
let raw_start = num(r, shape, b"AngS").unwrap_or(0.0);
let raw_end = num(r, shape, b"AngE").unwrap_or(TAU);
// Normalize in constant time. Repeatedly adding TAU can hang on finite values
// large enough that floating-point addition no longer changes the endpoint.
let start = raw_start.rem_euclid(TAU);
let delta = raw_end - raw_start;
let sweep = if raw_end >= raw_start {
delta.min(TAU)
} else if delta.is_finite() {
delta.rem_euclid(TAU)
} else {
(raw_end.rem_euclid(TAU) - start).rem_euclid(TAU)
};
let inner = num(r, shape, b"IRad").unwrap_or(0.0).clamp(0.0, 1.0);
pie(cx, cy, rx, ry, start, end.min(start + TAU), inner)
pie(cx, cy, rx, ry, start, start + sweep, inner)
}
b"ShpT" => {
let p = num(r, shape, b"Pos ").unwrap_or(0.5);
+201 -30
View File
@@ -3,11 +3,13 @@
//! OpenType features) is left to the importing application.
use crate::model::{Affine, Align, Point, Reader, Text, TextRun, rect};
use crate::paint::{self, Paint};
use crate::paint::{self, Color, Paint};
use crate::stream::{ObjId, Value};
/// Characters read per text node (stories are split into blocks; this caps hostile ones).
const MAX_CHARS: usize = 1 << 20;
/// Shared character attributes must not amplify into unbounded font/feature/gradient data.
const MAX_ATTRIBUTE_BYTES: usize = 16 << 20;
pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
let s = r.s;
@@ -19,46 +21,76 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
let mut align = None;
let mut total = 0usize;
let mut placeholders = false;
let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES);
for block in s.objs(story, b"Blok") {
let glyphs = s.obj(block, b"Glyp")?;
let chars: Vec<char> = match s.str(glyphs, b"Utf8") {
Some(t) => t.chars().collect(),
let Some(glyphs) = s.obj(block, b"Glyp") else {
r.warn("a text block without readable characters (left out)");
continue;
};
// Bound collection itself, including placeholders, before allocating the character buffer.
let budget = MAX_CHARS - total;
let mut chars: Vec<char> = match s.str(glyphs, b"Utf8") {
Some(t) => t.chars().take(budget + 1).collect(),
None => {
// Inline objects (page numbers, anchors) each take one index before the segment text.
let segments = s.objs(glyphs, b"Mixd");
if segments.is_empty() {
r.warn("a text block without readable characters (left out)");
continue;
}
let mut v = Vec::new();
for seg in s.objs(glyphs, b"Mixd") {
for seg in segments {
let inline = s.objs(seg, b"Glys").len();
v.extend(std::iter::repeat_n('\u{FFFC}', inline));
v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(budget + 1 - v.len())));
placeholders |= inline > 0;
v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars());
v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(budget + 1 - v.len()));
if v.len() > budget {
break;
}
}
v
}
};
total = total.checked_add(chars.len())?;
if total > MAX_CHARS {
let truncated = chars.len() > budget;
if truncated {
chars.truncate(budget);
r.warn("text longer than a million characters (truncated)");
break;
}
total += chars.len();
let mut start = 0usize;
for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
let end = usize::try_from(s.int(run, b"Indx")?).ok()?.min(chars.len());
let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else {
r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
continue;
};
let end = index.min(chars.len());
if index > chars.len() || end < start {
r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
}
if end <= start {
continue;
}
let text: String = chars.get(start..end)?.iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect();
let text = characters(&chars, start, end);
start = end;
let Some(attrs) = s.obj(run, b"Item") else { continue };
if !text.is_empty() {
runs.push(run_attrs(r, attrs, text, world));
push_run(r, &mut runs, s.obj(run, b"Item"), text, world, &mut attribute_budget);
}
if start < chars.len() {
let text = characters(&chars, start, chars.len());
push_run(r, &mut runs, None, text, world, &mut attribute_budget);
}
for paragraph in s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() {
if let Some(attrs) = s.obj(paragraph, b"Item") {
let paragraph = paragraph_align(r, attrs);
match align {
None => align = Some(paragraph),
Some(first) if first != paragraph => r.warn("mixed paragraph alignments (the first alignment is used)"),
_ => {}
}
}
}
if align.is_none() {
align = s
.obj(block, b"PAtt")
.and_then(|p| s.objs(p, b"Runs").first().copied())
.and_then(|run| s.obj(run, b"Item"))
.map(|p| paragraph_align(r, p));
if truncated {
break;
}
}
if placeholders {
@@ -82,6 +114,39 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world })
}
fn characters(chars: &[char], start: usize, end: usize) -> String {
chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect()
}
fn push_run(r: &mut Reader, runs: &mut Vec<TextRun>, attrs: Option<ObjId>, text: String, world: Affine, attribute_budget: &mut Option<usize>) {
if text.is_empty() {
return;
}
let run = match attrs {
Some(attrs) if attribute_budget.is_some() => run_attrs(r, attrs, text, world, attribute_budget),
_ => {
// This is a recovery policy, not an assertion about unspecified Affinity attributes.
if attrs.is_none() {
r.warn("text without character attributes (characters preserved with default attributes)");
}
TextRun {
text,
postscript: String::new(),
family: String::new(),
weight: 400,
italic: false,
features: Vec::new(),
all_caps: false,
size: 12.0 * r.dpi / 72.0,
tracking: 0.0,
leading: None,
fill: Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }),
}
}
};
runs.push(run);
}
fn slot<T: Copy>(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option<T>) -> Option<T> {
match v? {
Value::Array(a) => a.get(i).and_then(f),
@@ -104,7 +169,7 @@ fn int(v: &Value) -> Option<i64> {
}
}
fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine) -> TextRun {
fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribute_budget: &mut Option<usize>) -> TextRun {
let s = r.s;
let doubles = s.field(attrs, b"Doub");
let ints = s.field(attrs, b"Ints");
@@ -112,24 +177,67 @@ fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine) -> TextR
let tracking = slot(doubles, 4, float).unwrap_or(0.0);
let leading = (slot(ints, 4, int) == Some(1)).then(|| slot(doubles, 13, float)).flatten().filter(|v| *v > 0.0);
let objects = match s.field(attrs, b"Objs") {
Some(Value::Array(a)) => a.iter().map(|v| if let Value::Obj(o) = v { *o } else { None }).collect(),
Some(Value::Array(a)) => a.iter().take(8).map(|v| if let Value::Obj(o) = v { *o } else { None }).collect(),
_ => Vec::new(),
};
let fill = objects.first().copied().flatten().and_then(|f| paint::descriptor(r, f, world)).unwrap_or(Paint::None);
if objects.get(1).copied().flatten().and_then(|f| paint::descriptor(r, f, world)).is_some_and(|p| p != Paint::None) {
let mut fill = match objects.first().copied().flatten().and_then(|f| paint::descriptor(r, f, world)) {
Some(fill) => fill,
None => {
r.warn("text without readable fill attributes (default black used)");
Paint::Solid(Color::Gray { v: 0.0, a: 1.0 })
}
};
// A single descriptor decode is bounded by paint::MAX_STOPS. Charge its owned stop data
// before keeping it; subsequent runs skip attribute decoding once the budget is exhausted.
if let Paint::Gradient(gradient) = &fill {
let bytes = gradient.stops.len().saturating_mul(std::mem::size_of::<paint::Stop>());
if !charge_attributes(r, attribute_budget, bytes) {
fill = Paint::Solid(Color::Gray { v: 0.0, a: 1.0 });
}
}
if attribute_budget.is_some() && objects.get(1).copied().flatten().and_then(|f| paint::descriptor(r, f, world)).is_some_and(|p| p != Paint::None)
{
r.warn("outlined (stroked) text");
}
if slot(doubles, 10, float).is_some_and(|h| (h - 1.0).abs() > 1e-3) {
r.warn("horizontally scaled text");
}
let font = s.obj(attrs, b"DFnt");
let get = |tag: &[u8; 4]| font.and_then(|f| s.str(f, tag)).unwrap_or_default().to_string();
// A resolved font is populated on the emoji run of the public Affinity 3 text-runs file
// (Courier New requested, Segoe UI Emoji stored in RFnt). Empty RFnt records are common.
// Source: https://github.com/SethRobinson/Patchy/tree/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af
let requested = s.obj(attrs, b"DFnt");
let resolved =
s.obj(attrs, b"RFnt").filter(|f| !s.str(*f, b"Famy").unwrap_or_default().is_empty() || !s.str(*f, b"Post").unwrap_or_default().is_empty());
let font = resolved.or(requested);
if let Some(resolved) = resolved {
let differs = [b"Famy", b"Post"]
.iter()
.any(|tag| s.str(resolved, tag).unwrap_or_default() != requested.and_then(|f| s.str(f, tag)).unwrap_or_default());
if differs {
r.warn("text uses a stored fallback font (imported with that font)");
}
}
if font.and_then(|f| s.int(f, b"Widh")).is_some_and(|w| w != 5) {
r.warn("font width variants (exact face depends on the installed PostScript font)");
}
let postscript = metadata_string(r, attribute_budget, font.and_then(|f| s.str(f, b"Post")).unwrap_or_default());
let family = metadata_string(r, attribute_budget, font.and_then(|f| s.str(f, b"Famy")).unwrap_or_default());
let (features, all_caps) = font_features(r, objects.get(7).copied().flatten(), attribute_budget);
let weight = font.and_then(|f| s.int(f, b"Wegt")).unwrap_or(400);
let weight = if (1..=1000).contains(&weight) {
weight
} else {
r.warn("invalid font weight (imported as regular)");
400
};
TextRun {
text,
postscript: get(b"Post"),
family: get(b"Famy"),
weight: font.and_then(|f| s.int(f, b"Wegt")).unwrap_or(400),
postscript,
family,
weight,
italic: font.and_then(|f| s.bool(f, b"Ital")).unwrap_or(false),
features,
all_caps,
size,
tracking,
leading,
@@ -137,7 +245,70 @@ fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine) -> TextR
}
}
fn charge_attributes(r: &mut Reader, budget: &mut Option<usize>, bytes: usize) -> bool {
let Some(remaining) = *budget else { return false };
match remaining.checked_sub(bytes) {
Some(remaining) => {
*budget = Some(remaining);
true
}
None => {
*budget = None;
r.warn("text attribute budget exceeded (excess font names, features and gradients left out)");
false
}
}
}
fn metadata_string(r: &mut Reader, budget: &mut Option<usize>, value: &str) -> String {
let bytes = value.len().saturating_add(std::mem::size_of::<String>());
if value.is_empty() || !charge_attributes(r, budget, bytes) { String::new() } else { value.to_owned() }
}
/// The public Affinity 3 caps fixture stores `smcp` and the private `CAP\x01` selector in
/// OtAt/Setn. Only the observed all-caps selector and boolean OpenType tags are mapped; other
/// values are reported, never guessed. Standard tag syntax: https://learn.microsoft.com/en-us/typography/opentype/spec/featuretags
fn font_features(r: &mut Reader, attrs: Option<ObjId>, attribute_budget: &mut Option<usize>) -> (Vec<String>, bool) {
let mut features = Vec::new();
let mut all_caps = false;
if attribute_budget.is_none() {
return (features, all_caps);
}
let s = r.s;
let Some(Value::Array(settings)) = attrs.and_then(|a| s.field(a, b"Setn")) else { return (features, all_caps) };
for (index, setting) in settings.iter().take(257).enumerate() {
if index == 256 {
r.warn("more than 256 text feature settings (truncated)");
break;
}
let Value::Obj(Some(setting)) = setting else {
r.warn("unreadable text feature settings (imported with defaults)");
continue;
};
let setting = *setting;
let tag = s.int(setting, b"Feat").and_then(|v| u32::try_from(v).ok()).map(u32::to_be_bytes);
let value = r.s.int(setting, b"Valu");
match (tag, value) {
(Some([b'C', b'A', b'P', 1]), Some(0 | 1)) => all_caps = value == Some(1),
(Some(tag), Some(value @ (0 | 1))) if tag.iter().all(u8::is_ascii_alphanumeric) => {
if !charge_attributes(r, attribute_budget, std::mem::size_of::<String>() + if value == 0 { 5 } else { 4 }) {
break;
}
let name = String::from_utf8_lossy(&tag);
features.push(if value == 0 { format!("-{name}") } else { name.into_owned() });
}
_ => r.warn("text feature selectors or non-boolean OpenType settings (imported with defaults)"),
}
}
(features, all_caps)
}
fn paragraph_align(r: &mut Reader, p: ObjId) -> Align {
// Nonzero offsets in these slots are present in the public text-indent and text-para-spacing
// fixtures. Their layout is not represented by this importer; retain text and report the gap.
if (1..=6).any(|i| slot(r.s.field(p, b"Doub"), i, float).is_some_and(|v| v.abs() > 1e-9)) {
r.warn("paragraph indents or spacing (imported with defaults)");
}
match slot(r.s.field(p, b"Ints"), 0, int) {
Some(1) => Align::Center,
Some(2) => Align::Right,
+168
View File
@@ -0,0 +1,168 @@
//! Original synthetic graph tests for bounded `.af` outline expansion. These model the reader's
//! accepted schema, without using Affinity software, third-party parser code or external assets.
#![cfg(feature = "synth")]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use vectorcraft_affinity::{
Document, Limits,
model::{Kind, Path, Point},
synth::{self, F, Method, tag},
};
fn compound(id: u32, children: Vec<F>) -> F {
F::Def(id, vec![tag(b"Comp")], vec![(tag(b"Chld"), F::Shared(children))])
}
fn shape(id: u32, class: &[u8; 4], parameters: Vec<(vectorcraft_affinity::stream::Tag, F)>) -> F {
F::Def(
id,
vec![tag(b"ShpN")],
vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 10.0, 20.0])), (tag(b"Shpe"), F::Def(id + 10_000, vec![tag(class)], parameters))],
)
}
fn read(definitions: Vec<F>, top: u32) -> Document {
let data = synth::stream(&[
(tag(b"Defs"), F::Shared(definitions)),
(
tag(b"DocR"),
F::Def(
1,
vec![tag(b"DocN")],
vec![(
tag(b"Chld"),
F::Shared(vec![F::Def(
2,
vec![tag(b"Sprd")],
vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(vec![F::Ref(top)]))],
)]),
)],
),
),
]);
let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None);
vectorcraft_affinity::read(&bytes, Limits::default()).unwrap()
}
fn path(document: &Document) -> &Path {
match &document.spreads[0].nodes[0].kind {
Kind::Shape { path, .. } => path,
other => panic!("expected shape, got {other:?}"),
}
}
fn rejected(document: &Document, warning: &str) {
assert!(matches!(document.spreads[0].nodes[0].kind, Kind::Unsupported));
assert!(document.warnings.iter().any(|value| value.contains(warning)), "{:?}", document.warnings);
}
#[test]
fn self_cycle_and_mutual_cycle_discard_the_entire_compound() {
// A valid first operand ensures a malformed later operand cannot leave a plausible partial path.
let rectangle = shape(100, b"ShNR", vec![]);
let self_cycle = compound(101, vec![F::Ref(100), F::Ref(101)]);
rejected(&read(vec![rectangle.clone(), self_cycle], 101), "compound outline that contains itself");
let mutual_cycle = compound(101, vec![F::Ref(100), compound(102, vec![F::Ref(101)])]);
rejected(&read(vec![rectangle, mutual_cycle], 101), "compound outline that contains itself");
}
#[test]
fn deep_reference_chain_is_bounded_independently_of_stream_nesting() {
let mut definitions = vec![shape(100, b"ShNR", vec![])];
for id in 101..=250 {
definitions.push(compound(id, vec![F::Ref(id - 1)]));
}
rejected(&read(definitions, 250), "compound outlines nested deeper than 128 levels");
}
#[test]
fn outline_at_the_depth_limit_is_still_imported() {
let mut definitions = vec![shape(100, b"ShNR", vec![])];
for id in 101..=227 {
definitions.push(compound(id, vec![F::Ref(id - 1)]));
}
let document = read(definitions, 227);
assert!(document.warnings.is_empty(), "{:?}", document.warnings);
assert_eq!(path(&document).subpaths.len(), 1);
assert_eq!(path(&document).subpaths[0].segments.len(), 3);
}
#[test]
fn excessive_declared_curve_count_is_rejected_before_expansion() {
let curve = F::Def(
100,
vec![tag(b"PCrv")],
vec![(tag(b"Crvs"), F::Def(101, vec![tag(b"PCvD")], vec![(tag(b"Data"), F::Pos(vec![F::U8(0), F::U32(u32::MAX)]))]))],
);
rejected(&read(vec![curve], 100), "compound outlines exceeding the geometry work limit");
}
#[test]
fn empty_shared_fanout_cannot_bypass_the_operand_visit_limit() {
// Only 21 on-disk objects, but an unbounded traversal would visit over two million operands.
let mut definitions = vec![compound(100, vec![])];
for id in 101..=120 {
definitions.push(compound(id, vec![F::Ref(id - 1), F::Ref(id - 1)]));
}
rejected(&read(definitions, 120), "compound outlines exceeding the operand visit limit");
}
#[test]
fn shared_large_operands_are_charged_for_cumulative_geometry_work() {
// A small reference graph expands a 20,000-segment star. Count work across every reuse and
// transform, rather than permitting each individual operand's allocation limit repeatedly.
let mut definitions = vec![shape(100, b"ShSt", vec![(tag(b"Pnts"), F::I32(10_000))])];
for id in 101..=112 {
definitions.push(compound(id, vec![F::Ref(id - 1), F::Ref(id - 1)]));
}
rejected(&read(definitions, 112), "compound outlines exceeding the geometry work limit");
}
#[test]
fn ordinary_nested_compound_preserves_repeated_operands_and_transforms() {
let mut rectangle = shape(100, b"ShNR", vec![]);
if let F::Def(_, _, fields) = &mut rectangle {
fields.push((tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 3.0, 0.0, 1.0, 7.0])));
}
let inner = compound(101, vec![F::Ref(100), F::Ref(100)]);
let mut outer = compound(102, vec![F::Ref(101)]);
if let F::Def(_, _, fields) = &mut outer {
fields.push((tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 100.0, 0.0, 1.0, 200.0])));
}
let document = read(vec![rectangle, inner, outer], 102);
assert!(document.warnings.is_empty(), "{:?}", document.warnings);
let path = path(&document);
assert_eq!(path.subpaths.len(), 2);
assert_eq!(path.subpaths[0], path.subpaths[1]);
assert_eq!(path.subpaths[0].start, Point { x: 103.0, y: 207.0 });
assert_eq!(path.subpaths[0].segments.last().unwrap()[2], Point { x: 103.0, y: 227.0 });
}
#[test]
fn overflowing_compound_transform_is_reported_before_processing_geometry() {
let mut child = shape(100, b"ShNR", vec![]);
if let F::Def(_, _, fields) = &mut child {
fields.push((tag(b"Xfrm"), F::F64s(vec![1.0e308, 0.0, 0.0, 0.0, 1.0, 0.0])));
}
let mut outer = compound(101, vec![F::Ref(100)]);
if let F::Def(_, _, fields) = &mut outer {
fields.push((tag(b"Xfrm"), F::F64s(vec![1.0e308, 0.0, 0.0, 0.0, 1.0, 0.0])));
}
rejected(&read(vec![child, outer], 101), "compound operand with an invalid transform");
}
#[test]
fn pie_angles_with_huge_finite_values_do_not_loop_or_emit_nonfinite_points() {
let document = read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(1.0e308)), (tag(b"AngE"), F::F64(-1.0e308))])], 100);
for subpath in &path(&document).subpaths {
assert!(subpath.start.x.is_finite() && subpath.start.y.is_finite());
assert!(subpath.segments.len() <= 20);
assert!(subpath.segments.iter().flatten().all(|point| point.x.is_finite() && point.y.is_finite()));
}
}
#[test]
fn wrapped_pie_angles_keep_the_same_geometry_as_the_positive_span() {
let make = |end| read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(0.0)), (tag(b"AngE"), F::F64(end))])], 100);
assert_eq!(path(&make(-std::f64::consts::FRAC_PI_2)), path(&make(3.0 * std::f64::consts::FRAC_PI_2)));
}
+116
View File
@@ -0,0 +1,116 @@
//! Pixel retention on current Affinity 3 documents published under MIT by Patchy.
//! Assertions use this reader's archive/stream and the original embedded image bytes;
//! no third-party Affinity parser, source code or application is used as an oracle.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use vectorcraft_affinity::{
Archive, Limits,
model::{Affine, Document, Image, Kind, Node, Pixels},
stream,
};
#[path = "support/corpus.rs"]
mod corpus;
fn images(nodes: &[Node], out: &mut Vec<Image>) {
for node in nodes {
if let Kind::Image(image) = &node.kind {
out.push(image.clone());
}
images(&node.children, out);
}
}
fn read_fixture(name: &str) -> Option<(Vec<u8>, Document, Vec<Image>)> {
let dir = corpus::pinned()?;
let bytes = std::fs::read(dir.join(name)).unwrap();
let doc = vectorcraft_affinity::read(&bytes, Limits::default()).unwrap();
assert!(doc.saved_by.as_deref().unwrap().starts_with("Affinity 3."));
let mut out = Vec::new();
for spread in &doc.spreads {
images(&spread.nodes, &mut out);
}
Some((bytes, doc, out))
}
fn source(bytes: &[u8]) -> Vec<u8> {
let mut archive = Archive::open(bytes, Limits::default()).unwrap();
let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap();
let bitmap =
doc.objects.iter().enumerate().find(|(_, o)| o.class == stream::Tag::of(b"DyBm") && o.get(stream::Tag::of(b"Bckg")).is_some()).unwrap().0;
let name = doc.entry(bitmap, b"Bckg").unwrap();
let block = stream::parse(&archive.read(name).unwrap()).unwrap();
block.bytes(block.root, b"Data").unwrap().to_vec()
}
#[test]
fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
let Some((bytes, doc, images)) = read_fixture("patchy-embedded-jpeg.af") else { return };
assert!(doc.warnings.is_empty(), "{:?}", doc.warnings);
assert_eq!(images.len(), 1);
let image = &images[0];
assert_eq!((image.width, image.height), (400, 300));
assert_eq!(image.transform, Affine::IDENTITY);
let Pixels::Rgba8(pixels) = &image.pixels else { panic!("expected retained level-zero pixels") };
let expected = image::load_from_memory(&source(&bytes)).unwrap().into_rgba8();
assert_eq!(pixels.as_slice(), expected.as_raw());
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
}
#[test]
fn lazy_placed_images_keep_the_original_encoded_bytes() {
let Some((bytes, doc, images)) = read_fixture("patchy-lazy-placed.af") else { return };
assert!(doc.warnings.is_empty());
assert_eq!(images.len(), 1);
assert_eq!((images[0].width, images[0].height), (400, 300));
assert_eq!(images[0].transform, Affine::IDENTITY);
assert_eq!(images[0].pixels, Pixels::Encoded(source(&bytes)));
}
#[test]
fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
let Some((_, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
let (_, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
assert!(doc8.warnings.is_empty());
assert!(doc16.warnings.is_empty());
assert_eq!(images8.len(), 1);
assert_eq!(images16, images8);
assert_eq!((images8[0].width, images8[0].height), (64, 48));
let Pixels::Rgba8(pixels) = &images8[0].pixels else { panic!() };
assert_eq!(pixels.len(), 64 * 48 * 4);
assert_eq!(&pixels[..4], &[0, 0, 0, 128]);
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] < 255));
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
// Frozen pixel-retention baseline, including every alpha sample. It is not a render oracle.
assert_eq!(crc32fast::hash(pixels), 0xc8ee4dc1);
}
#[test]
fn rotated_scaled_pixels_keep_the_full_affine_transform() {
let Some((_, doc, images)) = read_fixture("patchy-transform.af") else { return };
assert!(doc.warnings.is_empty());
assert_eq!(images.len(), 1);
assert_eq!((images[0].width, images[0].height), (80, 60));
let expected = [1.1742158910592235, 0.4286222593193142, -0.4286222593193142, 1.1742158910592235, 60.0, 40.0];
for (actual, expected) in images[0].transform.0.into_iter().zip(expected) {
assert!((actual - expected).abs() < 1e-12);
}
let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() };
assert_eq!(pixels.len(), 80 * 60 * 4);
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
assert_eq!(crc32fast::hash(pixels), 0x3720a442);
}
#[test]
fn cmyk_and_lab_losses_are_reported() {
let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
assert_eq!(images.len(), 1);
assert_eq!((images[0].width, images[0].height), (64, 48));
let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() };
assert_eq!(crc32fast::hash(pixels), 0x5872bb76);
assert_eq!(cmyk.warnings, ["CMYK pixel layers (converted to RGB without the document's colour profile)"]);
let (_, lab, images) = read_fixture("patchy-lab.af").unwrap();
assert!(images.is_empty());
assert_eq!(lab.warnings, ["pixel layers in grey, Lab or 32-bit formats"]);
}
+41 -9
View File
@@ -1,28 +1,32 @@
//! Public Affinity documents: the pinned set `cargo xtask corpus --affinity` fetches into
//! `corpus/affinity`, or any folder of `.af`/`.afdesign`/`.afphoto`/`.afpub` files named by
//! `AFFINITY_SAMPLES` (searched recursively). Without either, these tests do nothing.
//! `AFFINITY_SAMPLES` (searched recursively). CI requires a complete, checksum-verified pinned
//! corpus via `AFFINITY_CORPUS_REQUIRED=1`; ordinary local runs may skip an absent corpus.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::{Path, PathBuf};
use vectorcraft_affinity::{Archive, Limits, stream};
#[path = "support/corpus.rs"]
mod corpus;
#[path = "support/features.rs"]
mod features;
fn files(dir: &Path, out: &mut Vec<PathBuf>) {
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let p = e.path();
if p.is_dir() {
files(&p, out);
} else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["af", "afdesign", "afphoto", "afpub", "aftemplate"].contains(&e))
&& std::fs::read(&p).is_ok_and(|b| b.starts_with(vectorcraft_affinity::MAGIC))
{
} else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["af", "afdesign", "afphoto", "afpub", "aftemplate"].contains(&e)) {
out.push(p);
}
}
}
fn samples() -> Option<PathBuf> {
let pinned = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/affinity");
std::env::var_os("AFFINITY_SAMPLES").map(PathBuf::from).or_else(|| pinned.join("SOURCES.md").exists().then_some(pinned))
let pinned = corpus::pinned();
std::env::var_os("AFFINITY_SAMPLES").map(PathBuf::from).or(pinned)
}
#[test]
@@ -52,6 +56,7 @@ fn public_documents_map_to_the_model() {
let Some(dir) = samples() else { return };
let mut paths = Vec::new();
files(&dir, &mut paths);
assert!(!paths.is_empty(), "no Affinity documents under {dir:?}");
let mut warnings = std::collections::BTreeMap::<String, usize>::new();
let mut failures = Vec::new();
let (mut nodes, mut docs) = (0usize, 0usize);
@@ -60,9 +65,6 @@ fn public_documents_map_to_the_model() {
}
for p in &paths {
let bytes = std::fs::read(p).unwrap();
if !bytes.starts_with(vectorcraft_affinity::MAGIC) {
continue;
}
match vectorcraft_affinity::read(&bytes, Limits::default()) {
Ok(d) => {
docs += 1;
@@ -81,3 +83,33 @@ fn public_documents_map_to_the_model() {
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// Measured structural baselines for actual Affinity 3 files. Unlike a parse-success test,
/// this detects disappearing nodes, curves, runs, font names, artboards and loss warnings.
/// It does not claim that an unsupported feature is faithfully rendered.
#[test]
fn affinity3_feature_retention_matches_pinned_signatures() {
let Some(dir) = corpus::pinned() else { return };
let expected = include_str!("support/affinity3-signatures.txt");
let mut checked = std::collections::BTreeSet::new();
for line in expected.lines().filter(|l| !l.starts_with('#') && !l.is_empty()) {
let (name, signature) = line.split_once('\t').expect("signature row must have a tab");
assert!(checked.insert(name), "duplicate fixture {name}");
let bytes = std::fs::read(dir.join(name)).unwrap();
let doc = vectorcraft_affinity::read(&bytes, Limits::default()).unwrap();
assert_eq!(
features::signature(&doc),
signature,
"{name}: imported feature retention changed; review the pinned input and warning changes before updating this baseline"
);
assert!(
doc.saved_by.as_deref().is_some_and(|v| v.starts_with("Affinity 3.")),
"{name}: expected an actual Affinity 3 document, got {:?}",
doc.saved_by
);
}
let manifest = include_str!("../../../xtask/affinity-corpus.sha256");
let af_names: std::collections::BTreeSet<_> =
manifest.lines().filter_map(|l| l.split_once(" ")).map(|(_, n)| n).filter(|n| n.ends_with(".af")).collect();
assert_eq!(checked, af_names, "every pinned .af file needs a reviewed structural baseline");
}
@@ -0,0 +1,33 @@
affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=df3c417b;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (114×)", "layer effects (shadows, glows, outlines, bevels…) (156×)"]
affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=d0387de4;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 559, "subpaths": 881};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (545×)", "layer effects (shadows, glows, outlines, bevels…) (245×)"]
affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=b966f693;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (54×)", "layer effects (shadows, glows, outlines, bevels…) (278×)"]
affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=ac448123;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 288, "subpaths": 656};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes)", "layer effects (shadows, glows, outlines, bevels…) (339×)"]
patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=10a37502;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=c65409b4;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
patchy-artboards.af dpi=72;spreads=1;model_crc32=f1ae5644;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=f6691ff9;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
patchy-cmyk.af dpi=72;spreads=1;model_crc32=5145b5a1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=["CMYK pixel layers (converted to RGB without the document's colour profile)"]
patchy-dpi300.af dpi=300;spreads=1;model_crc32=0c23e7c8;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=090c674b;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-fx-blur.af dpi=72;spreads=1;model_crc32=3f1b8b44;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (2×)"]
patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=e868c992;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (3×)"]
patchy-fx.af dpi=72;spreads=1;model_crc32=5a1c34ac;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (5×)"]
patchy-group.af dpi=72;spreads=1;model_crc32=c217ab38;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=63ad778e;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…)"]
patchy-lab.af dpi=72;spreads=1;model_crc32=01e8a926;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=9ce9937e;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-live-filter.af dpi=72;spreads=1;model_crc32=30c5f8ee;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
patchy-rgba16.af dpi=72;spreads=1;model_crc32=1bb23571;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-rgba8.af dpi=72;spreads=1;model_crc32=1bb23571;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-shapes-2.af dpi=72;spreads=1;model_crc32=7828d3cd;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 62, "shapes": 12, "strokes": 0, "subpaths": 12};boards=[];fonts={};warnings=["cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse) (9×)"]
patchy-shapes.af dpi=72;spreads=1;model_crc32=e127e129;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 29, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=["rectangles with straight, concave or other corner types (imported with round corners)"]
patchy-text-artistic.af dpi=72;spreads=1;model_crc32=b6137f6e;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
patchy-text-caps.af dpi=72;spreads=1;model_crc32=b5527e72;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
patchy-text-frame.af dpi=72;spreads=1;model_crc32=7a2cd32d;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=["paragraph indents or spacing (imported with defaults)"]
patchy-text-indent.af dpi=72;spreads=1;model_crc32=30ee834c;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)", "paragraph indents or spacing (imported with defaults) (2×)"]
patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=3d580ad2;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "paragraph indents or spacing (imported with defaults)"]
patchy-text-rotated.af dpi=72;spreads=1;model_crc32=ad77772a;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
patchy-text-runs.af dpi=72;spreads=1;model_crc32=a8da3052;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "paragraph indents or spacing (imported with defaults)", "text uses a stored fallback font (imported with that font)"]
patchy-transform.af dpi=72;spreads=1;model_crc32=f8807611;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-vector-mask.af dpi=72;spreads=1;model_crc32=1851fd90;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
patchy-vector.af dpi=72;spreads=1;model_crc32=b89a91d3;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
+30
View File
@@ -0,0 +1,30 @@
//! Shared pinned corpus gate: an installed corpus must be complete and unmodified.
#![allow(dead_code)]
use std::path::PathBuf;
#[path = "../../../../xtask/src/sha256.rs"]
mod sha256;
pub fn pinned() -> Option<PathBuf> {
// This helper is compiled in both affinity and engine integration tests.
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/affinity");
let required = std::env::var_os("AFFINITY_CORPUS_REQUIRED").is_some_and(|v| v != "0");
if !dir.exists() {
assert!(!required, "required Affinity corpus absent: run `cargo xtask corpus --affinity`");
eprintln!("Affinity corpus absent: run `cargo xtask corpus --affinity` (CI sets AFFINITY_CORPUS_REQUIRED=1)");
return None;
}
assert!(dir.join("SOURCES.md").is_file(), "incomplete Affinity corpus: missing SOURCES.md; run `cargo xtask corpus --affinity`");
let manifest = include_str!("../../../../xtask/affinity-corpus.sha256");
let mut count = 0;
for line in manifest.lines().filter(|l| !l.trim().is_empty()) {
let (digest, name) = line.split_once(" ").expect("malformed pinned Affinity SHA256 manifest");
assert_eq!(digest.len(), 64, "invalid SHA256 for {name}");
let bytes = std::fs::read(dir.join(name)).unwrap_or_else(|e| panic!("missing pinned Affinity file {name}: {e}"));
assert_eq!(sha256::hex(&bytes), digest, "{name}: pinned corpus modified; run `cargo xtask corpus --affinity`");
count += 1;
}
assert!(count >= 4, "pinned Affinity manifest must include the four Affinity 3 .af fixtures");
Some(dir)
}
+63
View File
@@ -0,0 +1,63 @@
//! Structural regression signatures, measured from the pinned files through our own reader.
//! These freeze feature retention; they are not independent visual or compatibility oracles.
//! The model CRC covers every decoded field via its Debug representation (including paths,
//! paint, masks, image pixels and text runs). A deliberate reader/Debug change needs review;
//! input authenticity is independently checked with SHA256 by the corpus gate.
use std::collections::{BTreeMap, BTreeSet};
use vectorcraft_affinity::model::{Document, Kind, Node};
use vectorcraft_affinity::paint::Paint;
pub fn signature(doc: &Document) -> String {
fn visit(nodes: &[Node], counts: &mut BTreeMap<&'static str, usize>, fonts: &mut BTreeSet<String>, boards: &mut Vec<String>, depth: usize) {
for n in nodes {
*counts.entry("nodes").or_default() += 1;
counts.entry("depth").and_modify(|v| *v = (*v).max(depth)).or_insert(depth);
let key = match &n.kind {
Kind::Layer => "layers",
Kind::Group => "groups",
Kind::Artboard { rect, .. } => {
boards.push(format!("{}:{:.4},{:.4},{:.4},{:.4}", n.name, rect.x0, rect.y0, rect.x1, rect.y1));
"artboards"
}
Kind::Shape { path, fills, strokes, .. } => {
*counts.entry("subpaths").or_default() += path.subpaths.len();
*counts.entry("segments").or_default() += path.subpaths.iter().map(|p| p.segments.len()).sum::<usize>();
*counts.entry("fills").or_default() += fills.len();
*counts.entry("strokes").or_default() += strokes.len();
*counts.entry("gradients").or_default() += fills.iter().filter(|p| matches!(p, Paint::Gradient(_))).count();
"shapes"
}
Kind::Text(t) => {
*counts.entry("text_runs").or_default() += t.runs.len();
*counts.entry("text_chars").or_default() += t.runs.iter().map(|r| r.text.chars().count()).sum::<usize>();
for r in &t.runs {
fonts.insert(format!("{}:{}:{}:{}", r.family, r.postscript, r.weight, r.italic));
}
"texts"
}
Kind::Image(_) => "images",
Kind::Unsupported => "unsupported",
};
*counts.entry(key).or_default() += 1;
for (key, yes) in
[("hidden", !n.visible), ("vector_masks", n.mask.is_some()), ("pixel_masks", n.pixel_mask.is_some()), ("opacity", n.opacity < 1.0)]
{
if yes {
*counts.entry(key).or_default() += 1;
}
}
visit(&n.children, counts, fonts, boards, depth + 1);
}
}
let (mut counts, mut fonts, mut boards) = (BTreeMap::new(), BTreeSet::new(), Vec::new());
for spread in &doc.spreads {
visit(&spread.nodes, &mut counts, &mut fonts, &mut boards, 1);
}
let model_crc32 = crc32fast::hash(format!("{:?}", doc.spreads).as_bytes());
format!(
"dpi={};spreads={};model_crc32={model_crc32:08x};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}",
doc.dpi,
doc.spreads.len(),
doc.warnings
)
}
@@ -0,0 +1,170 @@
//! Original synthetic reader fixtures, shared by native and engine regression tests.
//! These describe the reader's existing schema; no Affinity software or third-party parser was
//! used to create them. They prove recovery/mapping behavior, not Affinity's layout or exporter.
#![allow(dead_code)]
use vectorcraft_affinity::synth::{self, F, Method, tag};
pub fn array_f64(field: &[u8; 4], values: &[f64]) -> F {
let mut bytes = vec![0x8a];
bytes.extend(tag(field).0.to_le_bytes());
bytes.extend((values.len() as u32).to_le_bytes());
bytes.extend(values.iter().flat_map(|v| v.to_le_bytes()));
F::Raw(bytes)
}
pub fn array_i32(field: &[u8; 4], values: &[i32]) -> F {
let mut bytes = vec![0x87];
bytes.extend(tag(field).0.to_le_bytes());
bytes.extend((values.len() as u32).to_le_bytes());
bytes.extend(values.iter().flat_map(|v| v.to_le_bytes()));
F::Raw(bytes)
}
pub fn solid(alpha: f32) -> F {
F::Obj(
tag(b"FilS"),
vec![(
tag(b"Colr"),
F::Obj(tag(b"RGBA"), vec![(tag(b"_col"), F::Struct([0.2f32, 0.4, 0.6, alpha].iter().flat_map(|v| v.to_le_bytes()).collect()))]),
)],
)
}
pub fn attrs(family: &str, postscript: &str, weight: i32, italic: bool, size: f64) -> F {
let mut doubles = vec![0.0; 14];
doubles[0] = size;
doubles[4] = 0.025;
doubles[10] = 1.0;
doubles[13] = 30.0;
F::Obj(
tag(b"GAtt"),
vec![
(
tag(b"DFnt"),
F::Obj(
tag(b"Font"),
vec![
(tag(b"Famy"), F::Str(family.into())),
(tag(b"Post"), F::Str(postscript.into())),
(tag(b"Wegt"), F::I32(weight)),
(tag(b"Ital"), F::Bool(italic)),
],
),
),
(tag(b"Doub"), array_f64(b"Doub", &doubles)),
(tag(b"Ints"), array_i32(b"Ints", &[0, 0, 0, 0, 1])),
(tag(b"Objs"), F::Shared(vec![solid(1.0)])),
],
)
}
pub fn run(end: i32, attrs: Option<F>) -> Vec<(vectorcraft_affinity::stream::Tag, F)> {
let mut fields = vec![(tag(b"Indx"), F::I32(end))];
if let Some(attrs) = attrs {
fields.push((tag(b"Item"), attrs));
}
fields
}
pub fn block(glyphs: F, runs: Vec<Vec<(vectorcraft_affinity::stream::Tag, F)>>, alignments: &[i32]) -> F {
F::Obj(
tag(b"StBl"),
vec![
(tag(b"Glyp"), glyphs),
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), runs))])),
(
tag(b"PAtt"),
F::Obj(
tag(b"PaAS"),
vec![(
tag(b"Runs"),
F::Objs(
tag(b"PaAR"),
alignments
.iter()
.map(|a| vec![(tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[*a]))]))])
.collect(),
),
)],
),
),
],
)
}
pub fn utf8(text: &str) -> F {
F::Obj(tag(b"GStr"), vec![(tag(b"Utf8"), F::Str(text.into()))])
}
pub fn document(blocks: Vec<F>, frame: bool, dpi: f64, transform: [f64; 6]) -> Vec<u8> {
let text = F::Obj(
tag(if frame { b"TxtF" } else { b"TxtA" }),
vec![
(tag(b"StSt"), F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(blocks))])),
(
tag(b"TxtH"),
F::Obj(
tag(if frame { b"FrFr" } else { b"ArFr" }),
vec![(tag(b"FrmB"), F::F64s(vec![10.0, 20.0, 210.0, 120.0])), (tag(b"ArtV"), F::F64(18.0))],
),
),
(tag(b"Xfrm"), F::F64s(transform.to_vec())),
],
);
let mut root = vec![
(tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(dpi))])),
(
tag(b"DocR"),
F::Obj(
tag(b"DocN"),
vec![(
tag(b"Chld"),
F::Shared(vec![F::Obj(
tag(b"Sprd"),
vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(vec![text]))],
)]),
)],
),
),
];
let mut next_id = 1000;
for (_, value) in &mut root {
shared_objects(value, &mut next_id);
}
let stream = synth::stream(&root);
synth::container(&[("doc.dat", &stream, Method::Zlib)], None)
}
pub const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
// Shared arrays require definitions/references, whereas inline fields use Obj. Give the original
// fixture objects independent shared IDs without making the fixture descriptions noisy.
fn shared_objects(value: &mut F, next_id: &mut u32) {
match value {
F::Shared(items) => {
for item in items {
if let F::Obj(class, fields) = item {
let class = *class;
let fields = std::mem::take(fields);
*next_id += 1;
*item = F::Def(*next_id, vec![class], fields);
}
shared_objects(item, next_id);
}
}
F::Obj(_, fields) | F::Def(_, _, fields) => {
for (_, value) in fields {
shared_objects(value, next_id);
}
}
F::Objs(_, items) => {
for fields in items {
for (_, value) in fields {
shared_objects(value, next_id);
}
}
}
_ => {}
}
}
+322
View File
@@ -0,0 +1,322 @@
//! Synthetic `.af` version-12 text regression oracles; see support/text_fixture.rs for provenance.
//! Unicode ranges below test the scalar-index contract corroborated by the pinned Affinity 3
//! mixed-run fixture. Broad complex typography still needs independent visual validation.
#![cfg(feature = "synth")]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod support {
pub mod corpus;
pub mod text_fixture;
}
use support::text_fixture::*;
use vectorcraft_affinity::{
Document, Limits,
model::{Align, Kind, Text},
paint::{Color, Paint},
synth::{F, tag},
};
fn read(blocks: Vec<F>) -> Document {
vectorcraft_affinity::read(&document(blocks, false, 96.0, IDENTITY), Limits::default()).unwrap()
}
fn text(d: &Document) -> &Text {
match &d.spreads[0].nodes[0].kind {
Kind::Text(t) => t,
other => panic!("expected text, got {other:?}"),
}
}
fn content(t: &Text) -> String {
t.runs.iter().map(|r| r.text.as_str()).collect()
}
fn warning(d: &Document, needle: &str) -> bool {
d.warnings.iter().any(|w| w.contains(needle))
}
#[test]
fn mixed_fonts_keep_unicode_and_attribute_boundaries() {
let d = read(vec![block(
utf8("Aé😀e\u{301}אב日本\u{2028}x\u{2029}\0"),
vec![
run(3, Some(attrs("Family One", "FamilyOne-Regular", 400, false, 16.0))),
run(9, Some(attrs("Family Two", "FamilyTwo-BoldItalic", 700, true, 24.0))),
run(13, Some(attrs("Family Three", "FamilyThree-Light", 300, false, 20.0))),
],
&[1],
)]);
let t = text(&d);
assert_eq!(t.runs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>(), ["Aé😀", "e\u{301}אב日本", "\u{2028}x\u{2029}"]);
assert_eq!(content(t), "Aé😀e\u{301}אב日本\u{2028}x\u{2029}");
assert_eq!(
(t.runs[1].family.as_str(), t.runs[1].postscript.as_str(), t.runs[1].weight, t.runs[1].italic),
("Family Two", "FamilyTwo-BoldItalic", 700, true)
);
assert_eq!((t.runs[1].size, t.runs[1].tracking, t.runs[1].leading), (24.0, 0.025, Some(30.0)));
assert!(matches!(t.runs[1].fill, Paint::Solid(Color::Rgb { a: 1.0, .. })));
assert_eq!(t.align, Align::Center);
assert_eq!((t.anchor.x, t.anchor.y), (110.0, 38.0));
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
}
#[test]
fn missing_attributes_and_uncovered_tail_preserve_characters() {
for runs in [vec![], vec![run(2, None)], vec![run(2, Some(attrs("First", "", 400, false, 14.0)))]] {
let d = read(vec![block(utf8("é😀 tail\0"), runs, &[])]);
assert_eq!(content(text(&d)), "é😀 tail");
assert!(warning(&d, "text without character attributes"));
assert!(matches!(text(&d).runs.last().unwrap().fill, Paint::Solid(Color::Gray { v: 0.0, a: 1.0 })));
assert_eq!(text(&d).runs.last().unwrap().size, 16.0); // Recovery default: 12 pt at 96 dpi.
}
}
#[test]
fn malformed_ranges_do_not_discard_the_story() {
let mut missing = run(1, None);
missing.clear();
let d = read(vec![block(
utf8("abcdef"),
vec![missing, run(-1, None), run(3, Some(attrs("First", "", 400, false, 10.0))), run(2, None), run(i32::MAX, None)],
&[],
)]);
assert_eq!(content(text(&d)), "abcdef");
assert_eq!(text(&d).runs[0].text, "abc");
assert!(warning(&d, "invalid text attribute range"));
}
#[test]
fn inline_fields_count_for_ranges_but_are_reported_and_omitted() {
let glyphs = F::Obj(
tag(b"GStr"),
vec![(
tag(b"Mixd"),
F::Objs(
tag(b"MixS"),
vec![
vec![(tag(b"Glys"), F::Shared(vec![F::Obj(tag(b"FldN"), vec![])])), (tag(b"Utf8"), F::Str("é😀".into()))],
vec![(tag(b"Utf8"), F::Str("尾\0".into()))],
],
),
)],
);
let d =
read(vec![block(glyphs, vec![run(3, Some(attrs("First", "", 400, false, 10.0))), run(5, Some(attrs("Second", "", 700, false, 15.0)))], &[])]);
assert_eq!(text(&d).runs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>(), ["é😀", "尾"]);
assert!(warning(&d, "text fields such as page numbers"));
}
#[test]
fn mixed_paragraph_alignments_are_explicitly_reported() {
let d = read(vec![block(utf8("one\u{2029}"), vec![run(4, None)], &[2]), block(utf8("two"), vec![run(3, None)], &[0, 1])]);
assert_eq!(content(text(&d)), "one\u{2029}two");
assert_eq!(text(&d).align, Align::Right);
assert!(warning(&d, "mixed paragraph alignments"));
}
#[test]
fn unknown_alignment_and_invalid_font_weight_have_honest_fallbacks() {
let d = read(vec![block(utf8("test"), vec![run(4, Some(attrs("", "OnlyPostScript", -50, true, f64::NAN)))], &[99])]);
assert_eq!((text(&d).runs[0].weight, text(&d).runs[0].size), (400, 16.0));
assert_eq!(text(&d).align, Align::Left);
assert!(warning(&d, "invalid font weight"));
assert!(warning(&d, "unknown paragraph alignment"));
}
#[test]
fn unreadable_block_does_not_remove_later_readable_text() {
let d = read(vec![F::Obj(tag(b"StBl"), vec![]), block(utf8("still here"), vec![], &[])]);
assert_eq!(content(text(&d)), "still here");
assert!(warning(&d, "a text block without readable characters"));
}
#[test]
fn text_budget_preserves_prefix_and_reports_truncation() {
let d = read(vec![block(utf8(&"é".repeat((1 << 20) + 1)), vec![], &[]), block(utf8("later"), vec![], &[])]);
assert_eq!(content(text(&d)).chars().count(), 1 << 20);
assert!(content(text(&d)).chars().all(|c| c == 'é'));
assert!(warning(&d, "text longer than a million characters"));
}
#[test]
fn boolean_opentype_and_observed_all_caps_selector_are_kept() {
let mut a = attrs("Family", "", 400, false, 12.0);
let settings = F::Obj(
tag(b"OtAt"),
vec![(
tag(b"Setn"),
F::Objs(
tag(b"OTFS"),
vec![
vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"smcp"))), (tag(b"Valu"), F::I32(1))],
vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"liga"))), (tag(b"Valu"), F::I32(0))],
vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"CAP\x01"))), (tag(b"Valu"), F::I32(1))],
vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"salt"))), (tag(b"Valu"), F::I32(2))],
],
),
)],
);
if let F::Obj(_, fields) = &mut a {
let objects = fields.iter_mut().find(|(t, _)| *t == tag(b"Objs")).unwrap();
objects.1 = F::Shared(vec![solid(1.0), F::Null, F::Null, F::Null, F::Null, F::Null, F::Null, settings]);
}
let d = read(vec![block(utf8("Mixed"), vec![run(5, Some(a))], &[])]);
assert_eq!(text(&d).runs[0].features, ["smcp", "-liga"]);
assert!(text(&d).runs[0].all_caps);
assert_eq!(content(text(&d)), "Mixed");
assert!(warning(&d, "non-boolean OpenType settings"));
}
#[test]
fn stored_fallback_font_is_used_only_when_it_names_a_font() {
for (family, expected) in [("", "Requested"), ("Emoji Family", "Emoji Family")] {
let mut a = attrs("Requested", "RequestedPS", 700, true, 12.0);
if let F::Obj(_, fields) = &mut a {
fields.push((tag(b"RFnt"), F::Obj(tag(b"Font"), vec![(tag(b"Famy"), F::Str(family.into())), (tag(b"Wegt"), F::I32(400))])));
}
let d = read(vec![block(utf8("😀"), vec![run(1, Some(a))], &[])]);
assert_eq!(text(&d).runs[0].family, expected);
assert_eq!(warning(&d, "stored fallback font"), !family.is_empty());
}
}
#[test]
fn real_affinity3_text_fixtures_confirm_unicode_and_caps_fields() {
let Some(corpus) = support::corpus::pinned() else { return };
// Files fetched at the commit and sha256 in xtask/affinity-corpus.sha256. No Patchy parser
// source was read; assertions describe this crate's parsing of its published MIT documents.
let load = |name: &str| vectorcraft_affinity::read(&std::fs::read(corpus.join(name)).unwrap(), Limits::default()).unwrap();
let d = load("patchy-text-runs.af");
let t = text(&d);
assert_eq!(t.runs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>(), ["AB", "cd", "É", "😀", "X"]);
assert_eq!(t.runs[3].family, "Segoe UI Emoji");
assert_eq!(t.runs[4].family, "Courier New");
assert!(warning(&d, "stored fallback font"));
let d = load("patchy-text-caps.af");
let texts: Vec<_> = d.spreads[0].nodes.iter().filter_map(|n| if let Kind::Text(t) = &n.kind { Some(t) } else { None }).collect();
assert_eq!(texts.len(), 2);
assert!(texts[0].runs[0].all_caps);
assert_eq!(texts[1].runs[0].features, ["smcp"]);
for name in ["patchy-text-indent.af", "patchy-text-para-spacing.af"] {
let d = load(name);
assert!(warning(&d, "paragraph indents or spacing"), "{name}: {:?}", d.warnings);
}
}
proptest::proptest! {
#![proptest_config(proptest::test_runner::Config::with_cases(64))]
#[test]
fn arbitrary_unicode_survives_damaged_attribute_ranges(
chars in proptest::collection::vec(proptest::prelude::any::<char>(), 0..128),
ends in proptest::collection::vec(-10i32..200, 0..32),
) {
let original: String = chars.into_iter().collect();
let expected: String = original.chars().filter(|c| *c != '\0' && *c != '\u{FFFC}').collect();
let d = read(vec![block(utf8(&original), ends.into_iter().map(|end| run(end, None)).collect(), &[])]);
proptest::prop_assert_eq!(content(text(&d)), expected);
}
}
#[test]
fn partially_missing_attributes_use_visible_fill_but_explicit_no_fill_is_kept() {
let empty = F::Obj(tag(b"GAtt"), vec![]);
let none = F::Obj(tag(b"GAtt"), vec![(tag(b"Objs"), F::Shared(vec![F::Obj(tag(b"FilN"), vec![])]))]);
let d = read(vec![block(utf8("ab"), vec![run(1, Some(empty)), run(2, Some(none))], &[])]);
assert!(matches!(text(&d).runs[0].fill, Paint::Solid(Color::Gray { v: 0.0, a: 1.0 })));
assert_eq!(text(&d).runs[1].fill, Paint::None);
assert_eq!(content(text(&d)), "ab");
assert!(warning(&d, "without readable fill attributes"));
}
#[test]
fn excessive_feature_settings_are_bounded_and_reported() {
let mut a = attrs("Family", "", 400, false, 12.0);
if let F::Obj(_, fields) = &mut a {
let settings = F::Obj(
tag(b"OtAt"),
vec![(
tag(b"Setn"),
F::Objs(
tag(b"OTFS"),
(0..257).map(|_| vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"smcp"))), (tag(b"Valu"), F::I32(1))]).collect(),
),
)],
);
fields.iter_mut().find(|(t, _)| *t == tag(b"Objs")).unwrap().1 =
F::Shared(vec![solid(1.0), F::Null, F::Null, F::Null, F::Null, F::Null, F::Null, settings]);
}
let d = read(vec![block(utf8("x"), vec![run(1, Some(a))], &[])]);
assert_eq!(text(&d).runs[0].features.len(), 256);
assert!(warning(&d, "more than 256 text feature settings"));
}
#[test]
fn shared_font_metadata_amplification_is_bounded_without_losing_characters() {
let mut a = attrs(&"F".repeat(16 * 1024), &"P".repeat(16 * 1024), 400, false, 12.0);
if let F::Obj(_, fields) = &mut a {
let settings = F::Obj(
tag(b"OtAt"),
vec![(
tag(b"Setn"),
F::Objs(
tag(b"OTFS"),
(0..256).map(|_| vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"smcp"))), (tag(b"Valu"), F::I32(1))]).collect(),
),
)],
);
fields.iter_mut().find(|(t, _)| *t == tag(b"Objs")).unwrap().1 =
F::Shared(vec![solid(1.0), F::Null, F::Null, F::Null, F::Null, F::Null, F::Null, settings]);
}
let F::Obj(class, fields) = a else { panic!("attributes must be an object") };
let mut runs = vec![run(1, Some(F::Def(42, vec![class], fields)))];
runs.extend((2..=1000).map(|end| run(end, Some(F::Ref(42)))));
let d = read(vec![block(utf8(&"x".repeat(1000)), runs, &[])]);
let t = text(&d);
assert_eq!(content(t), "x".repeat(1000));
assert_eq!(t.runs.len(), 1000);
let metadata: usize = t
.runs
.iter()
.flat_map(|r| [&r.family, &r.postscript].into_iter().chain(r.features.iter()))
.filter(|s| !s.is_empty())
.map(|s| s.len() + std::mem::size_of::<String>())
.sum();
assert!(metadata <= 16 << 20, "shared metadata was amplified to {metadata} bytes");
assert_eq!(t.runs[0].family.len(), 16 * 1024);
assert_eq!(t.runs[0].features.len(), 256);
assert!(t.runs.last().unwrap().family.is_empty());
assert!(t.runs.last().unwrap().features.is_empty());
assert!(warning(&d, "text attribute budget exceeded"));
}
#[test]
fn shared_gradient_attributes_are_bounded_without_losing_characters() {
let color =
F::Def(43, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([0.2f32, 0.4, 0.6, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect()))]);
let mut colors = vec![color];
colors.extend((1..1024).map(|_| F::Ref(43)));
let positions = (0..1024).map(|i| [(i as f32) / 1023.0, 0.5].iter().flat_map(|v| v.to_le_bytes()).collect()).collect();
let gradient = F::Obj(
tag(b"FilG"),
vec![(tag(b"Grad"), F::Obj(tag(b"Grad"), vec![(tag(b"Cols"), F::Shared(colors)), (tag(b"Posn"), F::Records(8, positions))]))],
);
let attrs = F::Def(42, vec![tag(b"GAtt")], vec![(tag(b"Objs"), F::Shared(vec![gradient]))]);
let mut runs = vec![run(1, Some(attrs))];
runs.extend((2..=1000).map(|end| run(end, Some(F::Ref(42)))));
let d = read(vec![block(utf8(&"x".repeat(1000)), runs, &[])]);
let t = text(&d);
assert_eq!(content(t), "x".repeat(1000));
assert_eq!(t.runs.len(), 1000);
let stop_count: usize = t
.runs
.iter()
.map(|r| match &r.fill {
Paint::Gradient(g) => g.stops.len(),
_ => 0,
})
.sum();
assert!(stop_count > 0);
assert!(stop_count * std::mem::size_of::<vectorcraft_affinity::paint::Stop>() <= 16 << 20);
let Paint::Gradient(first) = &t.runs[0].fill else { panic!("first gradient must fit") };
assert_eq!(first.stops.len(), 1024);
assert!(matches!(t.runs.last().unwrap().fill, Paint::Solid(_)));
assert!(warning(&d, "text attribute budget exceeded"));
assert!(!warning(&d, "text without character attributes"), "budget recovery must not claim source attributes are absent");
}
+312 -12
View File
@@ -1,7 +1,7 @@
//! Swatch library files: the native `.vcswatches` JSON (colour models, global, spot, gradients
//! and colour groups exactly), `.gpl` palettes (8-bit RGB; colour groups as `# Group:` comment
//! headers) and CSS custom properties (written only). Swatch exchange files (`.ase`) are read
//! only ([`read_bytes`]).
//! headers), swatch exchange `.ase` files (binary: solid colors in their own model, global, spot
//! and process colors, color groups) and CSS custom properties (written only).
use std::collections::{HashMap, HashSet};
@@ -16,18 +16,22 @@ pub enum PaletteFormat {
Native,
/// `.gpl`: a plain-text RGB palette many paint and design tools read.
Gpl,
/// `.ase`: a swatch exchange file (binary): solid colors in their own model, global, spot or
/// process, and color groups.
Ase,
/// `.css`: custom properties on `:root` (colours and gradients; written only).
Css,
}
impl PaletteFormat {
pub const ALL: [PaletteFormat; 3] = [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Css];
pub const ALL: [PaletteFormat; 4] = [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase, PaletteFormat::Css];
/// The format's id, which is also its extension.
pub fn id(self) -> &'static str {
match self {
PaletteFormat::Native => "vcswatches",
PaletteFormat::Gpl => "gpl",
PaletteFormat::Ase => "ase",
PaletteFormat::Css => "css",
}
}
@@ -35,6 +39,7 @@ impl PaletteFormat {
match self {
PaletteFormat::Native => "VectorCraft Swatches (.vcswatches)",
PaletteFormat::Gpl => "GPL Palette (.gpl)",
PaletteFormat::Ase => "Swatch Exchange (.ase)",
PaletteFormat::Css => "CSS Custom Properties (.css)",
}
}
@@ -47,6 +52,10 @@ impl PaletteFormat {
pub fn readable(self) -> bool {
self != PaletteFormat::Css
}
/// Are files of this format binary rather than text?
pub fn binary(self) -> bool {
self == PaletteFormat::Ase
}
}
/// The native file: a header around the library.
@@ -71,11 +80,13 @@ const ASE_MAX_ENTRIES: usize = 100_000;
const ASE_MAX_NAME: usize = 1024;
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
/// Write `lib` in `format`. Pattern swatches (their tiles live in a document) and None are left
/// out; `.gpl` keeps solid colours only, as 8-bit RGB.
pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> String {
/// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document)
/// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid
/// colors in their own model. Writing `.ase` fails for a library with more colors and groups than
/// [`read_bytes`] reads from one file.
pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result<Vec<u8>, String> {
let keep = |w: &&Swatch| matches!(w.paint, Paint::Solid { .. } | Paint::Gradient(_));
match format {
let text = match format {
PaletteFormat::Native => {
let strip = |list: &[Swatch]| list.iter().filter(keep).cloned().collect::<Vec<_>>();
let library = SwatchLibrary {
@@ -87,8 +98,10 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> String {
serde_json::to_string_pretty(&file).unwrap_or_default()
}
PaletteFormat::Gpl => write_gpl(lib),
PaletteFormat::Ase => return write_ase(lib),
PaletteFormat::Css => write_css(lib, keep),
}
};
Ok(text.into_bytes())
}
/// One line of text: no line breaks or tabs.
@@ -184,6 +197,102 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
out
}
/// `.ase`, as [`read_ase`] reads it: version 1.0, the ungrouped colors, then each color group as a
/// group start (its name), its colors and a group end, also for a group without colors. A color is
/// written in its own model: RGB, CMYK and gray components from 0 to 1 (gray as a level, 1 is
/// white), Lab lightness as a fraction of 100 and a and b from −128 to 127. Components are clamped
/// to those ranges, and a component that isn't a finite number is written as 0. The color type is
/// 1 for a spot color, 0 for another global color and 2 for a process color.
///
/// A swatch exchange file holds solid colors only: gradients, patterns and None are left out, and
/// a tint swatch is written as the color it shows, a process color without its link to its base.
/// The file has no library name ([`read_ase`] names a library after its file). More than
/// [`ASE_MAX_ENTRIES`] colors and groups is an error.
fn write_ase(lib: &SwatchLibrary) -> Result<Vec<u8>, String> {
let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count();
let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::<usize>();
if entries > ASE_MAX_ENTRIES {
return Err(format!(
"VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}"
));
}
let mut body = vec![];
let mut blocks = put_ase_colors(&mut body, &lib.swatches)?;
for g in &lib.groups {
let mut name = vec![];
put_ase_name(&mut name, &g.name)?;
put_ase_block(&mut body, ASE_GROUP_START, &name)?;
blocks += 2 + put_ase_colors(&mut body, &g.swatches)?;
put_ase_block(&mut body, ASE_GROUP_END, &[])?;
}
let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?;
let mut out = ASE_SIGNATURE.to_vec();
out.extend(1u16.to_be_bytes());
out.extend(0u16.to_be_bytes());
out.extend(blocks.to_be_bytes());
out.extend(body);
Ok(out)
}
/// The color blocks of the solid colors in `list` → how many were written.
fn put_ase_colors(out: &mut Vec<u8>, list: &[Swatch]) -> Result<usize, String> {
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 };
let mut n = 0;
for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) {
let mut body = vec![];
put_ase_name(&mut body, &w.name)?;
let (model, values): (&[u8; 4], Vec<f32>) = match color {
Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]),
Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]),
Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]),
Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]),
};
body.extend(model);
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
let kind: u16 = if w.spot {
1
} else if w.global {
0
} else {
2
};
body.extend(kind.to_be_bytes());
put_ase_block(out, ASE_COLOR, &body)?;
n += 1;
}
Ok(n)
}
/// A block: its type, the length of its body and the body.
fn put_ase_block(out: &mut Vec<u8>, kind: u16, body: &[u8]) -> Result<(), String> {
let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?;
out.extend(kind.to_be_bytes());
out.extend(len.to_be_bytes());
out.extend_from_slice(body);
Ok(())
}
/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included,
/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units
/// is cut before the character that would pass that limit.
fn put_ase_name(out: &mut Vec<u8>, name: &str) -> Result<(), String> {
let mut units: Vec<u16> = vec![];
for c in name.chars().filter(|&c| c != '\0') {
let mut buf = [0; 2];
let encoded = c.encode_utf16(&mut buf);
if units.len() + encoded.len() > ASE_MAX_NAME {
break;
}
units.extend_from_slice(encoded);
}
units.push(0);
let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?;
out.extend(count.to_be_bytes());
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
Ok(())
}
/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the
/// file doesn't.
pub fn read(text: &str, name: &str) -> Result<SwatchLibrary, String> {
@@ -442,6 +551,7 @@ impl UniqueNames {
mod tests {
use super::*;
use crate::{Gradient, GradientPaint, GradientStop};
use proptest::prelude::*;
fn sample() -> SwatchLibrary {
let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient {
@@ -468,10 +578,15 @@ mod tests {
}
}
/// `lib` written as text format `f`.
fn written(lib: &SwatchLibrary, f: PaletteFormat) -> String {
String::from_utf8(write(lib, f).unwrap()).unwrap()
}
#[test]
fn native_round_trip_keeps_cmyk_spot_and_groups() {
let lib = sample();
let text = write(&lib, PaletteFormat::Native);
let text = written(&lib, PaletteFormat::Native);
assert!(sniff(&text));
let back = read(&text, "fallback").unwrap();
let mut expected = lib.clone();
@@ -484,7 +599,7 @@ mod tests {
#[test]
fn gpl_writes_rgb_with_group_headers_and_reads_comments_and_headers() {
let text = write(&sample(), PaletteFormat::Gpl);
let text = written(&sample(), PaletteFormat::Gpl);
assert!(text.starts_with("GIMP Palette\nName: Brand */ Colours\n"));
assert!(text.contains("# Group: Neutrals\n255 0 0\tR=255 G=0 B=0\n"), "{text}");
assert!(!text.contains("Fade") && !text.contains("Tiles"), "only solid colours");
@@ -514,7 +629,7 @@ mod tests {
assert_eq!(css_property("#FF00CC"), "--\\#ff00cc");
assert_eq!(css_property("Café 50%"), "--café-50\\%");
assert_eq!(css_property(" "), "--swatch");
let text = write(&sample(), PaletteFormat::Css);
let text = written(&sample(), PaletteFormat::Css);
assert!(text.starts_with("/* Brand * / Colours */\n:root {\n"), "{text}");
assert!(text.contains(" --ink: #"), "{text}");
assert!(text.contains("; /* spot */"));
@@ -528,7 +643,7 @@ mod tests {
swatches: ["Red", "red"].map(|n| Swatch { name: n.into(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).to_vec(),
groups: vec![],
};
let text = write(&lib, PaletteFormat::Css);
let text = written(&lib, PaletteFormat::Css);
assert!(text.contains("--red: #000000;") && text.contains("--red-2: #000000;"));
assert!(read(&text, "x").is_err(), "CSS is written only");
}
@@ -645,4 +760,189 @@ mod tests {
assert!(read_bytes(&ase(&groups), "x").unwrap_err().contains("more than"));
assert_eq!(read_bytes(&ase(&groups[1..]), "x").unwrap().groups.len(), ASE_MAX_ENTRIES, "up to the limit");
}
#[test]
fn ase_writes_each_model_kind_and_group() {
let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot };
let tint = Swatch {
name: "Ink 40%".into(),
paint: Paint::Solid { color: Color::cmyk(0.4, 0.2, 0.0, 0.08), swatch: Some("Ink".into()), tint: 0.4 },
global: false,
spot: false,
};
// `sample()` holds the spot color Ink, the gradient Fade, the pattern Tiles and the group Neutrals.
let mut lib = sample();
lib.swatches.insert(0, sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false));
lib.swatches.push(tint);
lib.groups[0].swatches = vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)];
lib.groups.push(SwatchGroup { name: "Empty".into(), swatches: vec![] });
let bytes = write(&lib, PaletteFormat::Ase).unwrap();
let expected = ase(&[
ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
ase_color("Ink 40%", b"CMYK", &[0.4, 0.2, 0.0, 0.08], 2),
(ASE_GROUP_START, ase_name("Neutrals")),
ase_color("Mist", b"Gray", &[0.75], 2),
ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
(ASE_GROUP_END, vec![]),
(ASE_GROUP_START, ase_name("Empty")),
(ASE_GROUP_END, vec![]),
]);
assert_eq!(bytes, expected, "no gradient or pattern; the tint as the process color it shows");
let back = read_bytes(&bytes, "Brand").unwrap();
assert_eq!((back.len(), back.groups.len()), (5, 2), "the empty group stays");
assert_eq!(PaletteFormat::parse(".ASE"), Some(PaletteFormat::Ase));
assert!(PaletteFormat::Ase.readable() && PaletteFormat::Ase.binary() && !PaletteFormat::Gpl.binary());
}
#[test]
fn ase_names_lose_nul_and_stop_at_the_reader_limit() {
let names = ["Re\0d".to_string(), "é".repeat(1030), format!("a{}", "🎨".repeat(600))];
let swatches = names.iter().map(|n| Swatch { name: n.clone(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).collect();
let lib = SwatchLibrary { name: "x".into(), swatches, groups: vec![] };
let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap();
let got: Vec<&str> = back.swatches.iter().map(|w| w.name.as_str()).collect();
// At most 1024 UTF-16 code units, cut between characters: "a" and 511 two-unit emoji.
assert_eq!(got, ["Red".to_string(), "é".repeat(1024), format!("a{}", "🎨".repeat(511))]);
}
#[test]
fn ase_clamps_components_and_writes_non_finite_ones_as_zero() {
let sw = |name: &str, color| Swatch { name: name.into(), paint: Paint::solid(color), global: false, spot: false };
let swatches = vec![
sw("Lab", Color::lab(100.5, 300.0, -300.0)),
sw("Rgb", Color::rgb(2.0, -1.0, f32::NAN)),
sw("Cmyk", Color::cmyk(1.5, 0.0, 0.0, f32::INFINITY)),
sw("Gray", Color::gray(1.5)),
];
let bytes = write(&SwatchLibrary { name: "x".into(), swatches, groups: vec![] }, PaletteFormat::Ase).unwrap();
let expected = ase(&[
ase_color("Lab", b"LAB ", &[1.0, 127.0, -128.0], 2),
ase_color("Rgb", b"RGB ", &[1.0, 0.0, 0.0], 2),
ase_color("Cmyk", b"CMYK", &[1.0, 0.0, 0.0, 0.0], 2),
ase_color("Gray", b"Gray", &[0.0], 2),
]);
assert_eq!(bytes, expected, "clamped to the ranges .ase holds, a component that isn't finite as 0");
// Lightness 100.5 is written as 1, which reads back as L* 100.
let back = read_bytes(&bytes, "x").unwrap();
assert_eq!(back.swatches[0].paint.color(), Some(Color::lab(100.0, 127.0, -128.0)));
}
#[test]
fn ase_write_refuses_more_entries_than_the_reader_takes() {
let gray = |i: usize| Swatch { name: format!("G{i}"), paint: Paint::solid(Color::gray(0.5)), global: false, spot: false };
// The limit counts colors and groups: a group and `ASE_MAX_ENTRIES - 1` colors reach it.
let mut lib = SwatchLibrary {
name: "x".into(),
swatches: (1..ASE_MAX_ENTRIES).map(gray).collect(),
groups: vec![SwatchGroup { name: "Group".into(), swatches: vec![] }],
};
let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap();
assert_eq!((back.len(), back.groups.len()), (ASE_MAX_ENTRIES - 1, 1));
lib.swatches.push(gray(0));
let e = write(&lib, PaletteFormat::Ase).unwrap_err();
assert!(e.contains("reads at most 100000 colors and groups from a swatch exchange file, and this library has 100001"), "{e}");
// A gradient is left out and is not counted.
lib.swatches.last_mut().unwrap().paint = sample().swatches[1].paint.clone();
assert!(write(&lib, PaletteFormat::Ase).is_ok());
}
/// A color in one of the four models, in the ranges `.ase` holds.
fn arb_color() -> impl Strategy<Value = Color> {
let unit = || 0.0f32..=1.0;
prop_oneof![
(unit(), unit(), unit()).prop_map(|(r, g, b)| Color::rgb(r, g, b)),
(unit(), unit(), unit(), unit()).prop_map(|(c, m, y, k)| Color::cmyk(c, m, y, k)),
unit().prop_map(Color::gray),
(0.0f32..=100.0, -128.0f32..=127.0, -128.0f32..=127.0).prop_map(|(l, a, b)| Color::lab(l, a, b)),
]
}
/// A swatch's paint with its global and spot flags: a solid color with any flags, a tint swatch
/// (both flags off) or a gradient.
fn arb_paint() -> impl Strategy<Value = (Paint, bool, bool)> {
prop_oneof![
4 => (arb_color(), any::<bool>(), any::<bool>()).prop_map(|(c, global, spot)| (Paint::solid(c), global, spot)),
1 => arb_color().prop_map(|c| (Paint::Solid { color: c, swatch: Some("Base".into()), tint: 0.4 }, false, false)),
1 => Just((sample().swatches[1].paint.clone(), false, false)),
]
}
/// Ungrouped swatches and color groups. A name is a number and up to 12 characters of any script
/// but NUL, trimmed, so swatches and groups have unique names, as in a document.
fn arb_library() -> impl Strategy<Value = SwatchLibrary> {
let swatches = || prop::collection::vec((arb_paint(), "[^\\x00]{0,12}"), 0..12);
(swatches(), prop::collection::vec(("[^\\x00]{0,12}", swatches()), 0..4)).prop_map(|(loose, groups)| {
let mut n = 0;
let mut name = |prefix: &str, base: &str| {
n += 1;
format!("{prefix}{n} {base}").trim().to_string()
};
let mut lib = SwatchLibrary { name: "Fuzz".into(), ..Default::default() };
for ((paint, global, spot), base) in loose {
lib.swatches.push(Swatch { name: name("", &base), paint, global, spot });
}
for (base, list) in groups {
let mut g = SwatchGroup { name: name("G", &base), swatches: vec![] };
for ((paint, global, spot), base) in list {
g.swatches.push(Swatch { name: name("", &base), paint, global, spot });
}
lib.groups.push(g);
}
lib
})
}
/// Are `got` and `want` in the same model, with every component within 1e-4? Lab lightness and
/// gray read back within `f32` rounding.
fn close(got: Color, want: Color) -> bool {
let near = |a: f32, b: f32| (a - b).abs() < 1e-4;
match (got, want) {
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => near(r, r2) && near(g, g2) && near(b, b2),
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => near(c, c2) && near(m, m2) && near(y, y2) && near(k, k2),
(Color::Gray { k }, Color::Gray { k: k2 }) => near(k, k2),
(Color::Lab { l, a, b }, Color::Lab { l: l2, a: a2, b: b2 }) => near(l, l2) && near(a, a2) && near(b, b2),
_ => false,
}
}
/// The swatches of `list` as an `.ase` file reads them back: solid colors only, unlinked, spot
/// colors global.
fn ase_expected(list: &[Swatch]) -> Vec<Swatch> {
list.iter()
.filter_map(|w| Some(Swatch { name: w.name.clone(), paint: Paint::solid(w.paint.color()?), global: w.global || w.spot, spot: w.spot }))
.collect()
}
/// Do swatches `got` have the names, flags and unlinked colors (within 1e-4) of `want`?
fn same_swatches(got: &[Swatch], want: &[Swatch]) -> bool {
got.len() == want.len()
&& got.iter().zip(want).all(|(g, w)| {
let color = match (&g.paint, w.paint.color()) {
(Paint::Solid { color, swatch: None, .. }, Some(c)) => close(*color, c),
_ => false,
};
g.name == w.name && g.global == w.global && g.spot == w.spot && color
})
}
proptest! {
#![proptest_config(ProptestConfig { failure_persistence: None, ..ProptestConfig::default() })]
/// A written `.ase` file reads back as the library's solid colors in their own model, with
/// their names, kinds and color groups.
#[test]
fn ase_round_trip_keeps_models_kinds_and_groups(lib in arb_library()) {
let bytes = write(&lib, PaletteFormat::Ase).unwrap();
prop_assert!(sniff_bytes(&bytes));
let back = read_bytes(&bytes, &lib.name).unwrap();
prop_assert_eq!(&back.name, &lib.name);
prop_assert!(same_swatches(&back.swatches, &ase_expected(&lib.swatches)), "{:?}", back.swatches);
prop_assert_eq!(back.groups.len(), lib.groups.len());
for (g, want) in back.groups.iter().zip(&lib.groups) {
prop_assert_eq!(&g.name, &want.name);
prop_assert!(same_swatches(&g.swatches, &ase_expected(&want.swatches)), "{}: {:?}", g.name, g.swatches);
}
}
}
}
+3 -3
View File
@@ -116,7 +116,7 @@ fn every_effect_is_deterministic() {
assert_eq!(a, b, "{id}");
assert_ne!(a, src, "{id} changes the image");
// Premultiplied stays premultiplied.
assert!(a.chunks_exact(4).all(|p| p[0] <= p[3] && p[1] <= p[3] && p[2] <= p[3]), "{id}");
assert!(a.as_chunks::<4>().0.iter().all(|p| p[0] <= p[3] && p[1] <= p[3] && p[2] <= p[3]), "{id}");
}
}
@@ -196,9 +196,9 @@ fn lengths_are_document_units() {
fn gaussian_and_plane_blurs_keep_their_mass() {
let (w, h) = (30, 30);
let mut d = image(w, h, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { grey(255) } else { [0, 0, 0, 0] });
let before: u32 = d.chunks_exact(4).map(|p| p[3] as u32).sum();
let before: u32 = d.as_chunks::<4>().0.iter().map(|p| p[3] as u32).sum();
gaussian_rgba(&mut d, w, h, 2.0);
let after: u32 = d.chunks_exact(4).map(|p| p[3] as u32).sum();
let after: u32 = d.as_chunks::<4>().0.iter().map(|p| p[3] as u32).sum();
assert!((before as f64 - after as f64).abs() / (before as f64) < 0.02, "{before} → {after}");
assert!(at(&d, w, 9, 15)[3] > 0 && at(&d, w, 10, 15)[3] < 255);
let mut plane: Vec<f32> = (0..w * h).map(|i| if i == 15 * w + 15 { 100.0 } else { 0.0 }).collect();
+27 -10
View File
@@ -7,6 +7,7 @@ use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_text::embed::Embedding;
use super::*;
@@ -77,13 +78,17 @@ pub struct Section {
pub rows: Vec<(String, String)>,
}
/// What a font's `fsType` lets a copy of it do.
/// What a font's `fsType` lets a copy of it do, read as exports read it ([`Embedding`]): the
/// most permissive usage bit wins, and bitmap-only fonts may not be embedded.
pub fn embedding_label(fs_type: u16) -> &'static str {
match fs_type & 0x000f {
0x0002 => "embedding not allowed",
0x0004 => "embedding for preview and print",
0x0008 => "embedding for editing",
_ => "embedding allowed",
if Embedding::from_fs_type(fs_type) == Embedding::Forbidden {
"embedding not allowed"
} else if fs_type & 0x0008 != 0 {
"embedding for editing"
} else if fs_type & 0x0004 != 0 {
"embedding for preview and print"
} else {
"embedding allowed"
}
}
@@ -136,13 +141,19 @@ fn sections(d: &Document, info: &Value, fonts: &BTreeSet<(String, String)>, imag
fonts
.iter()
.map(|(family, style)| {
let detail = match db.face(family, style) {
Some(f) if f.family.eq_ignore_ascii_case(family) => {
// Found by any of its names; a style the family lacks shows in another.
let detail = match db.resolve(family, style) {
Some((f, m)) if m != vectorcraft_text::FontMatch::Missing => {
let file =
f.path().and_then(|p| p.file_name()).map_or_else(|| "built in".into(), |n| n.to_string_lossy().into_owned());
format!("{file}; {}", embedding_label(f.fs_type()))
let found = format!("{file}; {}", embedding_label(f.fs_type()));
if m == vectorcraft_text::FontMatch::Style {
format!("substituted: shown in {} {} ({found})", f.family, f.style)
} else {
found
}
}
Some(f) => format!("missing: shown in {} {}", f.family, f.style),
Some((f, _)) => format!("missing: shown in {} {}", f.family, f.style),
None => "missing".into(),
};
(format!("{family} {style}"), detail)
@@ -396,6 +407,12 @@ mod tests {
assert_eq!(embedding_label(0x0002), "embedding not allowed");
assert_eq!(embedding_label(0x0004 | 0x0100), "embedding for preview and print");
assert_eq!(embedding_label(0x0008), "embedding for editing");
// As exports read it: bitmap embedding only, the restricted bit with reserved bit 0, the
// most permissive of several usage bits.
assert_eq!(embedding_label(0x0200), "embedding not allowed");
assert_eq!(embedding_label(0x0003), "embedding not allowed");
assert_eq!(embedding_label(0x0006), "embedding for preview and print");
assert_eq!(embedding_label(0x000c), "embedding for editing");
}
#[test]
+22 -12
View File
@@ -1,6 +1,6 @@
//! File (document-level) and Edit commands, plus document queries.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
@@ -250,29 +250,39 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &json!({}), true);
}
// Copy promotes a compound member to its compound. Cut must remove the same objects it
// copied, while Clear on its own deletes exactly the selected members.
let ids = selected_roots(s)?;
copy(s, p)?;
clear(s, &json!({}))
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids })) } else { clear(s, &json!({})) }
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
// Direct-selected anchors: delete those anchors instead of whole objects.
if ids_param(p, "ids").is_none() && !s.doc()?.selection.anchors.is_empty() {
if explicit.is_none() && !s.doc()?.selection.anchors.is_empty() {
return super::path::delete_anchors(s, p);
}
// Selected ruler guides (selected on their own).
if ids_param(p, "ids").is_none() && s.doc()?.selection.is_empty() {
if explicit.is_none() && s.doc()?.selection.is_empty() {
return super::docmenu::guide_remove(s, &json!({}));
}
let ids = match ids_param(p, "ids") {
Some(v) => v,
None => selected_roots(s)?,
};
let st = s.doc()?;
let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc));
// Keep the selected ids themselves, without promoting compound members. Delete a selected
// ancestor just once; its selected descendants leave with it. Layers themselves are kept.
let targets: BTreeSet<_> = targets.into_iter().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer())).collect();
let ids: Vec<_> = targets
.iter()
.copied()
.filter(|id| !st.doc.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor)))
.collect();
if ids.is_empty() {
return ok();
}
s.edit("Clear", |d, sel| {
for id in &ids {
if d.node(*id).is_some_and(|n| n.is_layer()) {
continue;
}
let _ = d.remove(*id);
d.remove(*id)?;
}
sel.clear();
Ok(())
+37 -8
View File
@@ -206,6 +206,13 @@ impl Builder {
/// One Affinity node (and its subtree) as VectorCraft art; `to_doc` maps document pixels to
/// points. `layer_level`: the node is directly in a spread or a layer, so a layer stays a layer.
fn node(&mut self, n: &af::Node, to_doc: Affine, boards: &mut Vec<(String, Rect)>, layer_level: bool) -> Option<Arc<Node>> {
// Register before descending so nested artboards keep their document order.
if let Kind::Artboard { rect, .. } = &n.kind {
boards.push((
if n.name.is_empty() { format!("Artboard {}", boards.len() + 1) } else { n.name.clone() },
to_doc.transform_rect_bbox(rect_of(*rect)),
));
}
let child_level = matches!(n.kind, Kind::Layer) && layer_level;
let children: Vec<Arc<Node>> = n.children.iter().filter_map(|c| self.node(c, to_doc, boards, child_level)).collect();
let mut out = match &n.kind {
@@ -241,14 +248,18 @@ impl Builder {
self.base(n, NodeKind::Group { children: kids, clip: true })
}
}
Kind::Artboard { rect, background } => {
let r = to_doc.transform_rect_bbox(rect_of(*rect));
boards.push((if n.name.is_empty() { format!("Artboard {}", boards.len() + 1) } else { n.name.clone() }, r));
Kind::Artboard { path, even_odd, background, strokes, .. } => {
let mut clip = Node::new(
self.doc.alloc_id(),
NodeKind::Path { path: shapes::rectangle(r), rule: FillRule::NonZero, live: None, clipping: true, guide: false },
NodeKind::Path {
path: self.path(path, to_doc),
rule: if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero },
live: None,
clipping: true,
guide: false,
},
);
clip.appearance = self.appearance(background, &[], to_doc);
clip.appearance = self.appearance(background, strokes, to_doc);
let mut kids = vec![Arc::new(clip)];
kids.extend(children);
let mut g = self.base(n, NodeKind::Group { children: kids, clip: true });
@@ -432,9 +443,27 @@ impl Builder {
.runs
.iter()
.map(|r| {
let mut style =
CharStyle { font_family: if r.family.is_empty() { r.postscript.clone() } else { r.family.clone() }, ..CharStyle::default() };
style.font_style = font_style(r.weight, r.italic);
let mut style = CharStyle::default();
if !r.family.is_empty() {
style.font_family = r.family.clone();
} else if !r.postscript.is_empty() {
style.font_family = r.postscript.clone();
} else {
self.warn("text without a font name uses the default font");
}
// A family/weight pair cannot identify width variants such as Arial Narrow.
// Resolve a known PostScript identity to the exact installed family and style.
if let Some((family, face_style)) = vectorcraft_text::FontDb::global().by_postscript_name(&r.postscript) {
style.font_family = family;
style.font_style = face_style;
} else {
style.font_style = font_style(r.weight, r.italic);
}
style.features = r.features.clone();
if r.features.iter().any(|feature| !vectorcraft_text::OtFeatures::known_tag(feature)) {
self.warn("unsupported text OpenType features (retained but not rendered)");
}
style.all_caps = r.all_caps;
style.size = r.size * k;
style.leading = r.leading.map(|l| l * k);
style.tracking = r.tracking * 1000.0;
+15
View File
@@ -304,6 +304,21 @@ pub(crate) fn id_param(p: &Value, key: &str) -> Option<NodeId> {
pub(crate) fn ids_param(p: &Value, key: &str) -> Option<Vec<NodeId>> {
p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(NodeId).collect())
}
/// Validate all explicit targets before a command changes the document or selection.
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
let values =
p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?;
values.iter().map(|value| checked_id(s, value, command)).collect()
}
pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> {
let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?;
if s.doc()?.doc.node(id).is_none() {
return Err(bad(command, format!("no such object id {value}")));
}
Ok(id)
}
pub(crate) fn point_param(p: &Value, key: &str) -> Option<Point> {
let a = p.get(key)?.as_array()?;
Some(Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?))
+13 -6
View File
@@ -109,8 +109,15 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
lines.push("FONTS".to_string());
for (family, style) in super::fonts::used_fonts(&st.doc) {
let font = format!("{family} {style}");
let reason = match db.face(&family, &style) {
Some(f) if f.family.eq_ignore_ascii_case(&family) && f.embeddable() => {
// Found by any of its names, as the canvas draws it.
let resolved = db.resolve(&family, &style).filter(|(_, m)| *m != vectorcraft_text::FontMatch::Missing);
// A style the family lacks is shown in its closest style, whose file is copied.
let shown = match &resolved {
Some((f, vectorcraft_text::FontMatch::Style)) => format!(" (shown in {} {})", f.family, f.style),
_ => String::new(),
};
let reason = match resolved {
Some((f, _)) if f.embeddable() => {
let data = f.file_data();
let file = f.path().and_then(Path::file_name).map_or_else(
|| format!("{}-{}.{}", f.family, f.style, font_ext(data)).replace(|c: char| !(c.is_alphanumeric() || "-_.".contains(c)), ""),
@@ -121,13 +128,13 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
entries.push((format!("Fonts/{file}"), data.to_vec()));
fonts += 1;
}
lines.push(format!("{font} → Fonts/{file}"));
lines.push(format!("{font}{shown} → Fonts/{file}"));
continue;
}
Some(f) if f.family.eq_ignore_ascii_case(&family) => "its licence doesn't allow embedding",
_ => "not available on this computer",
Some(_) => "its licence doesn't allow embedding",
None => "not available on this computer",
};
lines.push(format!("{font}: {reason}, not copied"));
lines.push(format!("{font}{shown}: {reason}, not copied"));
skipped.push(json!({ "font": font, "reason": reason }));
}
lines.push(String::new());
+28 -5
View File
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Join",
["Object", "Path"],
Some("Cmd+J"),
"{} join two open paths' nearest endpoints, or close a single open path",
"{ids?: [path, path] (default: the selected paths), ends?: [\"first\"|\"last\", \"first\"|\"last\"] (which end of each path to join, as the Pen joins them; default: the nearest pair)} join two open paths into one (the first keeps its id, selected), or close a single open path",
has_selection,
join
),
@@ -283,8 +283,27 @@ fn end_points(sp: &SubPath) -> Option<(Point, Point)> {
Some((sp.anchors.first()?.p, sp.anchors.last()?.p))
}
fn join(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_paths(s)?;
fn join(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.join";
let ids = match ids_param(p, "ids") {
Some(ids) => {
let st = s.doc()?;
if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Path { .. }))) {
return Err(bad(C, format!("{} isn't a path", id.0)));
}
ids
}
None => selected_paths(s)?,
};
// The ends to join, as (reverse the first path, reverse the second): the first path's end
// must come last, the second's first.
let ends = match p.get("ends") {
None => None,
Some(e) => match e.as_array().map(|a| a.iter().map(Value::as_str).collect::<Vec<_>>()).as_deref() {
Some([Some(a @ ("first" | "last")), Some(b @ ("first" | "last"))]) => Some((*a == "first", *b == "last")),
_ => return Err(bad(C, "ends must be two of \"first\" and \"last\"")),
},
};
match ids.as_slice() {
[one] => {
let id = *one;
@@ -305,6 +324,9 @@ fn join(s: &mut Session, _: &Value) -> Result<Value> {
}
[a, b, ..] => {
let (a, b) = (*a, *b);
if a == b {
return Err(bad(C, "join two different paths"));
}
s.edit("Join", |d, sel| {
let pb = d.node(b).and_then(|n| n.path_data()).cloned().ok_or(EngineError::NoNode(b))?;
let pa = path_mut(d, a)?;
@@ -316,10 +338,11 @@ fn join(s: &mut Session, _: &Value) -> Result<Value> {
let (Some((xf, xl)), Some((yf, yl))) = (end_points(&x), end_points(&y)) else {
return Err(EngineError::Other("join needs open paths".into()));
};
// Pick the closest pair of ends.
// The ends asked for, else the closest pair.
let cands =
[(xl.distance(yf), false, false), (xl.distance(yl), false, true), (xf.distance(yf), true, false), (xf.distance(yl), true, true)];
let (_, rx, ry) = cands.into_iter().min_by(|p, q| p.0.total_cmp(&q.0)).unwrap_or((0.0, false, false));
let (rx, ry) =
ends.unwrap_or_else(|| cands.into_iter().min_by(|p, q| p.0.total_cmp(&q.0)).map_or((false, false), |(_, rx, ry)| (rx, ry)));
if rx {
x.reverse();
}
+36 -10
View File
@@ -25,14 +25,30 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("select.inverse", "Inverse", ["Select"], None, "{}", has_doc, inverse),
cmd!("select.nextAbove", "Next Object Above", ["Select"], Some("Cmd+Alt+]"), "{}", has_selection, |s, _| step(s, 1)),
cmd!("select.nextBelow", "Next Object Below", ["Select"], Some("Cmd+Alt+["), "{}", has_selection, |s, _| step(s, -1)),
cmd!("select.set", "Select Objects", [], None, "{ids: [id…]}", has_doc, set),
cmd!("select.add", "Add to Selection", [], None, "{ids: [id…]}", has_doc, add),
cmd!(
"select.set",
"Select Objects",
[],
None,
"{ids: [id…]} all ids must be non-negative integers naming existing objects → {count, ids} (resulting selection)",
has_doc,
set
),
cmd!(
"select.add",
"Add to Selection",
[],
None,
"{ids: [id…]} all ids must be non-negative integers naming existing objects → {count, ids} (resulting selection)",
has_doc,
add
),
cmd!(
"select.toggle",
"Toggle Selection",
[],
None,
"{id} or {ids: [id…]}: each selected one leaves the selection, the others join it",
"{id} or {ids: [id…]}: each selected one leaves the selection, the others join it; all ids must be non-negative integers naming existing objects → {count, ids} (resulting selection)",
has_doc,
toggle
),
@@ -225,29 +241,39 @@ fn step(s: &mut Session, dir: i64) -> Result<Value> {
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let ids = ids_param(p, "ids").ok_or_else(|| bad("select.set", "missing ids"))?;
s.select(|d, sel| sel.set(ids.iter().copied().filter(|i| d.node(*i).is_some())))?;
ok()
let ids = checked_ids_param(s, p, "ids", "select.set")?;
s.select(|_, sel| sel.set(ids.iter().copied()))?;
selection_result(s)
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
let ids = ids_param(p, "ids").ok_or_else(|| bad("select.add", "missing ids"))?;
let ids = checked_ids_param(s, p, "ids", "select.add")?;
s.select(|_, sel| {
for i in ids {
sel.add(i);
}
})?;
ok()
selection_result(s)
}
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
let ids = ids_param(p, "ids").or_else(|| id_param(p, "id").map(|id| vec![id])).ok_or_else(|| bad("select.toggle", "missing id or ids"))?;
let ids = if p.get("ids").is_some() {
checked_ids_param(s, p, "ids", "select.toggle")?
} else {
let value = p.get("id").ok_or_else(|| bad("select.toggle", "missing id or ids"))?;
vec![checked_id(s, value, "select.toggle")?]
};
s.select(|_, sel| {
for id in ids {
sel.toggle(id);
}
})?;
ok()
selection_result(s)
}
fn selection_result(s: &Session) -> Result<Value> {
let selection = &s.doc()?.selection;
Ok(json!({ "count": selection.len(), "ids": selection.objects }))
}
fn key(s: &mut Session, p: &Value) -> Result<Value> {
+2 -2
View File
@@ -15,7 +15,7 @@ use vectorcraft_doc::{Document, GraphicStyle, PatternDef, StyleLibrary};
use super::menucmds::squash;
use super::swatch::str_list;
use super::swatchlib::{LibraryFile, LibraryInfo, stem};
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem};
use super::*;
pub fn specs() -> Vec<CommandSpec> {
@@ -211,7 +211,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
let lib = StyleLibrary::from_document(&st.doc, &str_list(p, "names"), name).map_err(|e| bad(C, e))?;
let mut out = json!({ "count": lib.len() });
s.style_libraries.write(p, &lib.name, STYLES_EXT, style_libs::write(&lib), &mut out, C)?;
s.style_libraries.write(p, &lib.name, STYLES_EXT, FileData::Text(style_libs::write(&lib)), &mut out, C)?;
Ok(out)
}
+36 -14
View File
@@ -60,7 +60,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save Swatch Library…",
["Window", "Swatches"],
None,
"{path?, format?: \"vcswatches\" (lossless JSON: colour models, global, spot, gradients, groups) | \"gpl\" (8-bit RGB palette; groups as `# Group:` comments) | \"css\" (custom properties on :root) (default: the path's extension, else vcswatches), names?: [swatch or colour group names] (default: all; None and patterns are never saved), name?: library name (default: the document's), user?: false (save into the user library folder, listed under User Defined)} save the document's swatches as a library → {path, format, count, library?: id when saved to the user folder}; without path or user → {data: the file's text, format, count}",
"{path?, format?: \"vcswatches\" (lossless JSON: colour models, global, spot, gradients, groups) | \"gpl\" (8-bit RGB palette; groups as `# Group:` comments) | \"ase\" (swatch exchange, binary: solid colors in their own model (RGB, CMYK, Lab, Gray) as global, spot or process colors, and color groups; gradients are left out, and a tint swatch is saved as the color it shows) | \"css\" (custom properties on :root) (default: the path's extension, else vcswatches), names?: [swatch or colour group names] (default: all; None and patterns are never saved), name?: library name (default: the document's), user?: false (save into the user library folder, listed under User Defined)} save the document's swatches as a library → {path, format, count, library?: id when saved to the user folder}; without path or user → {data: the file's text, format, count}, or {dataBase64, format, count} for ase",
has_doc,
save
),
@@ -117,6 +117,14 @@ impl LibraryFile for SwatchLibrary {
/// The extensions of library files [`palette_io::read_bytes`] reads.
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase"];
/// A library file the save commands write ([`Libraries::write`]).
pub(crate) enum FileData {
/// Text (`.vcswatches`, `.gpl`, CSS, `.vcstyles`), returned as `data`.
Text(String),
/// Bytes (`.ase`), returned as `dataBase64`.
Binary(Vec<u8>),
}
impl<L: LibraryFile> Libraries<L> {
pub fn user_dir(&self) -> Option<&str> {
self.user_dir.as_deref()
@@ -155,29 +163,34 @@ impl<L: LibraryFile> Libraries<L> {
self.extra.iter().find(|e| e.info.id == id).and_then(|e| e.path.as_deref())
}
/// Write library file `text` as the save commands do: into the user library folder as
/// Write library file `data` as the save commands do: into the user library folder as
/// `name`.`ext` with `user: true` (→ `path`, and `library`: its id), to `path`, else back as
/// `data`; the results go into `out`.
pub(crate) fn write(&mut self, p: &Value, name: &str, ext: &str, text: String, out: &mut Value, cmd: &str) -> Result<()> {
/// `data` (text) or `dataBase64` (bytes); the results go into `out`.
pub(crate) fn write(&mut self, p: &Value, name: &str, ext: &str, data: FileData, out: &mut Value, cmd: &str) -> Result<()> {
let bytes = match &data {
FileData::Text(text) => text.as_bytes(),
FileData::Binary(bytes) => bytes.as_slice(),
};
if bool_or(p, "user", false) {
let dir = self
.user_dir()
.ok_or_else(|| bad(cmd, "no user library folder here (save with a path, or without one to get the data)"))?
.to_string();
// A file name from the library's name, without characters file systems reject.
let base: String = name.chars().map(|c| if "/\\:*?\"<>|".contains(c) || c.is_control() { '-' } else { c }).collect();
let file = format!("{}.{ext}", base.trim_matches(['.', ' ']));
let file = library_file_name(name, ext);
let path = std::path::Path::new(&dir).join(&file).to_string_lossy().to_string();
create_dir(&dir)?;
write_file(&path, text.as_bytes())?;
write_file(&path, bytes)?;
self.rescan();
out["path"] = json!(path);
out["library"] = json!(format!("user/{file}"));
} else if let Some(path) = str_param(p, "path") {
write_file(path, text.as_bytes())?;
write_file(path, bytes)?;
out["path"] = json!(path);
} else {
out["data"] = json!(text);
match data {
FileData::Text(text) => out["data"] = json!(text),
FileData::Binary(bytes) => out["dataBase64"] = json!(vectorcraft_format::base64_encode(&bytes)),
}
}
Ok(())
}
@@ -207,6 +220,14 @@ impl<L: LibraryFile> Libraries<L> {
}
}
/// The file name of library `name` with extension `ext`: characters file systems reject become
/// `-`, and dots and spaces at either end are dropped. A name with nothing left is `Library`.
pub fn library_file_name(name: &str, ext: &str) -> String {
let base: String = name.chars().map(|c| if "/\\:*?\"<>|".contains(c) || c.is_control() { '-' } else { c }).collect();
let base = base.trim_matches(['.', ' ']);
format!("{}.{ext}", if base.is_empty() { "Library" } else { base })
}
/// The library files with extensions `exts` in folder `dir`, sorted by name.
#[cfg(not(target_arch = "wasm32"))]
fn library_files(dir: &str, exts: &[&str]) -> Vec<String> {
@@ -343,15 +364,16 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.save";
let path = str_param(p, "path");
let format = match str_param(p, "format").or_else(|| path.map(|p| p.rsplit_once('.').map_or("", |(_, e)| e))).filter(|f| !f.is_empty()) {
Some(f) => PaletteFormat::parse(f).ok_or_else(|| bad(C, format!("unknown format `{f}` (vcswatches, gpl or css)")))?,
Some(f) => PaletteFormat::parse(f).ok_or_else(|| bad(C, format!("unknown format `{f}` (vcswatches, gpl, ase or css)")))?,
None => PaletteFormat::Native,
};
let st = s.doc()?;
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
let lib = document_library(&st.doc, &str_list(p, "names"), name, C)?;
let (count, text) = (lib.len(), palette_io::write(&lib, format));
let mut out = json!({"format": format.id(), "count": count});
s.swatch_libraries.write(p, &lib.name, format.id(), text, &mut out, C)?;
let bytes = palette_io::write(&lib, format).map_err(|e| bad(C, e))?;
let data = if format.binary() { FileData::Binary(bytes) } else { FileData::Text(String::from_utf8_lossy(&bytes).into_owned()) };
let mut out = json!({"format": format.id(), "count": lib.len()});
s.swatch_libraries.write(p, &lib.name, format.id(), data, &mut out, C)?;
Ok(out)
}
+4 -1
View File
@@ -1055,7 +1055,10 @@ impl Session {
/// Execute a command by id. This is THE entry point for every frontend.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
if let Err(why) = (spec.enabled)(self) {
// Clear's menu needs a selection; an agent supplying explicit targets only needs a
// document. The command validates those targets before making any edit.
let enabled = if id == "edit.clear" && params.get("ids").is_some() { cmd::has_doc(self) } else { (spec.enabled)(self) };
if let Err(why) = enabled {
return Err(EngineError::Disabled(id.to_string(), why));
}
// Only top-level commands are journaled (commands that call other commands would otherwise
+54
View File
@@ -790,3 +790,57 @@ fn pen_with_alt_converts_the_anchors_of_the_path_being_drawn() {
gesture(&mut s, &[(500.0, 400.0)], none);
assert_eq!((paths(&s).len(), path(&s, id).subpaths[0].anchors.len()), (1, 5));
}
/// #776: the Pen continues any open path from the end clicked, selected or not, and while drawing a
/// click on an end of another open path joins the two into one path, in one undo step, which
/// finishes it.
#[test]
fn the_pen_continues_any_open_path_and_joins_another() {
use vectorcraft_tools::Cursor;
let (v, none) = (view(), Mods::default());
let mut s = session();
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
let b = line(&mut s, 300.0, 200.0, 400.0, 200.0);
s.execute("select.none", &json!({})).unwrap();
s.select_tool("pen", v).unwrap();
assert_eq!(s.cursor(Point::new(200.0, 100.0), none, v), Cursor::PenContinue, "an end of a path that isn't selected");
gesture(&mut s, &[(200.0, 100.0)], none);
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v), Cursor::PenJoin);
assert_eq!(s.cursor(Point::new(350.0, 200.0), none, v), Cursor::Pen, "the middle of the other path");
assert_eq!(gesture(&mut s, &[(300.0, 200.0)], none), 1);
let pts = |s: &Session, id| path(s, id).subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|x| (x.p.x, x.p.y))).collect::<Vec<_>>();
assert_eq!(pts(&s, a), [(100.0, 100.0), (200.0, 100.0), (300.0, 200.0), (400.0, 200.0)]);
assert!(s.doc().unwrap().doc.node(b).is_none() && paths(&s).len() == 1, "one path");
// The join finished it: the next click starts a new path.
gesture(&mut s, &[(500.0, 500.0)], none);
assert_eq!(paths(&s).len(), 2);
// From a path's first end, drawing goes on from there: the path is reversed.
s.execute("select.none", &json!({})).unwrap();
s.select_tool("selection", v).unwrap();
s.select_tool("pen", v).unwrap();
gesture(&mut s, &[(100.0, 100.0)], none);
gesture(&mut s, &[(50.0, 50.0)], none);
assert_eq!(pts(&s, a), [(400.0, 200.0), (300.0, 200.0), (200.0, 100.0), (100.0, 100.0), (50.0, 50.0)]);
}
/// `path.join {ids, ends}` joins the ends asked for, not the nearest pair; bad requests are errors.
#[test]
fn join_takes_the_paths_and_the_ends_to_join() {
let mut s = session();
let a = line(&mut s, 0.0, 0.0, 100.0, 0.0);
let b = line(&mut s, 110.0, 0.0, 200.0, 0.0);
// The far ends: a's first to b's last (the nearest pair would be a's last and b's first).
s.execute("path.join", &json!({"ids": [a.0, b.0], "ends": ["first", "last"]})).unwrap();
let pts: Vec<(f64, f64)> = path(&s, a).subpaths[0].anchors.iter().map(|x| (x.p.x, x.p.y)).collect();
assert_eq!(pts, [(100.0, 0.0), (0.0, 0.0), (200.0, 0.0), (110.0, 0.0)]);
let r = rect(&mut s, 0.0, 50.0, 10.0, 10.0);
for bad in [
json!({"ids": [a.0, a.0]}),
json!({"ids": [a.0, 999]}),
json!({"ids": [a.0, r.0], "ends": ["first"]}),
json!({"ids": [a.0, b.0], "ends": ["first", "middle"]}),
] {
assert!(s.execute("path.join", &bad).is_err(), "{bad}");
}
}
+30
View File
@@ -157,6 +157,36 @@ fn a_missing_link_is_reported_not_copied() {
assert!(report.contains("blue.png: not found"), "{report}");
}
#[test]
fn a_font_named_by_another_of_its_names_is_copied() {
let dir = Folder::new("package-alias");
let mut s = poster(&dir);
// The bundled Semibold by its PostScript name, as an SVG or a PDF can name it.
run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Alias", "font": "SourceSans3-Semibold"}));
let r = run(&mut s, "file.package", json!({}));
assert_eq!((r["fonts"].as_u64(), r["skippedFonts"].clone()), (Some(2), json!([])), "{}", r["skippedFonts"]);
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
let report = String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap();
assert!(report.contains("SourceSans3-Semibold Regular → Fonts/"), "{report}");
let details = report.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default();
assert!(details.contains("embedding allowed") && !details.contains("missing"), "{report}");
}
#[test]
fn a_substituted_style_names_the_style_shown() {
let dir = Folder::new("package-style");
let mut s = poster(&dir);
// No Source Sans 3 has a Black Wide, bundled or installed: its closest style stands in, and
// that style's file is copied.
run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Heavy", "font": "Source Sans 3", "style": "Black Wide"}));
let r = run(&mut s, "file.package", json!({}));
assert_eq!(r["skippedFonts"], json!([]));
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
let report = String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap();
assert!(report.contains("Source Sans 3 Black Wide (shown in Source Sans 3 "), "{report}");
assert!(report.contains("Source Sans 3 Black Wide: substituted: shown in Source Sans 3 "), "{report}");
}
#[test]
fn the_document_info_report_has_every_category() {
let dir = Folder::new("docinfo-report");
+48
View File
@@ -182,6 +182,10 @@ fn libraries_saved_in_the_user_folder_are_user_defined() {
let css = dir.join("out.css").to_string_lossy().to_string();
run(&mut s, "swatch.library.save", json!({ "path": css }));
assert!(std::fs::read_to_string(&css).unwrap().contains(" --white: #ffffff;"));
// A name with nothing a file name can keep is saved as Library.vcswatches, and User Defined lists it.
let r = run(&mut s, "swatch.library.save", json!({"user": true, "name": "..."}));
assert_eq!(r["library"], "user/Library.vcswatches");
assert_eq!(cmd::swatchlib::library(&s, "user/Library.vcswatches").map(|(info, _)| info.name), Some("...".into()));
let _ = std::fs::remove_dir_all(dir);
}
@@ -235,6 +239,50 @@ fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn swatch_exchange_files_save_with_models_kinds_and_groups() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 1.0, "m": 0.5, "y": 0.0, "k": 0.2}, "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Clay", "color": {"l": 50, "a": 20, "b": -30}}));
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#123456", "#abcdef"]}));
let r = run(&mut s, "swatch.library.save", json!({"format": "ase", "names": ["Ink", "Clay", "Brand", "Grays", "Sunset"], "name": "Brand Kit"}));
assert_eq!(r["format"], "ase");
assert!(r.get("data").is_none(), "a binary file comes back as dataBase64");
let b64 = r["dataBase64"].as_str().unwrap().to_string();
assert!(vectorcraft_format::base64_decode(&b64).unwrap().starts_with(b"ASEF"));
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Brand Kit.ase"}));
let (_, lib) = cmd::swatchlib::library(&s, r["library"].as_str().unwrap()).unwrap();
assert_eq!(lib.name, "Brand Kit", "named after the file");
let ink = lib.swatch("Ink").unwrap();
assert!(ink.spot && ink.global);
assert_eq!(ink.paint.color(), Some(Color::cmyk(1.0, 0.5, 0.0, 0.2)));
assert_eq!(lib.swatch("Clay").unwrap().paint.color(), Some(Color::lab(50.0, 20.0, -30.0)));
assert!(lib.swatch("Sunset").is_none(), "a gradient is left out");
let groups: Vec<(&str, usize)> = lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.len())).collect();
assert_eq!(groups, [("Grays", 9), ("Brand", 2)], "in document order");
// Gray colors come back within float rounding.
let grays = &doc(&s).swatch_groups.iter().find(|g| g.name == "Grays").unwrap().swatches;
for (w, want) in lib.groups[0].swatches.iter().zip(grays) {
let (Some(Color::Gray { k }), Some(Color::Gray { k: want_k })) = (w.paint.color(), want.paint.color()) else {
panic!("{} isn't gray", w.name)
};
assert!(w.name == want.name && (k - want_k).abs() < 1e-4, "{}: {k} for {want_k}", w.name);
}
// Into the user library folder, and to a path ending in .ase.
let dir = temp_dir("ase-save");
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
let r = run(&mut s, "swatch.library.save", json!({"format": "ase", "user": true, "name": "Brand Kit"}));
assert_eq!(r["library"], "user/Brand Kit.ase");
assert!(std::fs::read(r["path"].as_str().unwrap()).unwrap().starts_with(b"ASEF"));
assert!(cmd::swatchlib::library(&s, "user/Brand Kit.ase").is_some(), "the user folder lists it");
let path = dir.join("out.ase").to_string_lossy().to_string();
assert_eq!(run(&mut s, "swatch.library.save", json!({ "path": path }))["format"], "ase");
assert!(std::fs::read(&path).unwrap().starts_with(b"ASEF"));
let e = s.execute("swatch.library.save", &json!({"format": "aco"})).unwrap_err().to_string();
assert!(e.contains("vcswatches, gpl, ase or css"), "{e}");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_library_group_stays_one_group_when_a_swatch_has_its_name() {
use vectorcraft_testkit::ase::{Block, ase};
+147
View File
@@ -0,0 +1,147 @@
//! Synthetic version-12 regression documents exercise placement and clipping, independently of
//! the pinned real-file corpus. These are reader fixtures, never claimed as Affinity-authored.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use kurbo::Rect;
use vectorcraft_affinity::synth::{self, F, Method, tag};
use vectorcraft_doc::{Document, Node, NodeKind};
fn field(t: &[u8; 4], f: F) -> (vectorcraft_affinity::stream::Tag, F) {
(tag(t), f)
}
fn red(id: u32) -> F {
F::Def(
id,
vec![tag(b"FDsc")],
vec![field(
b"FDeF",
F::Def(
id + 1,
vec![tag(b"FilS")],
vec![field(
b"Colr",
F::Def(
id + 2,
vec![tag(b"RGBA")],
vec![field(b"_col", F::Struct([1f32, 0.0, 0.0, 1.0].into_iter().flat_map(f32::to_le_bytes).collect()))],
),
)],
),
)],
)
}
fn shape(id: u32, name: &str, board: bool, ellipse: bool, bounds: [f64; 4], transform: [f64; 6], children: Vec<F>) -> F {
F::Def(
id,
vec![tag(b"ShpN")],
vec![
field(b"Desc", F::Str(name.into())),
field(b"ABEn", F::Bool(board)),
field(b"Shpe", F::Def(id + 1, vec![tag(if ellipse { b"ShpE" } else { b"ShNR" })], vec![])),
field(b"ShpB", F::F64s(bounds.to_vec())),
field(b"Xfrm", F::F64s(transform.to_vec())),
field(b"BFFl", F::Shared(vec![red(id + 2)])),
field(b"Chld", F::Shared(children)),
],
)
}
const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
fn document(spreads: Vec<Vec<F>>, dpi: f64, method: Method) -> Vec<u8> {
let spreads = spreads
.into_iter()
.enumerate()
.map(|(i, nodes)| {
F::Def(1000 + i as u32, vec![tag(b"Sprd")], vec![field(b"SprB", F::F64s(vec![0.0, 0.0, 200.0, 100.0])), field(b"Chld", F::Shared(nodes))])
})
.collect();
let doc = synth::stream(&[
field(b"UVCn", F::Obj(tag(b"UVCn"), vec![field(b"UPPI", F::F64(dpi))])),
field(b"DocR", F::Def(2000, vec![tag(b"DocN")], vec![field(b"Chld", F::Shared(spreads))])),
]);
synth::container(&[("doc.dat", &doc, method)], None)
}
fn find<'a>(nodes: &'a [std::sync::Arc<Node>], name: &str) -> Option<&'a Node> {
nodes.iter().find_map(|n| {
if n.name.as_deref() == Some(name) && matches!(n.kind, NodeKind::Group { .. }) {
Some(n.as_ref())
} else {
n.children().and_then(|c| find(c, name))
}
})
}
#[test]
fn nested_boards_keep_order_and_negative_origins_at_document_resolution() {
let inner = shape(20, "Inner", true, false, [0.0, 0.0, 20.0, 10.0], [1.0, 0.0, 10.0, 0.0, 1.0, 5.0], vec![]);
let outer = shape(10, "Outer", true, false, [0.0, 0.0, 100.0, 60.0], [1.0, 0.0, -40.0, 0.0, 1.0, -20.0], vec![inner]);
let last = shape(30, "Last", true, false, [0.0, 0.0, 40.0, 80.0], [1.0, 0.0, 150.0, 0.0, 1.0, 0.0], vec![]);
for method in [Method::Stored, Method::Zlib, Method::Zstd] {
let loaded = vectorcraft_engine::cmd::fileio::load("boards.af", &document(vec![vec![outer.clone(), last.clone()]], 144.0, method)).unwrap();
let boards = &loaded.doc.artboards;
assert_eq!(boards.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["Outer", "Inner", "Last"]);
assert_eq!(boards.iter().map(|b| b.id).collect::<Vec<_>>(), [1, 2, 3]);
assert_eq!(boards[0].rect, Rect::new(-20.0, -10.0, 30.0, 20.0));
assert_eq!(boards[1].rect, Rect::new(-15.0, -7.5, -5.0, -2.5));
assert_eq!(boards[2].rect, Rect::new(75.0, 0.0, 95.0, 40.0));
let reopened = vectorcraft_format::load_file(&vectorcraft_format::save_file(&loaded.doc)).unwrap();
assert_eq!(reopened.doc.artboards, loaded.doc.artboards);
assert_eq!(reopened.doc.layers, loaded.doc.layers);
}
}
fn pixel(d: &Document, x: usize, y: usize) -> [u8; 4] {
let img = vectorcraft_render::Renderer::new().render_region(d, d.artboards[0].rect, 1.0, false);
img.to_straight()[(y * img.width as usize + x) * 4..][..4].try_into().unwrap()
}
#[test]
fn rotated_board_clips_to_its_outline_instead_of_its_export_rectangle() {
let child = shape(20, "Oversized", false, false, [-100.0, -100.0, 200.0, 200.0], IDENTITY, vec![]);
let c = std::f64::consts::FRAC_1_SQRT_2;
let board = shape(10, "Diamond", true, false, [0.0, 0.0, 80.0, 80.0], [c, -c, 60.0, c, c, 0.0], vec![child]);
let loaded = vectorcraft_engine::cmd::fileio::load("rotated.af", &document(vec![vec![board]], 72.0, Method::Zstd)).unwrap();
let d = &loaded.doc;
let g = find(&d.layers, "Diamond").unwrap();
let NodeKind::Path { path, clipping: true, .. } = &g.children().unwrap()[0].kind else { panic!() };
let a = &path.subpaths[0].anchors;
assert!((a[0].p.x - 60.0).abs() < 1e-8 && a[0].p.y.abs() < 1e-8);
assert!((a[1].p.x - (60.0 + 80.0 * c)).abs() < 1e-8);
assert_eq!(pixel(d, 2, 2), [0, 0, 0, 0], "bbox corners are outside the diamond");
assert_eq!(pixel(d, 55, 55), [255, 0, 0, 255]);
}
#[test]
fn converted_ellipse_artboard_keeps_curved_clipping() {
let child = shape(20, "Oversized", false, false, [-20.0, -20.0, 120.0, 120.0], IDENTITY, vec![]);
let board = shape(10, "Ellipse", true, true, [0.0, 0.0, 100.0, 100.0], IDENTITY, vec![child]);
let loaded = vectorcraft_engine::cmd::fileio::load("ellipse.af", &document(vec![vec![board]], 72.0, Method::Stored)).unwrap();
assert_eq!(pixel(&loaded.doc, 2, 2), [0, 0, 0, 0]);
assert_eq!(pixel(&loaded.doc, 50, 50), [255, 0, 0, 255]);
}
#[test]
fn invalid_board_keeps_children_and_reports_the_loss() {
let child = shape(20, "Retained", false, false, [1.0, 2.0, 10.0, 20.0], IDENTITY, vec![]);
let board = shape(10, "Invalid", true, false, [0.0, 0.0, 0.0, 100.0], IDENTITY, vec![child]);
let loaded = vectorcraft_engine::cmd::fileio::load("invalid.af", &document(vec![vec![board]], 72.0, Method::Stored)).unwrap();
assert!(loaded.warnings.iter().any(|w| w.contains("artboard without valid bounds")));
assert!(!loaded.preview_only);
assert_eq!(loaded.doc.artboards[0].rect, Rect::new(0.0, 0.0, 200.0, 100.0));
let invalid = find(&loaded.doc.layers, "Invalid").unwrap();
assert_eq!(invalid.children().unwrap()[0].name.as_deref(), Some("Retained"));
}
#[test]
fn several_spreads_preserve_each_board_and_leave_room_between_spreads() {
let a = shape(10, "First", true, false, [0.0, 0.0, 100.0, 60.0], IDENTITY, vec![]);
let b = shape(20, "Second", true, false, [0.0, 0.0, 100.0, 60.0], IDENTITY, vec![]);
let loaded = vectorcraft_engine::cmd::fileio::load("spreads.af", &document(vec![vec![a], vec![b]], 72.0, Method::Stored)).unwrap();
assert_eq!(loaded.doc.artboards.len(), 2);
assert_eq!(loaded.doc.artboards[0].rect, Rect::new(0.0, 0.0, 100.0, 60.0));
assert_eq!(loaded.doc.artboards[1].rect, Rect::new(136.0, 0.0, 236.0, 60.0));
}
+185 -18
View File
@@ -4,14 +4,27 @@
//! (0–255 per channel, both flattened on white, at the thumbnail's size) must stay under its
//! ceiling, which sits just above the difference measured when the importer landed.
//!
//! Skips when `corpus/affinity` is absent.
//! Each artboard is checked. Local runs may skip an absent corpus; CI requires the complete
//! pinned corpus with `AFFINITY_CORPUS_REQUIRED=1`. Tests recheck hashes before using inputs.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::PathBuf;
#[path = "../../affinity/tests/support/corpus.rs"]
mod corpus_gate;
/// (file, ceiling). Measured differences when the importer landed are in the comments.
const FILES: &[(&str, f64)] = &[
("patchy-artboards.af", 0.25), // 0.00 across both boards, including overflow clipping
("patchy-rgba8.af", 3.0), // 2.34: embedded thumbnail versus raster sampling
("patchy-rgba16.af", 3.0), // 2.34
("patchy-dpi300.af", 1.5), // 0.87
("patchy-group.af", 0.25), // 0.00
("patchy-transform.af", 1.0), // 0.19
("patchy-vector.af", 1.0), // 0.12
("patchy-lazy-placed.af", 1.0), // 0.50: upstream byte-derived lazy-image regression
("patchy-embedded-jpeg.af", 1.0), // 0.50
("affinity3-mexican-guy.af", 3.0), // 1.80: brush strokes as plain strokes
("affinity3-mexican-man.af", 3.5), // 2.24
("affinity3-mexican-woman.af", 3.5), // 2.55
@@ -37,8 +50,7 @@ const FILES: &[(&str, f64)] = &[
];
fn corpus() -> Option<PathBuf> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/affinity");
dir.join("SOURCES.md").exists().then_some(dir)
corpus_gate::pinned()
}
/// Mean absolute difference of two RGBA8 images of one size, both composited on white.
@@ -48,7 +60,7 @@ fn difference(a: &[u8], b: &[u8]) -> f64 {
[0, 1, 2].map(|i| f64::from(p[i]) * al + 255.0 * (1.0 - al))
};
let (mut sum, mut n) = (0.0, 0usize);
for (p, q) in a.chunks_exact(4).zip(b.chunks_exact(4)) {
for (p, q) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0.iter()) {
let (x, y) = (white(p), white(q));
sum += (0..3).map(|i| (x[i] - y[i]).abs()).sum::<f64>();
n += 3;
@@ -69,23 +81,178 @@ fn public_affinity_documents_render_like_their_affinity_thumbnails() {
assert!(!loaded.preview_only, "{name} opened as its preview: {:?}", loaded.warnings);
let d = &loaded.doc;
let thumb = image::load_from_memory(vectorcraft_affinity::preview(&bytes).unwrap().png).unwrap().to_rgba8();
// The thumbnail shows the first page, or every artboard: compare the largest artboard
// with its part of the thumbnail.
// The embedded thumbnail shows the union of the artboards. Check every board,
// including small ones that the previous largest-board-only check omitted.
let union = d.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).unwrap();
assert!(union.width().is_finite() && union.width() > 0.0);
let scale = f64::from(thumb.width()) / union.width();
let board = d.artboards.iter().max_by(|a, b| a.rect.area().total_cmp(&b.rect.area())).unwrap().rect;
let crop = |v: f64| (v * scale).round().max(0.0) as u32;
let (x, y) = (crop(board.x0 - union.x0), crop(board.y0 - union.y0));
let (w, h) = (crop(board.width()).min(thumb.width() - x), crop(board.height()).min(thumb.height() - y));
let expected = image::imageops::crop_imm(&thumb, x, y, w, h).to_image();
let rendered = vectorcraft_render::Renderer::new().render_region(d, board, scale, false);
let got = image::RgbaImage::from_raw(rendered.width, rendered.height, rendered.to_straight()).unwrap();
let got = image::imageops::resize(&got, w, h, image::imageops::FilterType::Triangle);
let diff = difference(expected.as_raw(), got.as_raw());
eprintln!("{name}: {diff:.2} (ceiling {ceiling})");
if diff > *ceiling {
failures.push(format!("{name}: {diff:.2} > {ceiling}"));
for (index, artboard) in d.artboards.iter().enumerate() {
let board = artboard.rect;
let crop = |v: f64| (v * scale).round().max(0.0) as u32;
let (x, y) = (crop(board.x0 - union.x0), crop(board.y0 - union.y0));
assert!(x < thumb.width() && y < thumb.height(), "{name} board {index}: thumbnail crop outside image");
let (w, h) = (crop(board.width()).min(thumb.width() - x), crop(board.height()).min(thumb.height() - y));
assert!(w > 0 && h > 0, "{name} board {index}: empty thumbnail crop");
let expected = image::imageops::crop_imm(&thumb, x, y, w, h).to_image();
let rendered = vectorcraft_render::Renderer::new().render_region(d, board, scale, false);
let got = image::RgbaImage::from_raw(rendered.width, rendered.height, rendered.to_straight()).unwrap();
let got = image::imageops::resize(&got, w, h, image::imageops::FilterType::Triangle);
let diff = difference(expected.as_raw(), got.as_raw());
eprintln!("{name} board {index} ({}): {diff:.2} (ceiling {ceiling})", artboard.name);
if diff > *ceiling {
failures.push(format!("{name} board {index}: {diff:.2} > {ceiling}"));
}
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// Every actual .af fixture must open as editable art, retain its complete native document,
/// and export every artboard. Reimporting our SVG/PDF and comparing our PSD merged pixels
/// checks our export paths; it is not an independent Affinity-versus-PSD fidelity oracle.
#[test]
fn affinity3_all_artboards_survive_native_save_and_export() {
let Some(dir) = corpus() else { return };
let names: Vec<_> = include_str!("../../../xtask/affinity-corpus.sha256")
.lines()
.filter_map(|l| l.split_once(" "))
.map(|(_, name)| name)
.filter(|name| name.ends_with(".af"))
.collect();
for name in names {
let bytes = std::fs::read(dir.join(name)).unwrap();
let loaded = vectorcraft_engine::cmd::fileio::load(name, &bytes).unwrap();
assert!(!loaded.preview_only, "{name}: preview-only import: {:?}", loaded.warnings);
let doc = &loaded.doc;
assert!(!doc.artboards.is_empty(), "{name}: no artboards");
let native = vectorcraft_format::save(doc, false);
let reloaded = vectorcraft_format::load(&native).unwrap();
assert_eq!(serde_json::to_value(&reloaded).unwrap(), serde_json::to_value(doc).unwrap(), "{name}: native save/reload lost document data");
if doc.artboards.len() > 1 {
let params = serde_json::json!({"range": "all", "useArtboards": true, "preserveEditing": false});
let svg = vectorcraft_engine::cmd::fileio::encode_all(doc, "svg", &params).unwrap();
assert_eq!(svg.files.len(), doc.artboards.len(), "{name}: SVG must write every artboard");
assert_eq!(
svg.files.iter().map(|(index, _)| *index).collect::<Vec<_>>(),
(0..doc.artboards.len()).map(Some).collect::<Vec<_>>(),
"{name}: SVG artboard order"
);
let pdf = vectorcraft_engine::cmd::fileio::encode(doc, "pdf", &params).unwrap();
assert_eq!(
vectorcraft_pdf::info(&pdf, None).unwrap().pages.len(),
doc.artboards.len(),
"{name}: PDF must write every artboard as a page"
);
}
for (index, board) in doc.artboards.iter().enumerate() {
assert!(
board.rect.width().is_finite() && board.rect.width() > 0.0 && board.rect.height().is_finite() && board.rect.height() > 0.0,
"{name} board {index}: invalid bounds"
);
let scale = 128.0 / board.rect.width().max(board.rect.height());
let params =
serde_json::json!({"artboard": index, "useArtboards": true, "scale": scale, "background": "transparent", "preserveEditing": false});
let svg = vectorcraft_engine::cmd::fileio::encode(doc, "svg", &params).unwrap();
let svg = vectorcraft_svg::import(std::str::from_utf8(&svg).unwrap()).unwrap();
assert_eq!(svg.artboards.len(), 1, "{name} board {index}: SVG page count");
assert!((svg.artboards[0].rect.width() - board.rect.width()).abs() < 0.01, "{name} board {index}: SVG width");
assert!((svg.artboards[0].rect.height() - board.rect.height()).abs() < 0.01, "{name} board {index}: SVG height");
let pdf = vectorcraft_engine::cmd::fileio::encode(doc, "pdf", &params).unwrap();
let info = vectorcraft_pdf::info(&pdf, None).unwrap();
assert_eq!(info.pages.len(), 1, "{name} board {index}: PDF page count");
assert!((info.pages[0].width - board.rect.width()).abs() < 0.01, "{name} board {index}: PDF width");
assert!((info.pages[0].height - board.rect.height()).abs() < 0.01, "{name} board {index}: PDF height");
assert_eq!(vectorcraft_pdf::import(&pdf).unwrap().artboards.len(), 1, "{name} board {index}: PDF reimport");
let psd = vectorcraft_engine::cmd::fileio::encode(doc, "psd", &params).unwrap();
let png = vectorcraft_engine::cmd::fileio::encode(doc, "png", &params).unwrap();
let png = image::load_from_memory(&png).unwrap().to_rgba8();
let (merged, has_alpha) = psd_merged(&psd);
assert_eq!(merged.dimensions(), png.dimensions(), "{name} board {index}: PSD image dimensions");
// PSD merged RGB is stored on a white matte for readers that ignore alpha;
// the separate alpha plane, when present, keeps the original coverage.
for (pixel, (p, q)) in png.pixels().zip(merged.pixels()).enumerate() {
if has_alpha {
assert_eq!(p[3], q[3], "{name} board {index} pixel {pixel}: PSD alpha");
}
let alpha = u32::from(p[3]);
for channel in 0..3 {
let expected = ((u32::from(p[channel]) * alpha + 255 * (255 - alpha) + 127) / 255) as u8;
assert!(
q[channel].abs_diff(expected) <= 1,
"{name} board {index} pixel {pixel} channel {channel}: PSD white-matted RGB {} differs from PNG on white {expected}",
q[channel]
);
}
}
eprintln!("{name} board {index}: native/SVG/PDF/PSD verified (import warnings: {:?})", loaded.warnings);
}
}
}
/// Minimal test-only decoder written from the public PSD file-format layout:
/// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/
/// It independently reads the merged RGB planes and PackBits rows, skipping metadata/layers.
fn psd_merged(bytes: &[u8]) -> (image::RgbaImage, bool) {
let be16 = |at: usize| u16::from_be_bytes(bytes[at..at + 2].try_into().unwrap());
let be32 = |at: usize| u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) as usize;
assert_eq!(&bytes[..4], b"8BPS");
assert_eq!(be16(4), 1);
assert_eq!(&bytes[6..12], &[0; 6]);
let channels = usize::from(be16(12));
assert!((3..=4).contains(&channels));
let (height, width) = (be32(14), be32(18));
assert_eq!(be16(22), 8);
assert_eq!(be16(24), 3);
let mut at = 26;
for _ in 0..3 {
at += 4 + be32(at);
}
let compression = be16(at);
at += 2;
let mut planes = vec![vec![0; width * height]; channels];
match compression {
0 => {
for plane in &mut planes {
plane.copy_from_slice(&bytes[at..at + width * height]);
at += width * height;
}
}
1 => {
let row_lengths: Vec<_> = (0..channels * height).map(|i| usize::from(be16(at + i * 2))).collect();
at += channels * height * 2;
for (channel, plane) in planes.iter_mut().enumerate() {
for row in 0..height {
let end = at + row_lengths[channel * height + row];
let mut decoded = Vec::new();
while at < end {
let control = bytes[at] as i8;
at += 1;
match control {
0..=127 => {
let n = control as usize + 1;
assert!(at + n <= end);
decoded.extend_from_slice(&bytes[at..at + n]);
at += n;
}
-127..=-1 => {
assert!(at < end);
decoded.extend(std::iter::repeat_n(bytes[at], (1i16 - i16::from(control)) as usize));
at += 1;
}
-128 => {}
}
}
assert_eq!(decoded.len(), width);
plane[row * width..(row + 1) * width].copy_from_slice(&decoded);
}
}
}
_ => panic!("unexpected PSD compression {compression}"),
}
assert_eq!(at, bytes.len(), "PSD merged planes must consume the complete image section");
let image = image::RgbaImage::from_fn(width as u32, height as u32, |x, y| {
let i = y as usize * width + x as usize;
image::Rgba([planes[0][i], planes[1][i], planes[2][i], planes.get(3).map_or(255, |p| p[i])])
});
(image, channels == 4)
}
+198
View File
@@ -0,0 +1,198 @@
//! Editable text import regressions on original synthetic version-12 `.af` streams and pinned
//! public Affinity 3 files. Font rendering depends on installed fonts; these are structure and
//! conversion oracles, not claims of pixel-identical typography.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[path = "../../affinity/tests/support/corpus.rs"]
mod corpus;
#[path = "../../affinity/tests/support/text_fixture.rs"]
mod fixture;
use fixture::*;
use vectorcraft_affinity::synth::{F, tag};
use vectorcraft_doc::{
Document, Node, NodeKind, TextObject,
text::{CharStyle, Justify, TextKind},
};
use vectorcraft_engine::cmd::fileio;
fn texts(d: &Document) -> Vec<&TextObject> {
fn walk<'a>(n: &'a Node, out: &mut Vec<&'a TextObject>) {
if let NodeKind::Text(t) = &n.kind {
out.push(t);
}
if let Some(children) = n.children() {
for child in children {
walk(child, out);
}
}
}
let mut out = Vec::new();
for n in &d.layers {
walk(n, &mut out);
}
out
}
fn import(blocks: Vec<F>, frame: bool, dpi: f64, transform: [f64; 6]) -> fileio::Loaded {
let loaded = fileio::load("original-text.af", &document(blocks, frame, dpi, transform)).unwrap();
assert!(!loaded.preview_only);
loaded
}
#[test]
fn unicode_mixed_fonts_line_breaks_and_styles_remain_editable_after_save() {
let loaded = import(
vec![block(
utf8("é😀\u{2028}ab\u{2029}尾\0"),
vec![run(2, Some(attrs("First", "FirstPS", 700, true, 24.0))), run(8, Some(attrs("Second", "SecondPS", 300, false, 20.0)))],
&[1],
)],
false,
96.0,
[2.0, 0.0, 30.0, 0.0, 2.0, 40.0],
);
let t = texts(&loaded.doc)[0];
assert_eq!(t.runs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>(), ["é😀", "\nab\n尾"]);
assert_eq!(t.runs[0].style.font_family, "First");
assert_eq!(t.runs[0].style.font_style, "Bold Italic");
assert_eq!(t.runs[1].style.font_style, "Light");
assert_eq!((t.runs[0].style.size, t.runs[0].style.leading, t.runs[0].style.tracking), (36.0, Some(45.0), 25.0));
assert_eq!(t.para.justify, Justify::Center);
assert!(matches!(t.kind, TextKind::Point));
assert_eq!(t.xf.as_coeffs(), [1.0, 0.0, 0.0, 1.0, 187.5, 87.0]);
let saved = vectorcraft_format::save_file(&loaded.doc);
let restored = vectorcraft_format::load(&saved).unwrap();
assert_eq!(texts(&restored)[0], t);
}
#[test]
fn absent_font_name_uses_named_default_and_postscript_name_is_preserved() {
let loaded =
import(vec![block(utf8("ab"), vec![run(1, Some(attrs("", "OnlyPostScript", 400, false, 12.0))), run(2, None)], &[])], false, 72.0, IDENTITY);
let t = texts(&loaded.doc)[0];
assert_eq!(t.runs[0].style.font_family, "OnlyPostScript");
assert_eq!(t.runs[1].style.font_family, CharStyle::default().font_family);
assert_eq!(t.runs[1].style.fill.color().unwrap().to_rgb(), [0.0, 0.0, 0.0]);
assert!(loaded.warnings.iter().any(|w| w.contains("without a font name")));
assert!(loaded.warnings.iter().any(|w| w.contains("without character attributes")));
}
#[test]
fn frame_type_keeps_dimensions_alignment_and_unit_conversion() {
let loaded = import(vec![block(utf8("text"), vec![run(4, Some(attrs("Frame", "", 500, false, 20.0)))], &[3])], true, 144.0, IDENTITY);
let t = texts(&loaded.doc)[0];
assert_eq!(t.runs[0].style.size, 10.0);
assert_eq!(t.runs[0].style.font_style, "Medium");
assert_eq!(t.para.justify, Justify::JustifyLeft);
let TextKind::Area { frame } = &t.kind else { panic!("expected area type") };
assert_eq!(frame.bounds().unwrap().width(), 100.0);
assert_eq!(frame.bounds().unwrap().height(), 50.0);
}
#[test]
fn each_font_weight_and_italic_maps_to_the_expected_style() {
let cases = [
(100, "Thin"),
(200, "ExtraLight"),
(300, "Light"),
(400, "Regular"),
(500, "Medium"),
(600, "SemiBold"),
(700, "Bold"),
(800, "ExtraBold"),
(900, "Black"),
];
for (weight, expected) in cases {
for italic in [false, true] {
let loaded = import(vec![block(utf8("x"), vec![run(1, Some(attrs("Family", "", weight, italic, 12.0)))], &[])], false, 72.0, IDENTITY);
let style = &texts(&loaded.doc)[0].runs[0].style.font_style;
let expected = if !italic {
expected.into()
} else if expected == "Regular" {
"Italic".into()
} else {
format!("{expected} Italic")
};
assert_eq!(*style, expected);
}
}
}
#[test]
fn caps_and_feature_overrides_pass_through_to_editable_type() {
let mut a = attrs("Family", "", 400, false, 12.0);
if let F::Obj(_, fields) = &mut a {
fields.iter_mut().find(|(t, _)| *t == tag(b"Objs")).unwrap().1 = F::Shared(vec![
solid(1.0),
F::Null,
F::Null,
F::Null,
F::Null,
F::Null,
F::Null,
F::Obj(
tag(b"OtAt"),
vec![(
tag(b"Setn"),
F::Objs(
tag(b"OTFS"),
vec![
vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"CAP\x01"))), (tag(b"Valu"), F::I32(1))],
vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"liga"))), (tag(b"Valu"), F::I32(0))],
vec![(tag(b"Feat"), F::U32(u32::from_be_bytes(*b"ss01"))), (tag(b"Valu"), F::I32(1))],
],
),
)],
),
]);
}
let loaded = import(vec![block(utf8("Mixed"), vec![run(5, Some(a))], &[])], false, 72.0, IDENTITY);
let t = texts(&loaded.doc)[0];
assert_eq!(t.runs[0].text, "Mixed");
assert!(t.runs[0].style.all_caps);
assert_eq!(t.runs[0].style.features, ["-liga", "ss01"]);
assert!(loaded.warnings.iter().any(|w| w.contains("retained but not rendered")));
let restored = vectorcraft_format::load(&vectorcraft_format::save_file(&loaded.doc)).unwrap();
assert_eq!(texts(&restored)[0], t);
}
#[test]
fn pinned_affinity3_text_opens_as_editable_unicode_with_resolved_emoji_font() {
let Some(corpus) = corpus::pinned() else { return };
let load = |name: &str| {
let loaded = fileio::load(name, &std::fs::read(corpus.join(name)).unwrap()).unwrap();
assert!(!loaded.preview_only);
loaded
};
let loaded = load("patchy-text-runs.af");
let t = texts(&loaded.doc)[0];
assert_eq!(t.runs.iter().map(|r| r.text.as_str()).collect::<String>(), "ABcdÉ😀X");
assert_eq!(t.runs[3].style.font_family, "Segoe UI Emoji");
assert_eq!(t.runs[4].style.font_family, "Courier New");
let loaded = load("patchy-text-caps.af");
let ts = texts(&loaded.doc);
assert!(ts[0].runs[0].style.all_caps);
assert_eq!(ts[1].runs[0].style.features, ["smcp"]);
for name in ["patchy-text-artistic.af", "patchy-text-frame.af", "patchy-text-rotated.af", "patchy-text-indent.af", "patchy-text-para-spacing.af"]
{
let loaded = load(name);
assert!(!texts(&loaded.doc).is_empty(), "{name}");
let restored = vectorcraft_format::load(&vectorcraft_format::save_file(&loaded.doc)).unwrap();
assert_eq!(texts(&restored), texts(&loaded.doc), "{name}");
}
}
#[test]
fn installed_postscript_identity_overrides_ambiguous_family_and_weight() {
// This is an OS font metadata check. No font file is committed or required; the structural
// fallback cases above always run, including when the optional font repository is absent.
let db = vectorcraft_text::FontDb::global();
let Some((family, face_style)) = db.by_postscript_name("DejaVuSans") else {
eprintln!("DejaVuSans is not installed; exact PostScript face test skipped");
return;
};
let loaded =
import(vec![block(utf8("x"), vec![run(1, Some(attrs("Ambiguous Family", "DejaVuSans", 900, true, 12.0)))], &[])], false, 72.0, IDENTITY);
let style = &texts(&loaded.doc)[0].runs[0].style;
assert_eq!(style.font_family, family);
assert_eq!(style.font_style, face_style);
}
+145
View File
@@ -0,0 +1,145 @@
//! Clear deletes its exact targets, including compound members (#786).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_engine::{EngineError, Session};
fn compound() -> (Session, NodeId, NodeId, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let mut rectangle =
|x| NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap());
let a = rectangle(10);
let b = rectangle(50);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let c = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
(s, a, b, c)
}
#[test]
fn clear_selected_compound_member_preserves_its_sibling_and_is_undoable() {
let (mut s, a, b, c) = compound();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
assert!(s.active().unwrap().doc.node(a).is_none());
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
assert!(s.active().unwrap().selection.is_empty());
assert_eq!(s.execute("edit.undo", &json!({})).unwrap()["undone"], "Clear");
assert_eq!(s.active().unwrap().doc.parent_of(a), Some(c));
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.active().unwrap().doc.node(a).is_none());
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
}
#[test]
fn clear_explicit_ids_works_without_a_selection_and_overrides_selected_anchors() {
let (mut s, a, b, c) = compound();
s.execute("select.none", &json!({})).unwrap();
let info = s.commands().into_iter().find(|info| info.id == "edit.clear").unwrap();
assert!(!info.enabled, "the menu stays disabled with no selection");
s.execute("edit.clear", &json!({"ids": [a.0]})).unwrap();
assert!(s.active().unwrap().doc.node(a).is_none());
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]]})).unwrap();
let sibling = s.active().unwrap().doc.node(b).unwrap().clone();
s.execute("edit.clear", &json!({"ids": [a.0]})).unwrap();
assert!(s.active().unwrap().doc.node(a).is_none());
assert_eq!(s.active().unwrap().doc.node(b).unwrap(), &sibling);
}
#[test]
fn clear_explicit_targets_are_validated_atomically() {
let (mut s, a, _, _) = compound();
s.execute("select.none", &json!({})).unwrap();
for ids in [json!([a.0, 999]), json!([a.0, -1]), json!([a.0, "bad"]), json!([a.0, 2.5]), json!(null), json!(a.0)] {
let doc = s.active().unwrap().doc.clone();
let journal = s.journal.clone();
assert!(matches!(s.execute("edit.clear", &json!({"ids": ids})), Err(EngineError::BadParams { .. })), "{ids}");
assert_eq!(s.active().unwrap().doc, doc);
assert_eq!(s.journal, journal);
}
assert!(s.execute("edit.clear", &json!({})).is_err());
assert!(Session::new().execute("edit.clear", &json!({"ids": [a.0]})).is_err());
}
#[test]
fn clear_compound_and_member_together_deletes_the_compound() {
for explicit in [false, true] {
let (mut s, a, b, c) = compound();
s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
s.execute("edit.clear", &if explicit { json!({"ids": [a.0, c.0, c.0]}) } else { json!({}) }).unwrap();
for id in [a, b, c] {
assert!(s.active().unwrap().doc.node(id).is_none());
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.parent_of(a), Some(c));
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
}
}
#[test]
fn cut_compound_member_keeps_copy_and_delete_targets_consistent() {
let (mut s, a, b, c) = compound();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("edit.cut", &json!({})).unwrap();
assert_eq!(s.clipboard.nodes.len(), 1);
assert_eq!(s.clipboard.nodes[0].id, c);
assert!(s.active().unwrap().doc.node(c).is_none());
s.execute("edit.pasteInPlace", &json!({})).unwrap();
let pasted = s.active().unwrap().selection.objects[0];
assert_eq!(s.active().unwrap().doc.node(pasted).unwrap().children().unwrap().len(), 2);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.parent_of(a), Some(c));
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
}
#[test]
fn clear_direct_selected_anchors_keeps_the_rest_of_the_path() {
let (mut s, a, b, c) = compound();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.node(a).unwrap().path_data().unwrap().anchor_count(), 3);
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
}
#[test]
fn clear_guides_and_empty_explicit_targets_keep_their_separate_behavior() {
let (mut s, a, _, _) = compound();
s.execute("guide.add", &json!({"vertical": true, "pos": 10})).unwrap();
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
let history = s.active().unwrap().history.undo.len();
let selection = s.active().unwrap().selection.clone();
s.execute("edit.clear", &json!({"ids": []})).unwrap();
assert_eq!(s.active().unwrap().history.undo.len(), history);
assert_eq!(s.active().unwrap().selection, selection);
assert_eq!(s.active().unwrap().doc.guides.len(), 1);
s.execute("edit.clear", &json!({})).unwrap();
assert!(s.active().unwrap().doc.guides.is_empty());
assert!(s.active().unwrap().doc.node(a).is_some());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.guides.len(), 1);
}
#[test]
fn clear_keeps_layers_but_deletes_an_explicitly_targeted_child() {
let (mut s, a, b, c) = compound();
let layer = s.active().unwrap().doc.layers[0].id;
s.execute("select.none", &json!({})).unwrap();
s.execute("edit.clear", &json!({"ids": [layer.0, a.0]})).unwrap();
assert!(s.active().unwrap().doc.node(layer).is_some());
assert!(s.active().unwrap().doc.node(a).is_none());
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
}
#[test]
fn cut_direct_selected_anchors_retains_anchor_deletion() {
let (mut s, a, b, c) = compound();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]]})).unwrap();
s.execute("edit.cut", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.node(a).unwrap().path_data().unwrap().anchor_count(), 3);
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
}
+27
View File
@@ -823,6 +823,20 @@ fn swatch_exchange(what: &str, bytes: &[u8]) -> Result<(), TestCaseError> {
})
}
/// The rich document's swatches with a CMYK spot color and a global Lab color added, saved as a
/// swatch exchange file, made once.
fn saved_ase() -> Vec<u8> {
static ASE: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();
ASE.get_or_init(|| {
let mut s = rich_session();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 1, "m": 0.5, "y": 0, "k": 0.2}, "spot": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Clay", "color": {"l": 50, "a": 20, "b": -30}, "global": true})).unwrap();
let r = s.execute("swatch.library.save", &json!({"format": "ase"})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
})
.clone()
}
/// A random swatch exchange block (type, body). The body holds a name, a color model when the block
/// is a color, and random bytes for the rest.
fn arb_ase_block() -> impl Strategy<Value = (u16, Vec<u8>)> {
@@ -899,6 +913,19 @@ proptest! {
}
swatch_exchange("mutated swatch exchange file", &bytes)?;
}
#[test]
fn mutated_saved_swatch_exchange_files_never_panic(cut in prop::option::of(0usize..4_000), edits in prop::collection::vec((0usize..4_000, any::<u8>()), 0..12)) {
let mut bytes = saved_ase();
for (at, b) in edits {
let n = bytes.len();
bytes[at % n] = b;
}
if let Some(cut) = cut {
bytes.truncate(cut);
}
swatch_exchange("mutated saved swatch exchange file", &bytes)?;
}
}
/// A small image of each raster format Place reads, with resolution metadata where it has some.
+75
View File
@@ -0,0 +1,75 @@
//! Selection command results and validation for agent callers (#784).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_engine::{EngineError, Session};
fn session() -> (Session, NodeId, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let mut rectangle =
|x| NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
let a = rectangle(0);
let b = rectangle(20);
(s, a, b)
}
#[test]
fn selection_commands_reject_invalid_ids_without_changing_state() {
for command in ["select.set", "select.add", "select.toggle"] {
let (mut s, a, b) = session();
s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
s.execute("select.key", &json!({"id": b.0})).unwrap();
for invalid in [json!(999), json!(-1), json!(2.5), json!("2"), Value::Null, json!(true), json!(u64::MAX)] {
let selection = s.active().unwrap().selection.clone();
let revision = s.active().unwrap().revision;
let journal = s.journal.clone();
let error = s.execute(command, &json!({"ids": [b.0, invalid]})).unwrap_err();
assert!(matches!(error, EngineError::BadParams { .. }), "{command}: {error}");
assert!(error.to_string().contains(&invalid.to_string()), "the error must identify {invalid}: {error}");
assert_eq!(s.active().unwrap().selection, selection, "{command}: {invalid}");
assert_eq!(s.active().unwrap().revision, revision);
assert_eq!(s.journal, journal);
}
}
}
#[test]
fn selection_commands_require_an_id_array() {
for command in ["select.set", "select.add", "select.toggle"] {
let (mut s, _, _) = session();
for params in [json!({}), json!({"ids": null}), json!({"ids": 2}), json!({"ids": "2"}), json!({"ids": true})] {
let selection = s.active().unwrap().selection.clone();
assert!(matches!(s.execute(command, &params), Err(EngineError::BadParams { .. })), "{command}: {params}");
assert_eq!(s.active().unwrap().selection, selection);
}
}
}
#[test]
fn selection_commands_report_the_resulting_selection() {
let (mut s, a, b) = session();
assert_eq!(s.execute("select.set", &json!({"ids": [b.0, a.0, b.0]})).unwrap(), json!({"count": 2, "ids": [b.0, a.0]}));
assert_eq!(s.execute("select.set", &json!({"ids": []})).unwrap(), json!({"count": 0, "ids": []}));
assert_eq!(s.execute("select.add", &json!({"ids": [a.0, a.0]})).unwrap(), json!({"count": 1, "ids": [a.0]}));
assert_eq!(s.execute("select.add", &json!({"ids": [b.0]})).unwrap(), json!({"count": 2, "ids": [a.0, b.0]}));
assert_eq!(s.execute("select.toggle", &json!({"id": a.0})).unwrap(), json!({"count": 1, "ids": [b.0]}));
assert_eq!(s.execute("select.toggle", &json!({"ids": [b.0, a.0]})).unwrap(), json!({"count": 1, "ids": [a.0]}));
for command in ["select.add", "select.toggle"] {
assert_eq!(s.execute(command, &json!({"ids": []})).unwrap(), json!({"count": 1, "ids": [a.0]}));
}
}
#[test]
fn single_id_toggle_validates_before_mutating() {
let (mut s, a, _) = session();
for invalid in [json!(999), json!(-1), json!(2.5), json!("2"), Value::Null, json!(true)] {
let selection = s.active().unwrap().selection.clone();
assert!(matches!(s.execute("select.toggle", &json!({"id": invalid})), Err(EngineError::BadParams { .. })));
assert_eq!(s.active().unwrap().selection, selection);
}
// A malformed array must not silently fall back to a valid single id.
assert!(s.execute("select.toggle", &json!({"ids": "bad", "id": a.0})).is_err());
}
+28 -13
View File
@@ -14,21 +14,36 @@ fn a_fresh_session_resolves_pdf_fonts_to_installed_families() {
let probe = FontDb::with_font_dirs(system_font_dirs());
probe.load_system_fonts();
let installed = probe.families();
// A family whose PDF name is its name without the spaces (as "TimesNewRoman").
let Some(family) = installed.iter().find(|f| !bundled.contains(f) && f.contains(' ') && f.chars().all(|c| c.is_ascii_alphanumeric() || c == ' '))
else {
// Families whose PDF name is their name without the spaces (as "TimesNewRoman"). The font
// isn't embedded, so the page draws a stand-in; text stays live only where the installed
// font's glyphs match it, as a plain sans-serif's do and a condensed display face's don't:
// which family that is depends on the machine's fonts, so the first of them to do is checked.
let candidates: Vec<&String> = installed
.iter()
.filter(|f| !bundled.contains(f) && f.contains(' ') && f.chars().all(|c| c.is_ascii_alphanumeric() || c == ' '))
.take(200)
.collect();
if candidates.is_empty() {
eprintln!("no system fonts installed: nothing to check");
return;
}
let import = |family: &str| {
let resources = format!("/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /{} >> >>", family.replace(' ', ""));
let page = PdfPage { resources, ..PdfPage::new(100.0, 100.0, "BT /F1 12 Tf 10 30 Td (Hi) Tj ET") };
let r = import_with_report(&pdf_with(&[page], &[], None), &ImportOptions::default()).unwrap();
let mut families = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
families.extend(t.runs.iter().map(|r| r.style.font_family.clone()));
}
});
(families, r.warnings)
};
let resources = format!("/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /{} >> >>", family.replace(' ', ""));
let page = PdfPage { resources, ..PdfPage::new(100.0, 100.0, "BT /F1 12 Tf 10 30 Td (Hi) Tj ET") };
let r = import_with_report(&pdf_with(&[page], &[], None), &ImportOptions::default()).unwrap();
let mut families = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
families.extend(t.runs.iter().map(|r| r.style.font_family.clone()));
}
let found = candidates.iter().find_map(|family| {
let (families, warnings) = import(family);
(!families.is_empty()).then_some((family, families, warnings))
});
assert_eq!(families, std::slice::from_ref(family));
assert!(!r.warnings.iter().any(|w| w.contains(family.as_str())), "{:?}", r.warnings);
let (family, families, warnings) = found.expect("one of the installed families stays live text");
assert_eq!(families, std::slice::from_ref(*family));
assert!(!warnings.iter().any(|w| w.contains(family.as_str())), "{warnings:?}");
}
+49 -13
View File
@@ -270,9 +270,10 @@ impl FontFace {
use skrifa::raw::TableProvider;
self.skrifa().and_then(|f| f.os2().ok()).map_or(0, |t| t.fs_type())
}
/// May the font file be copied along with a document (its licence doesn't restrict embedding)?
/// May the font file be copied along with a document? Its license allows embedding its
/// outlines, as exports check it ([`Self::embedding`]).
pub fn embeddable(&self) -> bool {
self.fs_type() & 0x000f != 0x0002
self.embedding() != crate::embed::Embedding::Forbidden
}
/// The face's index in its font file ([`Self::file_data`]; collections hold several).
pub fn face_index(&self) -> u32 {
@@ -773,16 +774,43 @@ fn enumerate_faces(data: &[u8]) -> Vec<(u32, FaceStyle)> {
.collect()
}
/// The font files held by the file at `path`: its contents, or for a suitcase font the fonts in
/// its resource fork ([`crate::suitcase`]). None when it can't be read.
#[cfg(not(target_arch = "wasm32"))]
fn font_files(path: &Path) -> Vec<Vec<u8>> {
if crate::suitcase::is_suitcase(path) {
return crate::suitcase::read_fonts(path);
}
std::fs::read(path).into_iter().collect()
}
/// The tables holding outlines the font engine draws: TrueType, CFF, CFF2 and VARC. A face with
/// none of them (outlines in Apple's `hvgl` table, bitmaps only) draws nothing.
#[cfg(not(target_arch = "wasm32"))]
const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"];
/// The styles of every face in the font file at `path` ([`face_styles`]), reading only its table
/// directories and `name` and `fvar` tables: a scan opens hundreds of font files, many of them
/// megabytes long.
/// megabytes long. Faces without outlines the font engine draws (no [`OUTLINE_TABLES`] table) are
/// left out.
#[cfg(not(target_arch = "wasm32"))]
fn file_face_names(path: &Path) -> Vec<FaceStyle> {
use std::io::{Read, Seek, SeekFrom};
if crate::suitcase::is_suitcase(path) {
return crate::suitcase::read_fonts(path).into_iter().flat_map(|font| reader_face_names(std::io::Cursor::new(font))).collect();
}
match std::fs::File::open(path) {
Ok(file) => reader_face_names(file),
Err(_) => vec![],
}
}
/// [`file_face_names`] for the font file `file` reads.
#[cfg(not(target_arch = "wasm32"))]
fn reader_face_names(mut file: impl std::io::Read + std::io::Seek) -> Vec<FaceStyle> {
use std::io::SeekFrom;
/// Caps on what a (possibly damaged) file can make the scan read.
const MAX_FACES: u32 = 256;
const MAX_NAME_TABLE: u32 = 1 << 20;
let Ok(mut file) = std::fs::File::open(path) else { return vec![] };
let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {
let mut buf = vec![0; len];
file.seek(SeekFrom::Start(offset)).ok()?;
@@ -804,6 +832,9 @@ fn file_face_names(path: &Path) -> Vec<FaceStyle> {
let dir = read_at(start.into(), 12)?;
let tables = u16::from_be_bytes(dir.get(4..6)?.try_into().ok()?) as usize;
let records = read_at(u64::from(start) + 12, tables * 16)?;
if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {
return None;
}
let mut table = |tag: &[u8; 4]| -> Option<Vec<u8>> {
let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?;
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?);
@@ -869,7 +900,9 @@ static PLATFORM_FONT_FILES: std::sync::OnceLock<PlatformFontFiles> = std::sync::
/// folders, asked again by each scan and each check for installed fonts
/// ([`FontDb::installed_fonts_changed`]). The desktop app lists DirectWrite's system font
/// collection on Windows: fonts a font service such as Adobe Fonts loads in place, from files
/// outside the font folders and unknown to the registry (#579). Only the first call counts.
/// outside the font folders and unknown to the registry (#579). On macOS it lists the fonts
/// CoreText's font manager has available, which apps and font managers can register from any
/// folder. Only the first call counts.
pub fn set_platform_font_files(list: PlatformFontFiles) {
#[cfg(not(target_arch = "wasm32"))]
// A second call keeps the first lister, as documented.
@@ -1329,9 +1362,10 @@ impl FontDb {
}
for (p, named) in files {
// A file named by itself is a font whatever its name (font services keep fonts in
// files without an extension); one of a folder's only with a font's extension.
// files without an extension); one of a folder's only with a font's extension, or
// a suitcase font (whose fonts are in its resource fork, whatever its name).
let ext = p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase());
if !named && !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) {
if !named && !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) && !crate::suitcase::is_suitcase(&p) {
continue;
}
for FaceStyle { family, style, keys, weight, italic, traits, .. } in file_face_names(&p) {
@@ -1452,7 +1486,7 @@ impl FontDb {
paths.dedup();
let mut any = false;
for p in paths {
if let Ok(data) = std::fs::read(&p) {
for data in font_files(&p) {
any |= self.add_font_from(data, Some(&p)) > 0;
}
}
@@ -1593,10 +1627,12 @@ impl FontDb {
if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) {
continue;
}
let Ok(data) = std::fs::read(&p) else { continue };
let hit = enumerate_faces(&data).iter().any(|(i, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()));
if hit && self.add_font_from(data, Some(&p)) > 0 && covered(self) {
return true;
for data in font_files(&p) {
let hit =
enumerate_faces(&data).iter().any(|(i, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()));
if hit && self.add_font_from(data, Some(&p)) > 0 && covered(self) {
return true;
}
}
}
self.sys.lock().unwrap_or_else(|e| e.into_inner()).misses.insert(c);
+2
View File
@@ -18,6 +18,8 @@ mod fontdb;
pub mod hyphen;
mod layout;
mod shape;
#[cfg(not(target_arch = "wasm32"))]
mod suitcase;
#[cfg(any(test, feature = "test-fonts"))]
pub mod test_fonts;
pub mod thread;
+151
View File
@@ -0,0 +1,151 @@
//! Suitcase fonts: classic Mac OS font files whose data fork is empty and whose fonts are `sfnt`
//! resources in the resource fork (Microsoft Office installs its fonts this way in
//! `/Library/Fonts/Microsoft`). macOS lists them as installed; a reader of the file's data finds
//! nothing, so the scan reads the resource fork. The fork's layout is Apple's published resource
//! file format (Inside Macintosh: More Macintosh Toolbox, "Resource Manager").
use std::path::Path;
/// Caps on what a (possibly damaged) fork can make the scan read.
const MAX_FORK: u64 = 256 << 20;
const MAX_TYPES: usize = 1 << 12;
const MAX_FONTS: usize = 256;
fn be16(b: &[u8], at: usize) -> Option<usize> {
b.get(at..at.checked_add(2)?).and_then(|s| s.try_into().ok()).map(|s| u16::from_be_bytes(s) as usize)
}
fn be32(b: &[u8], at: usize) -> Option<usize> {
b.get(at..at.checked_add(4)?).and_then(|s| s.try_into().ok()).map(|s| u32::from_be_bytes(s) as usize)
}
/// The font files (`sfnt` resources) of a resource fork, in the order its map lists them. A
/// fork that isn't well formed gives the fonts read before the damage, or none.
pub(crate) fn sfnt_resources(fork: &[u8]) -> Vec<&[u8]> {
let mut fonts = Vec::new();
let _ = collect(fork, &mut fonts);
fonts
}
fn collect<'a>(fork: &'a [u8], fonts: &mut Vec<&'a [u8]>) -> Option<()> {
// The header: where the data and the map start.
let data = be32(fork, 0)?;
let map = fork.get(be32(fork, 4)?..)?;
// The map: its type list starts at the offset kept 24 bytes in, and counts from the map.
let types = be16(map, 24)?;
// Counts are stored less one, so a list of none is 0xFFFF.
let n_types = (be16(map, types)? + 1) & 0xFFFF;
let mut total = 0usize;
for t in 0..n_types.min(MAX_TYPES) {
let at = types + 2 + t * 8;
if map.get(at..at + 4)? != b"sfnt" {
continue;
}
let count = (be16(map, at + 4)? + 1) & 0xFFFF;
// Each reference: its data's offset is the low three bytes of the word 4 bytes in.
let refs = types + be16(map, at + 6)?;
for r in 0..count {
let start = data.checked_add(be32(map, refs + r * 12 + 4)? & 0x00FF_FFFF)?;
let len = be32(fork, start)?;
// References can share data: cap the total too, as every font is copied out.
total = total.checked_add(len)?;
if fonts.len() >= MAX_FONTS || total as u64 > MAX_FORK {
return Some(());
}
fonts.push(fork.get(start + 4..start.checked_add(4)?.checked_add(len)?)?);
}
}
Some(())
}
/// The fonts of the suitcase font at `path`, read from its resource fork; none for a file
/// without one, and off macOS, the only place such a fork is a part of a file.
pub(crate) fn read_fonts(path: &Path) -> Vec<Vec<u8>> {
let Some(fork) = read_fork(path) else { return vec![] };
sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect()
}
/// Whether the file at `path` is a suitcase font: nothing in its data fork and something in its
/// resource fork.
pub(crate) fn is_suitcase(path: &Path) -> bool {
// Off macOS no file has a fork: don't look at every font file twice.
cfg!(target_os = "macos") && std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() == 0) && fork_len(path) > 0
}
#[cfg(target_os = "macos")]
fn fork_path(path: &Path) -> std::path::PathBuf {
path.join("..namedfork/rsrc")
}
#[cfg(target_os = "macos")]
fn fork_len(path: &Path) -> u64 {
std::fs::metadata(fork_path(path)).map_or(0, |m| m.len())
}
#[cfg(target_os = "macos")]
fn read_fork(path: &Path) -> Option<Vec<u8>> {
use std::io::Read;
let mut fork = Vec::new();
std::fs::File::open(fork_path(path)).ok()?.take(MAX_FORK).read_to_end(&mut fork).ok()?;
Some(fork)
}
#[cfg(not(target_os = "macos"))]
fn fork_len(_: &Path) -> u64 {
0
}
#[cfg(not(target_os = "macos"))]
fn read_fork(_: &Path) -> Option<Vec<u8>> {
let _ = MAX_FORK;
None
}
/// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as
/// a font utility writes them.
#[cfg(test)]
pub(crate) fn fork_of(fonts: &[Vec<u8>]) -> Vec<u8> {
let mut data = Vec::new();
let mut offsets = Vec::new();
for body in fonts.iter().map(Vec::as_slice).chain([&b"1.0"[..]]) {
offsets.push(data.len() as u32);
data.extend_from_slice(&(body.len() as u32).to_be_bytes());
data.extend_from_slice(body);
}
let n = fonts.len();
// The type list: `vers` (1 resource) then `sfnt`, each entry pointing at its references.
let list = 2 + 2 * 8;
let mut types = Vec::new();
types.extend_from_slice(&1u16.to_be_bytes());
types.extend_from_slice(b"vers");
types.extend_from_slice(&0u16.to_be_bytes());
types.extend_from_slice(&(list as u16).to_be_bytes());
types.extend_from_slice(b"sfnt");
types.extend_from_slice(&((n - 1) as u16).to_be_bytes());
types.extend_from_slice(&((list + 12) as u16).to_be_bytes());
let reference = |id: i16, offset: u32| {
let mut r = Vec::new();
r.extend_from_slice(&id.to_be_bytes());
r.extend_from_slice(&0xFFFFu16.to_be_bytes());
r.extend_from_slice(&offset.to_be_bytes());
r.extend_from_slice(&[0; 4]);
r
};
types.extend(reference(1, offsets[n]));
for (i, o) in offsets[..n].iter().enumerate() {
types.extend(reference(5000 + i as i16, *o));
}
// The map: a copy of the header, a handle, attributes, then the offsets of the lists.
let mut map = vec![0; 24];
map.extend_from_slice(&28u16.to_be_bytes());
map.extend_from_slice(&((28 + types.len()) as u16).to_be_bytes());
map.extend(types);
let mut fork = Vec::new();
for v in [256u32, 256 + data.len() as u32, data.len() as u32, map.len() as u32] {
fork.extend_from_slice(&v.to_be_bytes());
}
fork.resize(256, 0);
fork.extend(data);
fork.extend(map);
fork
}
+36
View File
@@ -19,6 +19,42 @@ fn fs_type_flags_decide_the_embedding() {
assert_eq!(Embedding::from_fs_type(0x0108), Embedding::Whole, "no subsetting");
}
/// The bundled Source Sans 3 Regular renamed `family` (13 characters, as long as the original
/// name) with OS/2 `fsType` set to `fs_type`.
fn licensed_font(family: &str, fs_type: u16) -> Vec<u8> {
let mut data = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf").to_vec();
let table = |data: &[u8], tag: &[u8; 4]| {
let f = skrifa::FontRef::new(data).unwrap();
let r = f.table_directory.table_records().iter().find(|r| r.tag().to_be_bytes() == *tag).unwrap();
(r.offset() as usize, r.length() as usize)
};
let (os2, _) = table(&data, b"OS/2");
data[os2 + 8..os2 + 10].copy_from_slice(&fs_type.to_be_bytes());
let (name, len) = table(&data, b"name");
assert_eq!(family.len(), "Source Sans 3".len());
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(utf16("Source Sans 3"), utf16(family)), (b"Source Sans 3".to_vec(), family.as_bytes().to_vec())] {
let mut i = name;
while let Some(at) = data[i..name + len].windows(from.len()).position(|w| w == from) {
data[i + at..i + at + to.len()].copy_from_slice(&to);
i += at + to.len();
}
}
data
}
/// A font file goes with a document (File → Package) only when exports may embed it: not when
/// its license is restricted or allows bitmaps only.
#[test]
fn fonts_exports_may_not_embed_are_not_embeddable() {
let db = FontDb::with_font_dirs(vec![]);
for (family, fs_type, embeddable) in [("Bitmap Sans 3", 0x0200, false), ("Lowbit Sans 3", 0x0003, false), ("Wholed Sans 3", 0x0100, true)] {
assert!(db.add_font(licensed_font(family, fs_type)) > 0, "{family}");
let face = db.face(family, "Regular").unwrap();
assert_eq!((face.family.as_str(), face.embeddable()), (family, embeddable), "fsType {fs_type:#06x}");
}
}
#[test]
fn a_subset_holds_only_the_glyphs_used_and_maps_their_characters() {
let face = FontDb::global().face("Source Sans 3", "Regular").unwrap();
+55
View File
@@ -104,6 +104,22 @@ fn the_scan_reads_collections_and_loads_fonts_only_when_used() {
assert_eq!(db.find(FAMILY, "Regular").unwrap().face_index(), 0, "the collection's faces load together");
}
#[test]
fn fonts_without_outlines_the_engine_draws_are_left_out() {
let dir = font_dir("outlines");
// The Bold's TrueType outlines under another tag, as in fonts that keep their outlines in
// Apple's `hvgl` table or hold bitmaps only. The tag keeps the table directory sorted.
let bold = dir.join("Sub/Sysfont-Bold.TTF");
let mut data = std::fs::read(&bold).unwrap();
let tables = u16::from_be_bytes([data[4], data[5]]) as usize;
let rec = (0..tables).map(|i| 12 + 16 * i).find(|&r| &data[r..r + 4] == b"glyf").unwrap();
data[rec..rec + 4].copy_from_slice(b"gxyz");
std::fs::write(&bold, data).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
assert_eq!(db.styles(FAMILY), ["Regular"]);
assert_eq!(db.load_system_fonts(), 1);
}
#[test]
fn rescanning_finds_fonts_installed_since() {
let dir = font_dir("rescan");
@@ -263,3 +279,42 @@ fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() {
assert_eq!(db.styles("Service Sans3"), ["Regular"]);
assert!(!FontDb::with_font_dirs(vec![file.parent().unwrap().to_path_buf()]).has_family("Service Sans3"));
}
#[test]
fn a_resource_fork_gives_up_its_font_files() {
let (regular, bold) = (renamed("SourceSans3-Regular.ttf"), renamed("SourceSans3-Bold.ttf"));
let fork = crate::suitcase::fork_of(&[regular.clone(), bold.clone()]);
assert_eq!(crate::suitcase::sfnt_resources(&fork), [regular.as_slice(), bold.as_slice()]);
// Damage keeps what was read before it, and never panics.
for cut in [0, 3, 16, 300, fork.len() - 1] {
let _ = crate::suitcase::sfnt_resources(&fork[..cut]);
}
assert!(crate::suitcase::sfnt_resources(&[0xFF; 600]).is_empty());
// A fork can't make the scan read more than so many fonts.
assert_eq!(crate::suitcase::sfnt_resources(&crate::suitcase::fork_of(&vec![b"font".to_vec(); 300])).len(), 256);
}
/// Office's fonts: a file with nothing in it but a resource fork holding the fonts, named
/// without an extension. Only macOS keeps a resource fork in a file.
#[cfg(target_os = "macos")]
#[test]
fn the_scan_reads_suitcase_fonts() {
let dir = font_dir("suitcase");
std::fs::remove_file(dir.join("Sysfont-Regular.ttf")).unwrap();
std::fs::remove_file(dir.join("Sub/Sysfont-Bold.TTF")).unwrap();
let suitcase = dir.join("Sysfont Sans3");
std::fs::write(&suitcase, b"").unwrap();
std::fs::write(
suitcase.join("..namedfork/rsrc"),
crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf"), renamed("SourceSans3-Bold.ttf")]),
)
.unwrap();
// A file with nothing in either fork is no font.
std::fs::write(dir.join("empty"), b"").unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
assert_eq!(db.styles(FAMILY), ["Regular", "Bold"]);
let bold = db.face(FAMILY, "Bold").unwrap();
assert_eq!((bold.family.as_str(), bold.style.as_str()), (FAMILY, "Bold"));
assert_eq!(bold.path(), Some(suitcase.as_path()));
assert_eq!(db.find_family("SysfontSans3").as_deref(), Some(FAMILY), "by a PostScript-style name, as an EPS names it");
}
+343
View File
@@ -0,0 +1,343 @@
//! Crop Image (#734): a crop box over the selected image. It starts on the part of the image over
//! its artboard (the whole image when it lies inside one); its handles and its inside drag it,
//! always within the image, and the part outside it is dimmed. Enter (or the Control bar's Apply)
//! crops the image to it (`object.cropImage {rect}`), Escape (or Cancel) leaves it as it was; both
//! go back to the Selection tool. The Control bar edits the box through the `rect` option.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, Selection};
use vectorcraft_geom::{Point, Rect, Vec2};
use crate::bbox::{Handle, hit_handle};
use crate::xform::CYAN;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
/// The tool's id; Object › Crop Image and the image's Crop Image buttons choose it.
pub const ID: &str = "cropImage";
/// The smallest the box gets, in points.
const MIN: f64 = 1.0;
/// Create the Crop Image tool by id (None = not ours).
pub fn create(id: &str) -> Option<Box<dyn Tool>> {
(id == ID).then(|| Box::new(CropImageTool::default()) as Box<dyn Tool>)
}
/// The selected image (the first image of the selection) and its bounds.
pub fn selected_image(doc: &Document, sel: &Selection) -> Option<(NodeId, Rect)> {
sel.objects.iter().find_map(|id| {
let n = doc.node(*id)?;
matches!(n.kind, NodeKind::Image(_)).then_some(())?;
Some((*id, n.geometric_bounds()?))
})
}
/// Where the box starts for an image with bounds `image`: its part over the artboard its centre is
/// on, or all of it when it lies inside that artboard or isn't on one.
pub fn initial_box(doc: &Document, image: Rect) -> Rect {
doc.artboard_at(image.center())
.and_then(|i| doc.artboards.get(i))
.map(|a| a.rect.intersect(image))
.filter(|r| r.width() >= MIN && r.height() >= MIN)
.unwrap_or(image)
}
/// The selected image, its bounds and the box over it: `set` kept within the image, or where the
/// box starts ([`initial_box`]).
pub fn crop_box(doc: &Document, sel: &Selection, set: Option<Rect>) -> Option<(NodeId, Rect, Rect)> {
let (id, image) = selected_image(doc, sel)?;
Some((id, image, set.map_or_else(|| initial_box(doc, image), |r| within(r, image))))
}
/// `r` (moved whole) slid back within `image` without changing its size; `r` lies within `image`
/// to begin with, so it fits.
fn slid_within(r: Rect, image: Rect) -> Rect {
let x0 = r.x0.min(image.x1 - r.width()).max(image.x0);
let y0 = r.y0.min(image.y1 - r.height()).max(image.y0);
Rect::new(x0, y0, x0 + r.width(), y0 + r.height())
}
/// `r` cut to `image`, at least [`MIN`] wide and high.
fn within(r: Rect, image: Rect) -> Rect {
let r = r.abs().intersect(image);
let w = r.width().max(MIN).min(image.width());
let h = r.height().max(MIN).min(image.height());
let x0 = r.x0.min(image.x1 - w).max(image.x0);
let y0 = r.y0.min(image.y1 - h).max(image.y0);
Rect::new(x0, y0, x0 + w, y0 + h)
}
#[derive(Clone, Copy)]
enum Drag {
/// A handle, with the box as it was pressed.
Handle(Handle, Rect),
/// The box itself, from where it was pressed.
Move(Point, Rect),
}
#[derive(Default)]
pub struct CropImageTool {
/// The box, for the image it was made for (None: set from outside, for the selected image);
/// None until it's dragged or set.
rect: Option<(Option<NodeId>, Rect)>,
drag: Option<Drag>,
}
impl CropImageTool {
/// The selected image, its bounds and the box over it.
fn current(&self, cx: &ToolContext) -> Option<(NodeId, Rect, Rect)> {
let (id, _) = selected_image(cx.doc, cx.selection)?;
let set = self.rect.filter(|(of, _)| of.is_none_or(|of| of == id)).map(|(_, r)| r);
crop_box(cx.doc, cx.selection, set)
}
/// Crop to the box and go back to the Selection tool (only back when it covers the image).
fn apply(&mut self, cx: &ToolContext) -> Vec<Action> {
let current = self.current(cx);
self.reset();
let mut out = vec![];
if let Some((_, image, r)) = current
&& !same(r, image)
{
out.push(Action::Exec("object.cropImage".into(), json!({ "rect": [r.x0, r.y0, r.width(), r.height()] })));
}
out.push(Action::SwitchTool("selection".into()));
out
}
fn reset(&mut self) {
self.rect = None;
self.drag = None;
}
}
/// Whether two rectangles are the same to a thousandth of a point.
fn same(a: Rect, b: Rect) -> bool {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-3)
}
/// The box `r` with the sides handle `h` holds moved to `p`.
fn resized(r: Rect, h: Handle, p: Point) -> Rect {
let (mut x0, mut y0, mut x1, mut y1) = (r.x0, r.y0, r.x1, r.y1);
match h {
Handle::TopLeft | Handle::Left | Handle::BottomLeft => x0 = p.x.min(x1 - MIN),
Handle::TopRight | Handle::Right | Handle::BottomRight => x1 = p.x.max(x0 + MIN),
Handle::Top | Handle::Bottom => {}
}
match h {
Handle::TopLeft | Handle::Top | Handle::TopRight => y0 = p.y.min(y1 - MIN),
Handle::BottomLeft | Handle::Bottom | Handle::BottomRight => y1 = p.y.max(y0 + MIN),
Handle::Left | Handle::Right => {}
}
Rect::new(x0, y0, x1, y1)
}
impl Tool for CropImageTool {
fn id(&self) -> &'static str {
ID
}
fn busy(&self) -> bool {
self.drag.is_some()
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let Some((id, image, r)) = self.current(cx) else { return vec![] };
match ev.kind {
PointerKind::Down => {
self.drag = match hit_handle(r, ev.pos, cx.tol(5.0)) {
Some(h) => Some(Drag::Handle(h, r)),
None => r.contains(ev.pos).then_some(Drag::Move(ev.pos, r)),
};
}
PointerKind::Drag => {
let next = match self.drag {
Some(Drag::Handle(h, from)) => within(resized(from, h, ev.pos), image),
Some(Drag::Move(start, from)) => {
let d: Vec2 = ev.pos - start;
slid_within(from + d, image)
}
None => return vec![],
};
self.rect = Some((Some(id), next));
}
PointerKind::Up => self.drag = None,
PointerKind::DoubleClick => return self.apply(cx),
PointerKind::Move => {}
}
vec![]
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
match key {
ToolKey::Enter => self.apply(cx),
ToolKey::Escape => {
self.reset();
vec![Action::SwitchTool("selection".into())]
}
_ => vec![],
}
}
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
matches!(key, ToolKey::Enter | ToolKey::Escape) && self.current(cx).is_some()
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let Some((_, image, r)) = self.current(cx) else { return vec![] };
let shade = [0, 0, 0, 110];
let quad = |x0: f64, y0: f64, x1: f64, y1: f64| [Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)];
// The image outside the box, dimmed: above, below, then left and right of it.
let mut out: Vec<Overlay> = [
quad(image.x0, image.y0, image.x1, r.y0),
quad(image.x0, r.y1, image.x1, image.y1),
quad(image.x0, r.y0, r.x0, r.y1),
quad(r.x1, r.y0, image.x1, r.y1),
]
.into_iter()
.filter(|q| (q[2].x - q[0].x) > 1e-9 && (q[2].y - q[0].y) > 1e-9)
.map(|quad| Overlay::Highlight { quad, color: shade })
.collect();
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
out.extend(corners.iter().zip(corners.iter().cycle().skip(1)).map(|(a, b)| Overlay::Line { a: *a, b: *b, color: CYAN, dashed: false }));
out.extend(Handle::ALL.iter().map(|h| Overlay::Handle { p: h.pos(r), color: CYAN }));
out.push(Overlay::Label { p: Point::new(r.x0, r.y1), text: cx.size_label(r.width(), r.height()), color: CYAN });
out
}
fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor {
let Some((_, _, r)) = self.current(cx) else { return Cursor::Arrow };
match hit_handle(r, p, cx.tol(5.0)) {
Some(Handle::Top | Handle::Bottom) => Cursor::ResizeV,
Some(Handle::Left | Handle::Right) => Cursor::ResizeH,
Some(Handle::TopLeft | Handle::BottomRight) => Cursor::ResizeNwSe,
Some(Handle::TopRight | Handle::BottomLeft) => Cursor::ResizeNeSw,
None if r.contains(p) => Cursor::Move,
None => Cursor::Arrow,
}
}
/// `rect`: the box as `[x, y, width, height]` once it's been dragged or set (until then it's
/// [`initial_box`]).
fn options(&self) -> Value {
match self.rect {
Some((_, r)) => json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }),
None => json!({}),
}
}
/// `rect` `[x, y, width, height]` sets the box (kept within the selected image when used);
/// anything else puts it back where it starts.
fn set_option(&mut self, key: &str, value: &Value) {
if key != "rect" {
return;
}
let n: Vec<f64> = value.as_array().map(|v| v.iter().filter_map(Value::as_f64).filter(|n| n.is_finite()).collect()).unwrap_or_default();
self.rect = match n.as_slice() {
[x, y, w, h] => Some((None, Rect::new(*x, *y, x + w, y + h))),
_ => None,
};
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.reset();
vec![]
}
}
#[cfg(test)]
mod tests {
use vectorcraft_doc::{ImageObject, Node};
use vectorcraft_geom::Affine;
use super::*;
use crate::testutil::{cx, paint};
/// A 500 × 500 document (one artboard) with a 100 × 50 px image drawn at twice that size from
/// `at`, selected.
fn doc_with_image(at: (f64, f64)) -> (Document, Selection) {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let im = ImageObject {
key: "k".into(),
width: 100,
height: 50,
xf: Affine::translate(at) * Affine::scale(2.0),
link: None,
placement: Default::default(),
};
d.insert(Some(l), 0, Node::new(id, NodeKind::Image(im))).unwrap();
let mut s = Selection::default();
s.add(id);
(d, s)
}
fn drag(t: &mut CropImageTool, cx: &ToolContext, from: (f64, f64), to: (f64, f64)) {
for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
assert!(t.pointer(cx, &PointerEvent::new(kind, x, y)).is_empty());
}
}
fn crop_rect(acts: &[Action]) -> Option<Vec<f64>> {
acts.iter().find_map(|a| match a {
Action::Exec(c, v) if c == "object.cropImage" => Some(v["rect"].as_array()?.iter().filter_map(Value::as_f64).collect()),
_ => None,
})
}
#[test]
fn the_box_is_dragged_by_its_handles_and_inside_within_the_image() {
let (d, s) = doc_with_image((50.0, 60.0));
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = CropImageTool::default();
// An image inside its artboard: the box starts on all of it, and Enter has nothing to cut.
assert_eq!(t.cursor(&cx, Point::new(50.0, 60.0), Mods::default()), Cursor::ResizeNwSe);
assert_eq!(t.cursor(&cx, Point::new(150.0, 110.0), Mods::default()), Cursor::Move);
assert!(t.claims_key(&cx, ToolKey::Enter));
// The top-left handle in, then the box dragged left past the image's edge: it stops there.
drag(&mut t, &cx, (50.0, 60.0), (80.0, 70.0));
assert_eq!(t.options()["rect"], json!([80.0, 70.0, 170.0, 90.0]));
drag(&mut t, &cx, (150.0, 110.0), (50.0, 110.0));
assert_eq!(t.options()["rect"], json!([50.0, 70.0, 170.0, 90.0]));
// A handle dragged past the opposite side leaves the box at least a point wide.
drag(&mut t, &cx, (220.0, 115.0), (0.0, 115.0));
assert_eq!(t.options()["rect"], json!([50.0, 70.0, 1.0, 90.0]));
drag(&mut t, &cx, (51.0, 115.0), (180.0, 115.0));
// The outside of the box is dimmed, the box drawn with its handles.
let ov = t.overlays(&cx);
assert_eq!(ov.iter().filter(|o| matches!(o, Overlay::Highlight { .. })).count(), 2, "above and right of the box");
assert_eq!(ov.iter().filter(|o| matches!(o, Overlay::Handle { .. })).count(), 8);
// Enter crops to it and goes back to the Selection tool.
let acts = t.key(&cx, ToolKey::Enter, Mods::default());
assert_eq!(crop_rect(&acts), Some(vec![50.0, 70.0, 130.0, 90.0]));
assert_eq!(acts.last(), Some(&Action::SwitchTool("selection".into())));
assert!(t.options().get("rect").is_none(), "the next crop starts afresh");
assert!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())).is_none(), "the whole image: nothing to cut");
}
#[test]
fn the_box_starts_on_the_part_over_the_artboard_and_escape_cancels() {
// 200 × 100 from (-50, 100): its left 50 pt hang off the artboard.
let (d, s) = doc_with_image((-50.0, 100.0));
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = CropImageTool::default();
drag(&mut t, &cx, (100.0, 150.0), (110.0, 150.0));
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("selection".into())]);
assert_eq!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(vec![0.0, 100.0, 150.0, 100.0]));
// The Control bar sets the box; it stays within the image.
t.set_option("rect", &json!([100, 120, 500, 20]));
assert_eq!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(vec![100.0, 120.0, 50.0, 20.0]));
// Nothing selected: no box, and the keys go elsewhere.
let none = Selection::default();
let cx = crate::testutil::cx(&d, &none, &p);
assert!(t.overlays(&cx).is_empty() && !t.claims_key(&cx, ToolKey::Enter));
}
#[test]
fn the_tool_is_made_by_its_id() {
assert_eq!(crate::create(ID).id(), ID);
}
}
+4
View File
@@ -11,6 +11,7 @@ pub mod bbox;
pub mod builder;
pub mod catalog;
pub mod corners;
pub mod cropimage;
pub mod cut;
pub mod direct;
pub mod distort;
@@ -431,6 +432,8 @@ pub enum Cursor {
PenDelete,
PenClose,
PenContinue,
/// While drawing, over an end of another open path (a click joins the two).
PenJoin,
/// Over the last anchor of the path being drawn (a click retracts its outgoing handle), or with
/// Alt held over a selected path's handle or anchor (the Anchor Point tool's gesture).
PenConvert,
@@ -591,6 +594,7 @@ pub fn create(id: &str) -> Box<dyn Tool> {
.or_else(|| extra::create(other))
.or_else(|| slice::create(other))
.or_else(|| printtiling::create(other))
.or_else(|| cropimage::create(other))
.or_else(|| cut::create(other))
.unwrap_or_else(|| Box::new(NoopTool(tool_info(other).map(|t| t.id).unwrap_or("selection")))),
}
+47 -3
View File
@@ -11,8 +11,9 @@
//! it a corner, dragging an anchor pulls out new symmetric handles and dragging a segment reshapes
//! it. Cmd held lends the selection tool used last for a drag (the engine's
//! `Session::pointer`); the path being drawn goes on afterwards while it stays selected.
//! Enter/Esc (or switching tools) ends the path. Clicking the end of a selected open path continues
//! it. The rubber-band preview shows the next segment (Enable Rubber Band for Pen Tool). Auto Add/Delete: between paths, a click on a
//! Enter/Esc (or switching tools) ends the path. Clicking an end of an open path continues it
//! (selecting it); while drawing, clicking an end of another open path joins the two into one
//! (#776). The rubber-band preview shows the next segment (Enable Rubber Band for Pen Tool). Auto Add/Delete: between paths, a click on a
//! segment of a selected path adds an anchor there and a click on one of its anchors deletes it
//! (Shift held or General → Disable Auto Add/Delete starts a new path instead). On a selected
//! blend's spine a click adds a point (on a point no key object sits on: deletes it).
@@ -80,6 +81,29 @@ fn active_path(cx: &ToolContext) -> Option<(NodeId, Point, Point, Point)> {
Some((id, first, last.p, last.h_out))
}
/// An end of an open path (one subpath, not `except`) under `p`, within `tol`: the path the Pen
/// continues or joins to, and whether it's the path's first anchor. Only paths that can be edited,
/// not guides.
fn open_end_at(cx: &ToolContext, p: Point, tol: f64, except: Option<NodeId>) -> Option<(NodeId, bool)> {
let id = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options())?.leaf;
if Some(id) == except || !cx.doc.is_editable(id) {
return None;
}
let NodeKind::Path { path, guide: false, .. } = &cx.doc.node(id)?.kind else { return None };
let [sp] = path.subpaths.as_slice() else { return None };
if sp.closed {
return None;
}
let (first, last) = (sp.anchors.first()?.p, sp.anchors.last()?.p);
if p.distance(last) <= tol {
Some((id, false))
} else if p.distance(first) <= tol {
Some((id, true))
} else {
None
}
}
/// The last anchor of `id`'s last subpath: (subpath, anchor).
fn last_anchor(cx: &ToolContext, id: NodeId) -> Option<(usize, usize)> {
let pd = cx.doc.node(id)?.path_data()?;
@@ -160,6 +184,12 @@ impl Tool for PenTool {
self.handle = Some((id, si, ai, last));
return vec![Action::Begin("Convert Anchor Point".into()), set_out_handle(id, si, ai, last)];
}
// An end of another open path: the two become one, and the path is finished.
if let Some((other, at_first)) = open_end_at(cx, p, tol, Some(id)) {
self.stop();
let end = if at_first { "first" } else { "last" };
return vec![Action::Exec("path.join".into(), json!({"ids": [id.0, other.0], "ends": ["last", end]}))];
}
if let Some(acts) = self.alt_convert(cx, ev) {
return acts;
}
@@ -184,6 +214,15 @@ impl Tool for PenTool {
}
return vec![];
}
// Continue any other open path from the end clicked, selecting it.
if let Some((id, at_first)) = open_end_at(cx, p, tol, None) {
(self.drawing, self.path) = (true, Some(id));
let mut out = vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))];
if at_first {
out.push(Action::Exec("path.reverse".into(), json!({"ids": [id.0]})));
}
return out;
}
if let Some(act) = auto_add_delete(cx, ev.pos, ev.mods, tol) {
return vec![act];
}
@@ -306,6 +345,9 @@ impl Tool for PenTool {
if p.distance(last) <= tol {
return Cursor::PenConvert;
}
if open_end_at(cx, p, tol, Some(id)).is_some() {
return Cursor::PenJoin;
}
}
if alt_converts(cx, p, m) {
return Cursor::PenConvert;
@@ -316,7 +358,9 @@ impl Tool for PenTool {
Some([_]) => return Cursor::PenAdd,
_ => {}
}
if active_path(cx).is_some_and(|(_, first, last, _)| p.distance(last) <= tol || p.distance(first) <= tol) {
if active_path(cx).is_some_and(|(_, first, last, _)| p.distance(last) <= tol || p.distance(first) <= tol)
|| open_end_at(cx, p, tol, None).is_some()
{
return Cursor::PenContinue;
}
match auto_add_delete(cx, p, m, tol) {
+46 -5
View File
@@ -73,9 +73,10 @@ pub struct SelectionTool {
guide: GuideEdit,
}
/// Snapping for the selection moved as a whole, its targets gathered when the move begins: Smart
/// Guides line its bounds up with the other art; with them off, View → Snap to Point lands the
/// point it was grabbed by on an anchor or a ruler guide; Snap to Pixel puts its top-left on whole
/// Snapping for the selection moved as a whole, its targets gathered when the move begins: View →
/// Snap to Grid lands its bounds on the grid (#740), taking over from the rest; otherwise Smart
/// Guides line its bounds up with the other art, and with them off, View → Snap to Point lands the
/// point it was grabbed by on an anchor or a ruler guide. Snap to Pixel puts its top-left on whole
/// pixels.
pub(crate) struct MoveSnap {
bounds: Option<Rect>,
@@ -87,14 +88,19 @@ impl MoveSnap {
pub(crate) fn new(cx: &ToolContext) -> Self {
Self {
bounds: selection_bounds(cx),
targets: cx.smart_guides.then(|| Targets::for_move(cx)),
points: Targets::snap_to_point(cx, &cx.selection.objects),
targets: (cx.smart_guides && !cx.snap_to_grid).then(|| Targets::for_move(cx)),
points: if cx.snap_to_grid { None } else { Targets::snap_to_point(cx, &cx.selection.objects) },
}
}
/// The move by `d` of the selection grabbed at `start`, snapped, and its guides.
pub(crate) fn snap(&self, cx: &ToolContext, start: Point, mut d: Vec2) -> (Vec2, Vec<Overlay>) {
let mut guides = vec![];
if cx.snap_to_grid
&& let Some(b) = self.bounds
{
d += grid_pull(b + d, cx.grid_step());
}
if let Some(t) = &self.points {
let (q, ov) = t.snap_point(start + d, cx.tol(cx.snap_tolerance));
d = q - start;
@@ -115,6 +121,15 @@ impl MoveSnap {
}
}
/// The shift that lands `r` on the grid (a gridline every `step`), on each axis by whichever of its
/// two edges and its centre is nearest a gridline, however far that is.
fn grid_pull(r: Rect, step: f64) -> Vec2 {
let pull = |vs: [f64; 3]| {
vs.iter().map(|v| vectorcraft_geom::snap::snap_to_grid(*v, step, 0.0) - v).min_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or(0.0)
};
Vec2::new(pull([r.x0, r.center().x, r.x1]), pull([r.y0, r.center().y, r.y1]))
}
pub fn matrix_json(a: Affine) -> Value {
let c = a.as_coeffs();
json!([c[0], c[1], c[2], c[3], c[4], c[5]])
@@ -517,6 +532,32 @@ mod tests {
assert_eq!(a, vec![Action::Commit]);
}
/// #740: with Snap to Grid on, a moved object lands on the grid (every 9 pt by default) by
/// whichever of its edges or its centre is nearest a gridline, on each axis.
#[test]
fn a_move_lands_the_nearest_edge_or_centre_on_the_grid() {
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = ToolContext { snap_to_grid: true, smart_guides: true, ..cx(&d, &s, &p) };
let moved = |to: (f64, f64)| {
let mut t = SelectionTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 150.0));
let a = t.pointer(&cx, &ev(PointerKind::Drag, to.0, to.1));
match a.get(1) {
Some(Action::Preview(_, v)) => (v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()),
other => panic!("{other:?}"),
}
};
// Bounds 100–200 moved by (13, 4): the centres (163, 154) are nearest gridlines (162, 153).
let (x, y) = moved((163.0, 154.0));
assert!((x - 12.0).abs() < 1e-9 && (y - 3.0).abs() < 1e-9, "{x} {y}");
// Moved by (7, 0): the right edge is on a gridline (207) and the top goes up to one (99).
let (x, y) = moved((157.0, 150.0));
assert!((x - 7.0).abs() < 1e-9 && (y + 1.0).abs() < 1e-9, "{x} {y}");
}
#[test]
fn shift_drag_on_a_selected_object_moves_it_constrained() {
let (d, id) = doc_with_rect();
+3 -1
View File
@@ -483,7 +483,9 @@ fn cursor_icon(c: Cursor) -> egui::CursorIcon {
Cursor::ResizeNwSe => C::ResizeNwSe,
Cursor::ResizeNeSw => C::ResizeNeSw,
Cursor::Rotate => C::Alias,
Cursor::Pen | Cursor::PenAdd | Cursor::PenDelete | Cursor::PenClose | Cursor::PenContinue | Cursor::PenConvert => C::Crosshair,
Cursor::Pen | Cursor::PenAdd | Cursor::PenDelete | Cursor::PenClose | Cursor::PenContinue | Cursor::PenJoin | Cursor::PenConvert => {
C::Crosshair
}
Cursor::Text => C::Text,
Cursor::Hand => C::Grab,
Cursor::HandGrab => C::Grabbing,
+9 -1
View File
@@ -84,6 +84,12 @@ fn pen(p: &mut Ink, o: Pos2, badge: &str) {
}
"-" => line(p, b + vec2(0.0, 3.0), b + vec2(6.0, 3.0)),
"/" => line(p, b + vec2(0.0, 6.0), b + vec2(5.0, 0.0)),
// Join: a segment running into a square end point.
"j" => {
line(p, b + vec2(0.0, 6.0), b + vec2(3.5, 2.5));
let sq = [(3.0, -1.0), (7.0, -1.0), (7.0, 3.0), (3.0, 3.0)].map(|(x, y)| b + vec2(x, y));
poly(p, sq.to_vec(), INK, INK);
}
"^" => {
line(p, b + vec2(0.0, 6.0), b + vec2(3.0, 0.0));
line(p, b + vec2(3.0, 0.0), b + vec2(6.0, 6.0));
@@ -270,6 +276,7 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
Cursor::PenDelete => pen(ink, p, "-"),
Cursor::PenClose => pen(ink, p, "o"),
Cursor::PenContinue => pen(ink, p, "/"),
Cursor::PenJoin => pen(ink, p, "j"),
Cursor::PenConvert => pen(ink, p, "^"),
Cursor::Text => ibeam(ink, p),
Cursor::AddStop => stop_badge(ink, p, true),
@@ -425,7 +432,7 @@ mod tests {
use crate::VectorcraftApp;
/// Every cursor with a glyph.
const GLYPHS: [Cursor; 32] = [
const GLYPHS: [Cursor; 33] = [
Cursor::Arrow,
Cursor::ArrowHollow,
Cursor::Move,
@@ -441,6 +448,7 @@ mod tests {
Cursor::PenDelete,
Cursor::PenClose,
Cursor::PenContinue,
Cursor::PenJoin,
Cursor::PenConvert,
Cursor::Text,
Cursor::Eyedropper,
+1
View File
@@ -67,6 +67,7 @@ fn order(kind: &str) -> &'static [&'static str] {
match kind {
"offsetPath" => &["offset", "joins", "miterLimit"],
"splitIntoGrid" => &["rows", "columns", "gutter"],
"artboardOptions" => &["name", "width", "height"],
_ => &[],
}
}
+10 -2
View File
@@ -114,7 +114,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
app.ui.dialog = None;
let n = r["files"].as_array().map_or(0, Vec::len);
let missing = r["missingLinks"].as_array().map_or(0, Vec::len);
let note = if missing > 0 { format!(" ({missing} linked file(s) not found)") } else { String::new() };
// The fonts left out: their license doesn't allow it, or they aren't on this computer.
let fonts = r["skippedFonts"].as_array().into_iter().flatten().filter_map(|f| f["font"].as_str()).collect::<Vec<_>>().join(", ");
let mut note = if missing > 0 { format!(" ({missing} linked file(s) not found)") } else { String::new() };
if !fonts.is_empty() {
note.push_str(&format!(" (fonts not copied: {fonts})"));
}
if web {
let (name, data) = (r["name"].as_str().unwrap_or("package.zip"), r["dataBase64"].as_str().unwrap_or_default());
let bytes = vectorcraft_format::base64_decode(data).ok_or("the package came back damaged")?;
@@ -124,11 +129,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
}
let folder = r["folder"].as_str().unwrap_or_default().to_string();
app.status(format!("Packaged {n} file(s) in {folder}{note}"));
let shown_note = if missing > 0 {
let mut shown_note = if missing > 0 {
format!(" ({})", crate::i18n::fmt(tl!("{count} linked file(s) not found"), &[("count", &missing.to_string())]))
} else {
String::new()
};
if !fonts.is_empty() {
shown_note.push_str(&format!(" ({})", crate::i18n::fmt(tl!("fonts not copied: {fonts}"), &[("fonts", &fonts)])));
}
let detail = crate::i18n::fmt(
tl!("{count} file(s) in {folder}{note}. Show the package folder?"),
&[("count", &n.to_string()), ("folder", &folder), ("note", &shown_note)],
+4 -2
View File
@@ -330,7 +330,8 @@ mod tests {
#[test]
fn save_a_copy_and_template_suggest_their_names() {
let (mut app, written, picks) = desktop("copy.vectorcraft");
app.session.prefs.templates_folder = "/templates".into();
let folder = vectorcraft_testkit::temp_dir("save-template-dialog");
app.session.prefs.templates_folder = folder.to_string_lossy().into_owned();
app.run("file.saveCopy", json!({})).unwrap();
assert_eq!(picks.borrow()[0].name, "Untitled-1 copy.vectorcraft");
assert!(app.ui.dialog.is_none(), "the native format has no options");
@@ -338,7 +339,8 @@ mod tests {
assert!(app.session.active().unwrap().path.is_none() && app.session.active().unwrap().is_dirty());
app.run("file.saveAsTemplate", json!({})).unwrap();
let pick = &picks.borrow()[1];
assert_eq!((pick.name.as_str(), pick.folder.as_deref()), ("Untitled-1 template.vctemplate", Some("/templates")));
assert_eq!(pick.name, "Untitled-1 template.vctemplate");
assert_eq!(pick.folder.as_deref().map(std::path::Path::new), Some(folder.as_path()));
assert_eq!(pick.filters, [("VectorCraft Template", &["vctemplate"][..])]);
assert_eq!(written.borrow()[1].0, "copy.vectorcraft", "the picked name is kept");
}
@@ -2,7 +2,7 @@
//! under Window → Swatch Libraries → User Defined) or a file picked in a save dialog (a download
//! on the web). OK runs `swatch.library.save`.
//!
//! Fields: `name`, `format` (`vcswatches`, `gpl` or `css`), `user` (save to the user library
//! Fields: `name`, `format` (`vcswatches`, `gpl`, `ase` or `css`), `user` (save to the user library
//! folder), `selectedOnly` and `names` (the swatches selected in the Swatches panel), `__user`
//! (there is a user library folder).
//!
@@ -34,12 +34,17 @@ pub fn open(app: &mut VectorcraftApp, names: Vec<String>) -> Result<Value, Strin
/// The fields a Save … Library dialog opens with: the document's name, Save To the user library
/// folder when there is one (`user`), and the panel's selected `names`.
pub(super) fn fields(app: &VectorcraftApp, user: bool, names: Vec<String>) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let title = st.title();
let name = title.rsplit_once('.').map_or(title.as_str(), |(s, _)| s).to_string();
let name = document_name(app).ok_or("no document open")?;
Ok(json!({"name": name, "user": user, "__user": user, "selectedOnly": false, "names": names}))
}
/// The active document's name without its extension: the library name the save commands use when
/// none is given.
fn document_name(app: &VectorcraftApp) -> Option<String> {
let title = app.session.active()?.title();
Some(title.rsplit_once('.').map_or(title.as_str(), |(s, _)| s).to_string())
}
fn format_of(d: &Dialog) -> PaletteFormat {
PaletteFormat::parse(&d.str("format")).unwrap_or(PaletteFormat::Native)
}
@@ -62,6 +67,9 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
if format_of(d) == PaletteFormat::Gpl {
widgets::dim_label(ui, tl!("GPL palettes keep solid colours only, as RGB."));
}
if format_of(d) == PaletteFormat::Ase {
widgets::dim_label(ui, tl!("Swatch exchange files keep solid colors only."));
}
false
}
@@ -104,8 +112,10 @@ pub(super) fn params(d: &Dialog) -> Value {
p
}
/// Run save command `cmd` with `p`: into the user library folder, else to a file the user picks
/// (extension `ext`).
/// Run save command `cmd` with `p`: into the user library folder, else to a file the user picks.
/// The save panel suggests the file name that a save into the user library folder uses: the name
/// (the document's when it is empty) with extension `ext`. The web downloads the file under that
/// name.
pub(super) fn save(app: &mut VectorcraftApp, d: &Dialog, cmd: &str, ext: &str, p: Value) -> Result<Value, String> {
if p["user"] == json!(true) {
let r = run_and_close(app, cmd, p)?;
@@ -113,7 +123,9 @@ pub(super) fn save(app: &mut VectorcraftApp, d: &Dialog, cmd: &str, ext: &str, p
return Ok(r);
}
app.ui.dialog = None;
crate::io::save_command_output(app, cmd, ext, p).map(|path| json!({ "path": path }))
let name = Some(d.str("name").trim().to_string()).filter(|n| !n.is_empty()).or_else(|| document_name(app)).unwrap_or_default();
let file = vectorcraft_engine::cmd::swatchlib::library_file_name(&name, ext);
crate::io::save_command_output_named(app, cmd, &file, p).map(|path| json!({ "path": path }))
}
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
+11
View File
@@ -370,3 +370,14 @@ fn a_dialog_opens_with_its_first_field_focused_so_typing_and_enter_apply() {
let after = bounds(&app);
assert!((after.x0 - before.x0 - 15.0).abs() < 1e-6 && (after.y0 - before.y0).abs() < 1e-6, "{before:?} → {after:?}");
}
/// #793: Artboard Options lists its fields as Name, Width, Height, not by key.
#[test]
fn artboard_options_lists_name_then_width_and_height() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 612, "height": 792})).unwrap();
open(&mut app, "artboardOptions", json!({"index": 0, "name": "Artboard 1", "width": 612, "height": 792, "x": 0, "y": 0}));
let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
let at = |s: &str| text.find(s).unwrap_or_else(|| panic!("{s} in {text}"));
assert!(at("Name") < at("Width") && at("Width") < at("Height"), "{text}");
}
@@ -106,6 +106,30 @@ fn the_web_downloads_a_zip() {
assert!(got[0].1 > 100);
}
#[test]
fn fonts_left_out_of_the_package_are_named() {
let dir = Folder::new("fonts");
let mut app = saved(&dir);
app.run("text.create", json!({"x": 10, "y": 40, "text": "Kept"})).unwrap();
app.run("text.create", json!({"x": 10, "y": 80, "text": "Gone", "font": "No Such Font Family"})).unwrap();
app.run("ui.packageDialog", json!({})).unwrap();
let out = dir.path("out");
std::fs::create_dir_all(&out).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("folder".into(), json!(out));
let r = confirm(&mut app).unwrap();
assert_eq!(r["skippedFonts"], json!([{"font": "No Such Font Family Regular", "reason": "not available on this computer"}]));
let gone = "fonts not copied: No Such Font Family Regular";
assert!(app.ui.status.contains(gone), "{}", app.ui.status);
let detail = app.ui.dialog.as_ref().unwrap().str("detail");
assert!(detail.contains(gone) && !detail.contains("Source Sans 3"), "{detail}");
// The web's download says so too.
app.ui.dialog = None;
app.services.download = Some(Box::new(|_: &str, _: &[u8]| {}));
app.run("ui.packageDialog", json!({})).unwrap();
confirm(&mut app).unwrap();
assert!(app.ui.status.contains(gone), "{}", app.ui.status);
}
#[test]
fn package_without_a_location_says_so() {
let dir = Folder::new("empty");
+3
View File
@@ -161,6 +161,7 @@
Appearance panel Panel Apariencia
Applies when the linked file is relinked or updated. Se aplica al volver a vincular o actualizar el archivo vinculado.
Applies the next time VectorCraft starts. Se aplica la próxima vez que se inicie VectorCraft.
Apply Aplicar
Apply Brush Aplicar pincel
Apply Character Style Aplicar estilo de carácter
Apply Effect Aplicar efecto
@@ -2639,6 +2640,7 @@
Swash Decorativa
Swatch Conflict Conflicto de muestras
Swatch Conflicts Conflictos de muestras
Swatch exchange files keep solid colors only. Los archivos de intercambio de muestras solo conservan colores sólidos.
Swatch Libraries Bibliotecas de muestras
Swatch Libraries Menu Menú Bibliotecas de muestras
Swatch Library Biblioteca de muestras
@@ -2989,6 +2991,7 @@
Scrub Numeric Fields by Dragging Ajustar campos numéricos arrastrando
{count} file(s) in {folder}{note}. Show the package folder? {count} archivo(s) en {folder}{note}. ¿Mostrar la carpeta del paquete?
{count} linked file(s) not found No se encontraron {count} archivo(s) vinculado(s)
fonts not copied: {fonts} fuentes no copiadas: {fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? {count} imagen(es) vinculada(s) cambiaron desde que se guardó este documento. ¿Mostrar las versiones nuevas?
{count} more rules: Export writes every one. {count} reglas más: Exportar las escribe todas.
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Se omitieron {count} objetos sin nombre: ponles nombre o activa Objetos sin nombre en el menú del panel.
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -162,6 +162,7 @@
Appearance panel Panneau Aspect
Applies when the linked file is relinked or updated. S’applique lorsque le fichier lié est de nouveau lié ou mis à jour.
Applies the next time VectorCraft starts. S’applique au prochain démarrage de VectorCraft.
Apply Appliquer
Apply Brush Appliquer la forme
Apply Character Style Appliquer le style de caractère
Apply Effect Appliquer l’effet
@@ -2636,6 +2637,7 @@
Swash Lettres ornées
Swatch Conflict Conflit de nuances
Swatch Conflicts Conflits de nuances
Swatch exchange files keep solid colors only. Les fichiers d’échange de nuances ne conservent que les couleurs unies.
Swatch Libraries Bibliothèques de nuances
Swatch Libraries Menu Menu Bibliothèques de nuances
Swatch Library Bibliothèque de nuances
@@ -2986,6 +2988,7 @@
Scrub Numeric Fields by Dragging Modifier les champs numériques en faisant glisser
{count} file(s) in {folder}{note}. Show the package folder? {count} fichier(s) dans {folder}{note}. Afficher le dossier de l’assemblage ?
{count} linked file(s) not found {count} fichier(s) lié(s) introuvable(s)
fonts not copied: {fonts} polices non copiées : {fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? {count} image(s) liée(s) modifiée(s) depuis l’enregistrement de ce document. Afficher les nouvelles versions ?
{count} more rules: Export writes every one. {count} règles de plus : Exporter les écrit toutes.
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} objets sans nom omis : nommez-les ou activez Objets sans nom dans le menu du panneau.
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -161,6 +161,7 @@
Appearance panel Pannello Aspetto
Applies when the linked file is relinked or updated. Si applica quando il file collegato viene ricollegato o aggiornato.
Applies the next time VectorCraft starts. Si applica al prossimo avvio di VectorCraft.
Apply Applica
Apply Brush Applica pennello
Apply Character Style Applica stile carattere
Apply Effect Applica effetto
@@ -2639,6 +2640,7 @@
Swash Ornamentale
Swatch Conflict Conflitto campioni
Swatch Conflicts Conflitti campioni
Swatch exchange files keep solid colors only. I file di scambio campioni conservano solo i colori pieni.
Swatch Libraries Librerie campioni
Swatch Libraries Menu Menu Librerie campioni
Swatch Library Libreria campioni
@@ -2989,6 +2991,7 @@
Scrub Numeric Fields by Dragging Regola i campi numerici trascinando
{count} file(s) in {folder}{note}. Show the package folder? {count} file in {folder}{note}. Vuoi mostrare la cartella del pacchetto?
{count} linked file(s) not found File collegati non trovati: {count}
fonts not copied: {fonts} font non copiati: {fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? Immagini collegate modificate dopo il salvataggio di questo documento: {count}. Vuoi mostrare le nuove versioni?
{count} more rules: Export writes every one. Altre {count} regole: Esporta le scrive tutte.
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} oggetti senza nome esclusi: assegna loro un nome o attiva Oggetti senza nome nel menu del pannello.
Can't render this file because it contains an unexpected character in line 2 and column 73.
+568 -1
View File
@@ -6,7 +6,8 @@
# Japanese localisation was copied. Toggles read as their action (「…を表示」「…を隠す」).
#
# Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`,
# tested). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
# tested) — and the status and error messages (`@msg` rows at the end, `COMPLETE_MESSAGES`, tested).
# Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language
# names, OpenType, the built-in workspace names and the bracketed perspective grid preset names.
About VectorCraft VectorCraft について
All Scripts すべての文字
@@ -342,6 +343,7 @@
Same 共通
Appearance アピアランス
Appearance Attribute アピアランス属性
Apply 適用
Blending Mode 描画モード
Fill & Stroke 塗りと線
Fill Color カラー (塗り)
@@ -2416,6 +2418,7 @@
Swash スワッシュ
Swatch Conflict スウォッチの競合
Swatch Conflicts スウォッチの競合
Swatch exchange files keep solid colors only. スウォッチ交換ファイルにはベタ塗りのカラーのみが保存されます。
Swatch Library スウォッチライブラリ
Swatch Name: スウォッチ名:
Swatch Options スウォッチオプション
@@ -2666,6 +2669,7 @@
to →
{count} file(s) in {folder}{note}. Show the package folder? {folder} に {count} 個のファイル{note}。パッケージフォルダーを表示しますか?
{count} linked file(s) not found リンクファイルが {count} 個見つかりません
fonts not copied: {fonts} コピーされなかったフォント:{fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? 保存後に {count} 個のリンク画像が変更されています。新しいバージョンを表示しますか?
{count} more rules: Export writes every one. ほかに {count} 個のルールがあります。書き出しにはすべて含まれます。
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 名前のないオブジェクト {count} 個を除外しました。名前を付けるか、パネルメニューで「名前のないオブジェクト」をオンにしてください。
@@ -3152,3 +3156,566 @@ theme Appearance 外観
Draft ドラフト
Good 標準
Best 高品質
# Status and error messages (`@msg`), translated where the status bar shows them; the message itself
# stays English for agents and tests. `{_1}`, `{_2}` … stand for the `{}` of the format string, in order
# (`complete_languages_translate_every_message` lists any that are missing). Command ids, parameter
# names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are.
# Japanese: no final 。 (these are status lines, and reasons that follow a colon), unless the English ends
# with a period; a space between Japanese text and an adjacent Latin word, number or {placeholder}.
@msg Reset {_1} {_1} をリセットしました
@msg Saving 保存中
@msg Saving {_1} {_1} を保存中
@msg Sent to {_1} {_1} に送信しました
@msg `to` must be "corner" or "smooth" `to` には "corner" または "smooth" を指定してください
@msg a layer couldn't be read 読み込めなかったレイヤーがあります
@msg it has more than one artboard アートボードが複数あります
@msg its editing data has no layers 編集データにレイヤーがありません
@msg its editing data is damaged 編集データが破損しています
@msg {_1} files {_1} 個のファイル
@msg A browser with WebGPU or WebGL2 is required. WebGPU または WebGL2 に対応したブラウザーが必要です。
@msg Loading VectorCraft… VectorCraft を読み込んでいます…
@msg Reload the page to go on (changes not saved yet may be lost). 続けるにはページを再読み込みしてください (未保存の変更は失われる場合があります)。
@msg The graphics were lost and couldn't be restarted. グラフィックス機能が利用できなくなり、再起動できませんでした。
@msg The graphics were lost and have been restarted グラフィックス機能が利用できなくなったため、再起動しました
@msg VectorCraft failed to start: {e} VectorCraft を起動できませんでした: {e}
@msg Your unsaved changes are kept in this browser: reload the page to get them back. 未保存の変更はこのブラウザーに残っています: 復元するにはページを再読み込みしてください。
@msg The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} 最初に試したグラフィックスプロセッサーではウィンドウを表示できなかったため、{summary} で VectorCraft を再起動しました
@msg not a DXF drawing DXF 図面ではありません
@msg scale must be a number from {_1} to {_2}, not {s} 縮尺は {_1} から {_2} までの数値にしてください ({s} は指定できません)
@msg the artboard to fit must be a positive size up to {_1} pt 合わせる先のアートボードのサイズは 0 より大きく {_1} pt 以下にしてください
@msg the drawing has no layout `{_1}` (it has {_2}) 図面にレイアウト `{_1}` はありません (含まれるレイアウト: {_2})
@msg this is a DWG drawing, which can't be read: save it from the CAD app as an ASCII DXF and open that DWG 図面は読み込めません: CAD アプリで ASCII DXF として保存し、そのファイルを開いてください
@msg at this scale the drawing is {w} × {h} pt, more than the canvas holds: choose a smaller scale or fit it to the artboard この縮尺では図面が {w} × {h} pt になり、カンバスに収まりません: 縮尺を小さくするか、アートボードに合わせてください
@msg the scale is not a usable number 縮尺が有効な数値ではありません
@msg the drawing is too large to open 図面が大きすぎて開けません
@msg scale must be a number from {_1} to {_2}, not {_3} 縮尺は {_1} から {_2} までの数値にしてください ({_3} は指定できません)
@msg image '{key}' has no pixels and was left out 画像「{key}」はピクセルがないため省略しました
@msg Embedded {n} image(s) 画像を {n} 枚埋め込みました
@msg object {0} cannot have children オブジェクト {0} には子オブジェクトを含められません
@msg range `{s}` is empty 範囲 `{s}` が空です
@msg range `{s}`: `{part}` names no number 範囲 `{s}`: `{part}` に番号が指定されていません
@msg range `{s}`: `{part}` runs backwards 範囲 `{s}`: `{part}` が逆順になっています
@msg range `{s}`: `{t}` is not a number from 1 to {count} 範囲 `{s}`: `{t}` は 1 から {count} までの数値ではありません
@msg not a graphic style library (format `{_1}`) グラフィックスタイルライブラリではありません (形式: `{_1}`)
@msg Show All Hidden Attributes: nothing is hidden 非表示の属性をすべて表示: 非表示の属性はありません
@msg Expand: no brush strokes selected 拡張: ブラシストロークが選択されていません
@msg no brush named `{name}` `{name}` という名前のブラシが見つかりません
@msg no symbol instances selected シンボルインスタンスが選択されていません
@msg select a symbol instance シンボルインスタンスを選択してください
@msg the art has no bounds アートに境界がありません
@msg Image Trace: the traced image is missing 画像トレース: トレース元の画像が見つかりません
@msg Live Paint Merge: select a Live Paint group and the paths to add ライブペイントの結合: ライブペイントグループと、追加するパスを選択してください
@msg Live Paint: select paths or compound paths ライブペイント: パスまたは複合パスを選択してください
@msg Live Paint: these paths are too degenerate to paint ライブペイント: これらのパスは形状がつぶれすぎていてペイントできません
@msg Shape Builder: no region under the pointer シェイプ形成ツール: ポインターの下に領域がありません
@msg Shape Builder: select paths or compound paths シェイプ形成ツール: パスまたは複合パスを選択してください
@msg image data `{_1}` is missing 画像データ `{_1}` が見つかりません
@msg no Live Paint edge near that point その位置の近くにライブペイントのエッジがありません
@msg no Live Paint face at that point その位置にライブペイントの面がありません
@msg select a Live Paint group ライブペイントグループを選択してください
@msg select an Image Trace object 画像トレースオブジェクトを選択してください
@msg select objects, not layers レイヤーではなくオブジェクトを選択してください
@msg Blend colors: select at least three objects with filled colours カラーのブレンド: カラーの塗りがあるオブジェクトを 3 つ以上選択してください
@msg no saved themes 保存したテーマはありません
@msg `{keep}` is not a side of this axis `{keep}` はこの軸のどちら側でもありません
@msg unknown side `{other}` (left|right|top|bottom) `{other}` は不明な側の指定です (left|right|top|bottom)
@msg an object in perspective would leave the edited grid 遠近グリッド上のオブジェクトが編集後のグリッドの外に出てしまいます
@msg nothing to warp ワープするものがありません
@msg select an object in perspective 遠近グリッド上のオブジェクトを選択してください
@msg select the artwork to warp ワープするアートワークを選択してください
@msg select the objects to transform in perspective 遠近グリッド上で変形するオブジェクトを選択してください
@msg select type in perspective 遠近グリッド上のテキストを選択してください
@msg the object has no geometry オブジェクトに形状がありません
@msg the object has no stroke オブジェクトに線がありません
@msg the object is beyond the plane's horizon オブジェクトが面の水平線を越えた位置にあります
@msg the object isn't in perspective オブジェクトが遠近グリッド上にありません
@msg the object isn't on a perspective plane オブジェクトが遠近グリッドの面上にありません
@msg the object would cross the horizon of the perspective plane オブジェクトが遠近グリッドの面の水平線をまたいでしまいます
@msg the objects would leave the grid オブジェクトがグリッドの外に出てしまいます
@msg the pointer is beyond the plane's horizon ポインターが面の水平線を越えた位置にあります
@msg the selection isn't in perspective 選択範囲が遠近グリッド上にありません
@msg the stroke has no weight 線に線幅がありません
@msg {command} didn't create an object {command} でオブジェクトが作成されませんでした
@msg Make Guides: select paths ガイドを作成: パスを選択してください
@msg Release Guides: no guides ガイドを解除: ガイドがありません
@msg guides are locked ガイドがロックされています
@msg no saved selections 保存した選択範囲はありません
@msg no such artboard 指定されたアートボードが見つかりません
@msg cannot split an open path at its end point オープンパスは端点で分割できません
@msg empty brush stroke ブラシストロークが空です
@msg no such anchor 指定されたアンカーポイントが見つかりません
@msg no such segment 指定されたセグメントが見つかりません
@msg no such subpath 指定されたサブパスが見つかりません
@msg object {id} is not a path オブジェクト {id} はパスではありません
@msg nothing to redo やり直す操作がありません
@msg nothing to undo 取り消す操作がありません
@msg Expand Appearance: the selection has a basic appearance アピアランスを分割: 選択範囲は基本アピアランスです
@msg select (or target) objects whose appearance isn't basic 基本アピアランスではないオブジェクトを選択するか、ターゲットに指定してください
@msg {C}: no effect at index {from} {C}: インデックス {from} に効果がありません
@msg Expand: no gradient fills 拡張: グラデーションの塗りがありません
@msg Expand: nothing to expand 拡張: 拡張するものがありません
@msg batch step {_1} (`{id}`) failed: {e} バッチのステップ {_1} (`{id}`) が失敗しました: {e}
@msg BMP files are RGB or grayscale: colorModel rgb or gray BMP ファイルが対応するのは RGB とグレースケールのみです: colorModel には rgb または gray を指定してください
@msg Targa files are RGB: colorModel rgb Targa ファイルが対応するのは RGB のみです: colorModel には rgb を指定してください
@msg antiAlias `{id}`: none, art or type antiAlias に `{id}` は指定できません: none、art、type のいずれかを指定してください
@msg background {other}: transparent, white, black or a colour such as "#ff8800" 背景に {other} は指定できません: transparent、white、black、または「#ff8800」のようなカラーを指定してください
@msg no artboard {i} (0-based; the document has {count}) アートボード {i} はありません (番号は 0 始まり、このドキュメントには {count} 個あります)
@msg no artboards named アートボードが指定されていません
@msg the document has no artboard ドキュメントにアートボードがありません
@msg this format holds one artboard: export several as PDF or with document.exportForScreens この形式で書き出せるアートボードは 1 つだけです: 複数のアートボードは PDF として書き出すか、document.exportForScreens を使用してください
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) このファイルは PDF 互換性なしで保存されており、編集データを読み込めません ({why})
@msg the export wrote no file 書き出しでファイルが作成されませんでした
@msg {_1} files can be opened but not written (see document.formats) {_1} ファイルは開けますが、保存や書き出しはできません (document.formats を参照してください)
@msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: この環境にはファイルシステムがありません (開くには dataBase64 を渡し、dataBase64 を受け取るにはパスを省略してください)
@msg Save writes {_1}, not {_2}: use document.export for other formats 保存できる形式は {_1} のみで、{_2} 形式では保存できません: ほかの形式には document.export を使用してください
@msg no changes since the last save 前回の保存以降、変更はありません
@msg unknown format `{f}` (Save writes {_1}) `{f}` は不明な形式です (保存できる形式: {_1})
@msg `svg` must be an object of SVG options (see document.formats) `svg` には SVG オプションのオブジェクトを指定してください (document.formats を参照)
@msg no end record 終端レコードがありません
@msg not a stored central record 無圧縮のセントラルディレクトリレコードではありません
@msg truncated データが途中で切れています
@msg {name}: CRC mismatch {name}: CRC が一致しません
@msg {name}: no local header {name}: ローカルヘッダーがありません
@msg Flatten Transparency: select objects to flatten 透明部分を分割・統合: 分割・統合するオブジェクトを選択してください
@msg Flatten Transparency: {e} 透明部分を分割・統合: {e}
@msg balance must be between 0 and 100 バランスは 0 から 100 までの値にしてください
@msg resolutions must be between 1 and 2400 ppi 解像度は 1 から 2400 ppi までの値にしてください
@msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) `{name}` は不明なプリセットです (high、medium、low、または保存したプリセット: flattener.presets.list を参照してください)
@msg `at` must be [x, y] `at` は [x, y] の形式で指定してください
@msg `color` must be a colour `color` にはカラーを指定してください
@msg `freeform.points` must be an array `freeform.points` には配列を指定してください
@msg `{key}` must be a number `{key}` には数値を指定してください
@msg a freeform gradient keeps at least one point フリーフォームグラデーションには少なくとも 1 つのポイントが必要です
@msg freeform point {i} needs `at` [x, y] and a valid `color` フリーフォームのポイント {i} には `at` [x, y] と有効な `color` が必要です
@msg no point {i} (the gradient has {_1}) ポイント {i} はありません (このグラデーションのポイントは {_1} 個です)
@msg no segment {segment} on line {line} ライン {line} にセグメント {segment} はありません
@msg unknown freeform mode `{m}` (points, lines) `{m}` は不明なフリーフォームのモードです (points、lines)
@msg `aspect` must be a number (%) `aspect` には数値 (%) を指定してください
@msg `gradient` must be an object `gradient` にはオブジェクトを指定してください
@msg `mode` applies to freeform gradients `mode` はフリーフォームグラデーションにのみ適用されます
@msg `stops` must be an array `stops` には配列を指定してください
@msg `{k}` must be [x, y] `{k}` は [x, y] の形式で指定してください
@msg a gradient needs at least two stops グラデーションには 2 つ以上の分岐点が必要です
@msg give both `start` and `end` [x, y] (or neither) `start` と `end` は両方とも [x, y] で指定するか、どちらも省略してください
@msg stop {i} needs `offset` 分岐点 {i} には `offset` が必要です
@msg stop {i} needs a valid `color` 分岐点 {i} には有効な `color` が必要です
@msg stop {i}: `{k}` must be a number 分岐点 {i}: `{k}` には数値を指定してください
@msg unknown gradient kind `{k}` (linear, radial, freeform) `{k}` は不明なグラデーションの種類です (linear、radial、freeform)
@msg the art could not be sampled アートをサンプリングできませんでした
@msg the art is too light for any dots アートが明るすぎて網点を生成できません
@msg the document has no symbols ドキュメントにシンボルがありません
@msg `{s}` is not a colour (#rrggbb or a preset name) `{s}` はカラーではありません (#rrggbb またはプリセット名で指定してください)
@msg a colour index is 0 to {_1}, not {n} カラーのインデックスは 0 から {_1} までにしてください ({n} は指定できません)
@msg a colour is an index, #rrggbb or a preset name, not {v} カラーはインデックス、#rrggbb、プリセット名のいずれかで指定してください ({v} は指定できません)
@msg a document needs at least one layer ドキュメントには少なくとも 1 つのレイヤーが必要です
@msg no artwork アートワークがありません
@msg no selection bounds 選択範囲に境界がありません
@msg the layer has no objects to clip by レイヤーにクリッピングマスクとして使えるオブジェクトがありません
@msg the layer or group is locked レイヤーまたはグループがロックされています
@msg the layer to flatten into is hidden 統合先のレイヤーが非表示になっています
@msg there are no objects to release レイヤーに分配するオブジェクトがありません
@msg no library `{id}` ライブラリ `{id}` が見つかりません
@msg {path}: {e} {path}: {e}
@msg can't write .{ext} images .{ext} 画像は書き出せません
@msg Replace Spine: select a blend and a path ブレンド軸を置き換え: ブレンドとパスを選択してください
@msg nothing to wrap まとめるものがありません
@msg select a blend ブレンドを選択してください
@msg select a gradient mesh グラデーションメッシュを選択してください
@msg the object has no opacity mask オブジェクトに不透明マスクがありません
@msg Convert to Artboards: selection has no area アートボードに変換: 選択範囲に面積がありません
@msg Convert to Shape: no rectangles or ellipses selected シェイプに変換: 長方形または楕円形が選択されていません
@msg image would be too large; lower the resolution 画像が大きくなりすぎるため、解像度を下げてください
@msg clipboard is empty クリップボードが空です
@msg no anchor points selected アンカーポイントが選択されていません
@msg select at least two objects オブジェクトを 2 つ以上選択してください
@msg no saved presets 保存したプリセットはありません
@msg compound paths can only contain paths 複合パスに含められるのはパスだけです
@msg no bounds 境界がありません
@msg no current layer 現在のレイヤーがありません
@msg no key object キーオブジェクトが設定されていません
@msg no previous transform 前回の変形がありません
@msg nothing to align 整列するものがありません
@msg select a clip group クリップグループを選択してください
@msg select two or more objects to distribute 分布させるオブジェクトを 2 つ以上選択してください
@msg selection has no bounds 選択範囲に境界がありません
@msg the top object must be a path, compound path or text object to use as a clipping mask クリッピングマスクとして使うには、最前面のオブジェクトがパス、複合パス、テキストオブジェクトのいずれかである必要があります
@msg no target object has an opacity mask: select one or give `id` 不透明マスクのあるターゲットオブジェクトがありません: 該当するオブジェクトを選択するか、`id` を指定してください
@msg the object already has an opacity mask オブジェクトにはすでに不透明マスクがあります
@msg `{name}` is a process colour: tints apply to global and spot colours `{name}` はプロセスカラーです: 濃淡を適用できるのはグローバルカラーと特色だけです
@msg `{name}` isn't a colour swatch `{name}` はカラースウォッチではありません
@msg a document needs at least one artboard ドキュメントには少なくとも 1 つのアートボードが必要です
@msg empty path パスが空です
@msg join needs open paths 連結にはオープンパスが必要です
@msg path is already closed パスはすでに閉じています
@msg select paths to join 連結するパスを選択してください
@msg direct-select anchor points to cut at (not the end points of open paths) ダイレクト選択ツールで、カットする位置のアンカーポイントを選択してください (オープンパスの端点を除く)
@msg select paths or anchor points パスまたはアンカーポイントを選択してください
@msg Divide Objects Below: select a path 背面のオブジェクトで型抜き: パスを選択してください
@msg Divide Objects Below: select exactly one path 背面のオブジェクトで型抜き: パスを 1 つだけ選択してください
@msg Offset Path: select paths パスのオフセット: パスを選択してください
@msg Outline Stroke: no stroked paths selected パスのアウトライン: 線のあるパスが選択されていません
@msg Split Into Grid: select paths large enough for the grid グリッドに分割: グリッドが収まる大きさのパスを選択してください
@msg empty cutter 型抜きに使うパスが空です
@msg paths contain invalid coordinates パスに無効な座標が含まれています
@msg {label} produced an empty result {label} の結果が空になりました
@msg {label}: lost track of a shape's style {label}: シェイプのスタイル情報が失われました
@msg {label}: select paths {label}: パスを選択してください
@msg {label}: select paths, compound paths, groups or text {label}: パス、複合パス、グループ、テキストのいずれかを選択してください
@msg already editing a pattern すでにパターンを編集中です
@msg no pattern `{name}` パターン `{name}` が見つかりません
@msg not in pattern editing mode パターン編集モードではありません
@msg pattern missing パターンが見つかりません
@msg select a repeat リピートを選択してください
@msg select the art to repeat リピートするアートを選択してください
@msg the document has no patterns ドキュメントにパターンがありません
@msg no artboard アートボードがありません
@msg installing from a path is not available on the web; pass the module as `dataBase64` Web 版ではファイルパスからはインストールできないため、モジュールは `dataBase64` で渡してください
@msg `{key}` must be `auto` or a language code such as `en` or `zh-hant` `{key}` は `auto` か、`en` や `zh-hant` などの言語コードにしてください
@msg `{key}` must be a #rrggbb colour `{key}` は #rrggbb 形式のカラーにしてください
@msg `{key}` must be a string `{key}` は文字列にしてください
@msg `{key}` must be a whole number `{key}` は整数にしてください
@msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` は {min} から {max} までの整数にしてください (指定値: {x})
@msg `{key}` must be between {min} and {max} (got {x}) `{key}` は {min} から {max} までの値にしてください (指定値: {x})
@msg `{key}` must be one of {_1} `{key}` は {_1} のいずれかにしてください
@msg unknown preference `{key}` `{key}` は不明な環境設定の項目です
@msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) データ復帰のコピーを保存する場所がありません: 環境設定 → ファイル管理 → データ復帰 → フォルダー (recoveryFolder) を設定してください
@msg `{area}` is no recovery area name `{area}` は復帰用領域の名前として使えません
@msg `{name}` is no recovery entry name `{name}` は復帰用エントリの名前として使えません
@msg no clock to keep a heartbeat by ハートビートの記録に必要な時刻を取得できません
@msg no free recovery area 空いている復帰用領域がありません
@msg no native format ネイティブ形式がありません
@msg nothing encoded 何もエンコードされませんでした
@msg recovery copy `{file}`: {e} 復帰用コピー `{file}` を読み込めませんでした: {e}
@msg {name}: no such recovery entry {name}: 復帰用エントリが見つかりません
@msg Combine Slices: the slices have no bounds スライスを結合: スライスに境界がありません
@msg Create from Guides: the document has no artboard ガイドから作成: ドキュメントにアートボードがありません
@msg Create from Guides: the guides make more than {MAX_PIECES} slices ガイドから作成: ガイドで区切るとスライスが {MAX_PIECES} 個を超えます
@msg Create from Selection: the selection has no area 選択範囲から作成: 選択範囲に面積がありません
@msg Release: no layer to put the rectangle in 解除: 長方形を追加するレイヤーがありません
@msg a slice size must be a positive number of points スライスのサイズはポイント単位の正の数にしてください
@msg divide into 1 to {MAX_PIECES} slices スライスの分割数は 1 から {MAX_PIECES} までにしてください
@msg no slice selected スライスが選択されていません
@msg the document has no slices ドキュメントにスライスがありません
@msg no saved profiles 保存したプロファイルはありません
@msg select a stroke with a variable width 可変幅の線を選択してください
@msg the selected stroke's profile is already listed as {_1} 選択した線のプロファイルは、すでに {_1} として登録されています
@msg a graphic style named `{to}` already exists `{to}` という名前のグラフィックスタイルはすでに存在します
@msg no graphic style `{name}` グラフィックスタイル `{name}` が見つかりません
@msg node {_1} is not text ノード {_1} はテキストではありません
@msg Text Wrap: select a wrap object テキストの回り込み: 回り込みオブジェクトを選択してください
@msg layers can't be wrap objects レイヤーは回り込みオブジェクトにできません
@msg no threaded text selected スレッドテキストが選択されていません
@msg Create Outlines: select text objects アウトラインを作成: テキストオブジェクトを選択してください
@msg paste unavailable 貼り付けを使用できません
@msg Save for Web: the image is empty Web 用に保存: 画像が空です
@msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` は「#ff8800」のような形式のカラーではありません
@msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: 指定できるカラーは {MAX_TABLE} 色までです
@msg no artboard {i} (0-based; the document has {_1}) アートボード {i} はありません (番号は 0 始まり、このドキュメントには {_1} 個あります)
@msg no selected slice in the image: select slices, or save all of them 画像内に選択されたスライスがありません: スライスを選択するか、すべてのスライスを保存してください
@msg nothing to save: the document has no visible art 保存するものがありません: ドキュメントに表示されているアートがありません
@msg percent must be above 0 and at most 6400, not {p} パーセントは 0 より大きく 6400 以下にしてください ({p} は指定できません)
@msg unknown preset `{name}` (see webExport.presets.list) `{name}` は不明なプリセットです (webExport.presets.list を参照してください)
@msg width and height are at least 1 pixel 幅と高さは 1 ピクセル以上にしてください
@msg `sampleSize` must be 1, 3 or 5 `sampleSize` は 1、3、5 のいずれかにしてください
@msg `{path}` must be a bool or an object of bools `{path}` はブール値、またはブール値からなるオブジェクトにしてください
@msg cannot distort a zero-size bounding box サイズが 0 のバウンディングボックスは変形できません
@msg nothing to distort 変形するものがありません
@msg unknown option `{path}.{k}` `{path}.{k}` は不明なオプションです
@msg command `{0}` is not available right now: {1} コマンド `{0}` は現在使用できません: {1}
@msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) `{cmd}` で内部エラーが発生しました: {msg} (ドキュメントは変更されていません。このバグを報告してください)
@msg invalid parameters for `{cmd}`: {msg} `{cmd}` のパラメーターが正しくありません: {msg}
@msg no active document アクティブなドキュメントがありません
@msg no interaction in progress 進行中の操作がありません
@msg no such object {0} オブジェクト {0} が見つかりません
@msg result would exceed the canvas (coordinates out of range) 結果がカンバスの範囲を超えます (座標が範囲外です)
@msg unknown command `{0}` `{0}` は不明なコマンドです
@msg `{what}` closes nothing `{what}` に対応する開始部分がありません
@msg `{what}` closes something it didn't open `{what}` が対応しない開始部分を閉じています
@msg a path has too many points ポイントが多すぎるパスがあります
@msg it ends inside a layer レイヤーの途中で終わっています
@msg it has art outside its layers レイヤーの外にアートがあります
@msg it has more than {MAX_NODES} objects オブジェクトが {MAX_NODES} 個を超えています
@msg it has no layers レイヤーがありません
@msg it has too many values in a row 連続する値が多すぎます
@msg it has {_1}, which VectorCraft doesn't read from it yet {_1} が含まれていますが、VectorCraft はまだこのファイルからは読み込めません
@msg its objects are nested too deeply オブジェクトの入れ子が深すぎます
@msg its section ending with `%{end}` doesn't end `%{end}` で終わるはずのセクションが終わっていません
@msg an image VectorCraft can't read was left out VectorCraft で読み込めない画像は除外されました
@msg an image whose data is cut short was left out データが途中で切れている画像は除外されました
@msg gradient “{name}” isn't defined in the file: a plain colour stands in for it グラデーション「{name}」はファイル内で定義されていません: 代わりに単色を使用しています
@msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet 塗りや線が複数ある、または効果やブラシを適用したオブジェクト {_1} 個は見た目のまま読み込まれました: アピアランスはまだ編集できません
@msg patterns nested too deeply are filled with mid-grey 入れ子が深すぎるパターンは中間のグレーで塗りつぶされています
@msg shadings of an unknown type were left out 種類が不明なシェーディングは除外されました
@msg shadings whose functions are of an unknown type are filled with their middle colour 関数の種類が不明なシェーディングは中間の色で塗りつぶされています
@msg the file's preview header points outside the file ファイルのプレビューヘッダーがファイルの範囲外を指しています
@msg this PostScript file can't be read ({_1}): save it as PDF or SVG in the app that made it この PostScript ファイルは読み込めません ({_1}): 作成したアプリで PDF または SVG として保存してください
@msg this is not a PostScript file PostScript ファイルではありません
@msg a PostScript error ({name} in `{op}`) PostScript エラー (`{op}` での {name})
@msg a PostScript error ({name} in `{op}`), in {procs} {procs} 内の PostScript エラー (`{op}` での {name})
@msg a PostScript error ({name} in `{op}`: {at}) PostScript エラー (`{op}` での {name}: {at})
@msg a PostScript error ({name} in `{op}`: {at}), in {procs} {procs} 内の PostScript エラー (`{op}` での {name}: {at})
@msg a PostScript error ({name}) PostScript エラー ({name})
@msg it uses `{at}`, which VectorCraft's PostScript reader doesn't know VectorCraft の PostScript 読み込み機能が対応していない `{at}` を使用しています
@msg the file was read up to an error ({why}): what follows it was left out ファイルはエラーが発生した箇所まで読み込まれました ({why}): それ以降の内容は除外されました
@msg this file's PostScript couldn't be read ({why}): {what} このファイルの PostScript を読み込めませんでした ({why}): {what}
@msg it has no page ページがありません
@msg it has too many text objects テキストオブジェクトが多すぎます
@msg it has too much text テキストが多すぎます
@msg its editing data doesn't say where its art is 編集データにアートの位置が記録されていません
@msg its editing data doesn't say where its artboard is 編集データにアートボードの位置が記録されていません
@msg its editing data is for a different page 編集データが別のページのものです
@msg its page has text, and its layers have no text objects to put it in ページにテキストがありますが、レイヤーにはそれを入れるテキストオブジェクトがありません
@msg the art on them differs from the page's in {_1}% of it レイヤー上のアートの {_1}% がページのアートと異なります
@msg its Windows metafile preview was opened instead, which may simplify the art 代わりに Windows メタファイルのプレビューを開いたため、アートが簡略化されている場合があります
@msg its preview was placed instead, at screen resolution 代わりにプレビューを画面解像度で配置しました
@msg shadings of more than 4096 patches or triangles were left out パッチまたは三角形が 4096 個を超えるシェーディングは除外されました
@msg it uses `{at}`, which VectorCraft's PostScript reader doesn't know, in {procs} {procs} 内で、VectorCraft の PostScript 読み込み機能が対応していない `{at}` を使用しています
@msg the export region is not finite 書き出し範囲に無効な数値が含まれています
@msg a page out of range 範囲外のページがあります
@msg a page's placement is not finite ページの配置に無効な数値が含まれています
@msg nothing to print プリントするものがありません
@msg page size {w} × {h} ページサイズ {w} × {h} は無効です
@msg the preview image is empty プレビュー画像が空です
@msg the thumbnail image is malformed サムネール画像の形式が正しくありません
@msg can't encode the document: {0} ドキュメントをエンコードできません: {0}
@msg can't save version {0}: VectorCraft writes versions {MIN_VERSION} to {VERSION} バージョン {0} では保存できません: VectorCraft で保存できるのはバージョン {MIN_VERSION} から {VERSION} までです
@msg file version {0} is newer than this VectorCraft supports ({VERSION}) ファイルのバージョン {0} は、この VectorCraft が対応するバージョン ({VERSION}) より新しいものです
@msg invalid image data for `{0}` `{0}` の画像データが正しくありません
@msg not a VectorCraft file: {0} VectorCraft ファイルではありません: {0}
@msg the compressed file unpacks to more than {_1} MB 圧縮ファイルを展開すると {_1} MB を超えます
@msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files バージョン {0} のファイルは圧縮できません: 圧縮ファイルを開けるのはバージョン {COMPRESSED_SINCE} 以降のみです
@msg a bitmap is empty ビットマップが空です
@msg a bitmap is too large to read ビットマップが大きすぎて読み込めません
@msg compressed (RLE) bitmaps can't be read yet 圧縮 (RLE) されたビットマップはまだ読み込めません
@msg the image's pixels don't match its size 画像のピクセル数がサイズと一致しません
@msg {bpp}-bit bitmaps can't be read {bpp} ビットのビットマップは読み込めません
@msg not an EMF or WMF file EMF ファイルでも WMF ファイルでもありません
@msg its layers use {_1}, which aren't read yet レイヤーで使用されている {_1} はまだ読み込めません
@msg the EMF header is damaged EMF ヘッダーが破損しています
@msg damaged 破損しています
@msg the WMF header is damaged WMF ヘッダーが破損しています
@msg the export region is empty 書き出し範囲が空です
@msg a stream runs past the end ストリームがファイルの末尾を超えています
@msg a stream's length is wrong ストリームの長さが正しくありません
@msg a stream's length isn't a number ストリームの長さが数値ではありません
@msg bad stream length ストリームの長さが無効です
@msg PDF writer error: {0} PDF の書き出し中にエラーが発生しました: {0}
@msg artboard {0} does not exist アートボード {0} は存在しません
@msg cannot read PDF: {0} PDF を読み込めません: {0}
@msg invalid PDF setting: {0} PDF の設定が正しくありません: {0}
@msg page {0} does not exist (the PDF has {1}) ページ {0} は存在しません (この PDF のページ数は {1} です)
@msg the PDF has no pages PDF にページがありません
@msg the PDF is password-protected: give its password この PDF はパスワードで保護されています: パスワードを入力してください
@msg the PDF password is wrong PDF のパスワードが正しくありません
@msg the file holds only a placeholder page, not its art (it was saved without PDF compatibility): save it again with PDF compatibility on, or as PDF or SVG ファイルには仮のページだけが含まれ、アートは含まれていません (PDF 互換なしで保存されています): PDF 互換をオンにして保存し直すか、PDF または SVG として保存してください
@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG これは PostScript ファイル (古い形式または PDF 互換なしで保存された .ai、または EPS ファイル) のため、まだ開けません: PDF、PDF 互換の .ai、または SVG として保存してください
@msg unsupported: {0} 対応していません: {0}
@msg a page is missing 見つからないページがあります
@msg a page tree kid isn't a reference ページツリーの子要素が参照になっていません
@msg a page tree node has no kids ページツリーのノードに子要素がありません
@msg an object can't be read 読み込めないオブジェクトがあります
@msg bad page tree ページツリーが無効です
@msg bad trailer トレーラーが無効です
@msg no catalog カタログがありません
@msg no cross-reference table 相互参照テーブルがありません
@msg no pages ページがありません
@msg no plug-in {0} is installed プラグイン {0} はインストールされていません
@msg not a valid plug-in module: {0} 有効なプラグインモジュールではありません: {0}
@msg plug-in ABI: {0} プラグインの ABI に問題があります: {0}
@msg plug-in exceeded its {0} プラグインが {0} を超えました
@msg plug-in failed: {0} プラグインの実行に失敗しました: {0}
@msg plug-in manifest: {0} プラグインのマニフェストに問題があります: {0}
@msg plug-in output: {0} プラグインの出力に問題があります: {0}
@msg plug-in parameters: {0} プラグインのパラメーターに問題があります: {0}
@msg plug-in trapped: {0} プラグインが異常終了しました: {0}
@msg is not an image VectorCraft reads VectorCraft で読み込める画像ではありません
@msg not found 見つかりません
@msg SVG parse error: {0} SVG を解析できませんでした: {0}
@msg decimals must be {_1}–{_2} (got {_3}) 小数点以下の桁数は {_1} から {_2} までにしてください (指定値: {_3})
@msg Exporting {_1} {_1} を書き出し中
@msg Exported {what} {what} を書き出しました
@msg "{0}" is not a colour: write it as #rrggbb 「{0}」はカラーではありません: #rrggbb の形式で指定してください
@msg could not decode image: {0} 画像をデコードできませんでした: {0}
@msg image is empty 画像が空です
@msg the image is {width} × {height} pixels, more than Image Trace takes ({max} megapixels) 画像が {width} × {height} ピクセルで、画像トレースで扱える上限 ({max} メガピクセル) を超えています
@msg this isn't a flat-colour logo ({_1}% of its solid areas match a few flat colours), so Flat Logo mode would turn its gradients into patches: use Color mode instead フラットカラーのロゴではないため (ベタ塗り部分のうち少数の単色に一致するのは {_1}% のみ)、フラットロゴモードではグラデーションがまだらになります: 代わりにカラーモードを使用してください
@msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset このトレースではアンカーポイントが {max} 個を超え、ドキュメントを滑らかに表示できなくなります: 「ノイズ」を上げる、「パス」か「カラー」を下げる、または精度の低いプリセットを選択してください
@msg internal error: {msg} (please report this bug) 内部エラー: {msg} (このバグを報告してください)
@msg the background worker stopped バックグラウンド処理が停止しました
@msg {_1} failed: {e} {_1} に失敗しました: {e}
@msg {label}… {label}…
@msg no blend options ブレンドオプションがありません
@msg bad color {v} カラー {v} が正しくありません
@msg Corners edits the corners of a path 「コーナー」で編集できるのはパスの角だけです
@msg give corners of the path: anchors between two straight sides パスの角 (2 本の直線の辺に挟まれたアンカーポイント) を指定してください
@msg select one path, or give its `id` パスを 1 つ選択するか、その `id` を指定してください
@msg the drawing is no longer loaded 図面はもう読み込まれていません
@msg No saved selections (Select → Save Selection…) 保存した選択範囲はありません (選択 → 選択範囲を保存…)
@msg effect {k} is `{_1}`, not `{id}` インデックス {k} の効果は `{id}` ではなく `{_1}` です
@msg no effect at index {k} インデックス {k} に効果がありません
@msg unknown effect `{id}` `{id}` は不明な効果です
@msg `{id}` has no envelope dialog `{id}` にはエンベロープのダイアログがありません
@msg select an envelope エンベロープを選択してください
@msg no format to export to 書き出し形式が指定されていません
@msg nothing to export: the document has no visible art (or turn on Use Artboards) 書き出すものがありません: ドキュメントに表示されているアートがありません (または「アートボードを使用」をオンにしてください)
@msg add a format to export 書き出す形式を追加してください
@msg check an asset to export 書き出すアセットにチェックを入れてください
@msg `{tool}` isn't a freehand tool `{tool}` はフリーハンドツールではありません
@msg bad colour `{hex}` (#rrggbb) カラー `{hex}` が正しくありません (#rrggbb の形式で指定してください)
@msg no gradient stop or freeform point is selected グラデーションの分岐点またはフリーフォームポイントが選択されていません
@msg no graphic style `{n}` グラフィックスタイル `{n}` が見つかりません
@msg select two or more graphic styles to merge 統合するグラフィックスタイルを 2 つ以上選択してください
@msg the PDF is no longer loaded PDF はもう読み込まれていません
@msg no such layer or object 指定されたレイヤーまたはオブジェクトが見つかりません
@msg `{tool}` isn't a Liquify tool `{tool}` はゆがみツールではありません
@msg {_1} linked file(s) can't be read here: their previews show この環境では {_1} 個のリンクファイルを読み込めません: 代わりにプレビューを表示しています
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} 個のリンク画像がディスク上で変更されました: 「リンクを更新」で新しいバージョンを表示できます
@msg pick a colour, gradient or pattern to save as a swatch スウォッチとして保存するカラー、グラデーション、またはパターンを選択してください
@msg Packaged {n} file(s) in {folder}{note} {n} 個のファイルを {folder} にパッケージしました{note}
@msg Packaged {n} file(s){note} {n} 個のファイルをパッケージしました{note}
@msg choose a location for the package パッケージの保存場所を選択してください
@msg missing `folder` `folder` が指定されていません
@msg the package came back damaged 返されたパッケージのデータが破損しています
@msg no preset editor プリセットの編集ダイアログが開いていません
@msg no perspective grid preset named `{name}` `{name}` という名前の遠近グリッドプリセットが見つかりません
@msg no active perspective plane アクティブな遠近面がありません
@msg plane must be left, right or ground plane には left、right、ground のいずれかを指定してください
@msg missing `id` (see plugin.list) `id` が指定されていません (plugin.list を参照)
@msg no plug-in {id} is installed プラグイン {id} はインストールされていません
@msg {_1} is a live effect (Effect › Plug-ins) {_1} はライブ効果です (「効果 › プラグイン」から使用してください)
@msg a preset named `{_1}` exists `{_1}` という名前のプリセットはすでに存在します
@msg no print preset named `{base}` `{base}` という名前のプリントプリセットが見つかりません
@msg no print preset named `{name}` `{name}` という名前のプリントプリセットが見つかりません
@msg no saved print preset named `{name}` ({DEFAULT_PRESET} is protected: start a new one from it) `{name}` という名前の保存済みプリントプリセットが見つかりません ({DEFAULT_PRESET} は保護されています: これを元に新しいプリセットを作成してください)
@msg print settings are not an object プリント設定がオブジェクト形式ではありません
@msg no colour group `{g}` カラーグループ `{g}` が見つかりません
@msg select artwork (or a colour group) to recolor 再配色するアートワーク (またはカラーグループ) を選択してください
@msg Downloaded {_1} file(s) {_1} 個のファイルをダウンロードしました
@msg Preview in Browser needs the desktop app (the web downloads files instead) 「ブラウザーでプレビュー」にはデスクトップアプリが必要です (Web 版では代わりにファイルをダウンロードします)
@msg no file system here この環境にはファイルシステムがありません
@msg nothing to preview プレビューするものがありません
@msg Saved {n} files beside {path} {path} と同じ場所にファイルを {n} 個保存しました
@msg `{_1}` is no save command `{_1}` は保存コマンドではありません
@msg name the file ファイル名を入力してください
@msg unknown format 不明な形式です
@msg PDF settings are not an object PDF 設定がオブジェクト形式ではありません
@msg no saved PDF preset named `{name}` (built-in presets are read-only: start a new one from them) `{name}` という名前の保存済み PDF プリセットが見つかりません (組み込みのプリセットは読み取り専用です: それを元に新しいプリセットを作成してください)
@msg Saved to User Defined: {_1} 「ユーザー定義」に保存しました: {_1}
@msg choose a direction to divide in 分割する方向を選択してください
@msg choice must be "merge" or "add", not `{choice}` choice には "merge" または "add" を指定してください (`{choice}` は指定できません)
@msg `{name}` has no options `{name}` にはオプションがありません
@msg no swatch `{name}` スウォッチ `{name}` が見つかりません
@msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` はカラーではありません (#rrggbb またはプリセット名で指定してください)
@msg give the path `id` and the width point `index` パスの `id` と幅ポイントの `index` を指定してください
@msg no such width point 指定された幅ポイントが見つかりません
@msg onto must name a panel floating in another group onto には、別のグループでフローティングしているパネルを指定してください
@msg unknown panel `{raw}` `{raw}` は不明なパネルです
@msg x and y must both be numbers x と y はどちらも数値で指定してください
@msg Downloaded {what} {what} をダウンロードしました
@msg Exported {count} file(s) to {folder} {count} 個のファイルを {folder} に書き出しました
@msg Imported {what}: {_1} {what} を読み込みました: {_1}
@msg Installed plug-in {_1} プラグイン {_1} をインストールしました
@msg Opened with {_1} note(s): {_2} ドキュメントを開きました (注意 {_1} 件): {_2}
@msg Saved {path} {path} を保存しました
@msg no app to open files here この環境にはファイルを開くアプリがありません
@msg no data データがありません
@msg no document ドキュメントがありません
@msg no file manager here この環境にはファイルマネージャーがありません
@msg no revert command 「保存済みの状態に戻す」コマンドがありません
@msg the Save PDF dialog didn't open PDF 保存ダイアログが開きませんでした
@msg the document has never been saved ドキュメントはまだ一度も保存されていません
@msg the export returned unreadable data 書き出し処理から読み取れないデータが返されました
@msg {status} ({e}) {status} ({e})
@msg Exported {what} with {_1} note(s): {first} {what} を書き出しましたが、注意事項が {_1} 件あります: {first}
@msg Saved {path} with {_1} note(s): {first} {path} を保存しましたが、注意事項が {_1} 件あります: {first}
@msg Couldn't open {name}: {e} {name} を開けませんでした: {e}
@msg Couldn't read {name}: {e} {name} を読み込めませんでした: {e}
@msg Internal error: {msg} (please report this bug) 内部エラー: {msg} (このバグを報告してください)
@msg Opened {url} {url} を開きました
@msg No saved views (View → New View…) 保存した表示はありません (表示 → 新規表示…)
@msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` には、メニュー項目がダイアログを開くコマンドを指定してください (ui.menuDialog を参照)
@msg `{key}` must be true or false `{key}` には true または false を指定してください
@msg brightness must be dark|mediumDark|mediumLight|light brightness には dark|mediumDark|mediumLight|light のいずれかを指定してください
@msg index must be a number or first, previous, next or last index には数値、または first、previous、next、last のいずれかを指定してください
@msg index must be a number or first, previous, next or last, not `{other}` index には数値、または first、previous、next、last のいずれかを指定してください (`{other}` は指定できません)
@msg lang must be one of {_1} lang には {_1} のいずれかを指定してください
@msg missing `name` `name` が指定されていません
@msg missing `tool` `tool` が指定されていません
@msg missing index index が指定されていません
@msg multiple windows land with M11.5 複数ウィンドウは M11.5 で対応予定です
@msg no PNG encoder PNG エンコーダーがありません
@msg no document open ドキュメントが開かれていません
@msg no effect applied yet まだ効果を適用していません
@msg no such perspective grid preset 指定された遠近グリッドプリセットが見つかりません
@msg no such recent file 指定された最近使ったファイルが見つかりません
@msg no such recent font 指定された最近使ったフォントが見つかりません
@msg no such saved selection 指定された選択範囲は保存されていません
@msg no such user library 指定されたユーザーライブラリが見つかりません
@msg no such view 指定された表示が見つかりません
@msg printing isn't available here この環境ではプリントできません
@msg select an image 画像を選択してください
@msg the document has no artboards ドキュメントにアートボードがありません
@msg tool (a tool id) is required tool (ツール ID) を指定してください
@msg unknown tool `{t}` `{t}` は不明なツールです
@msg no such action 指定されたアクションが見つかりません
@msg choose a folder to export to 書き出し先のフォルダーを選択してください
@msg the selection has no URL (or they differ) 選択したオブジェクトに URL がありません (または URL がそれぞれ異なります)
@msg select some type first 先にテキストを選択してください
@msg {_1} font families available {_1} 個のフォントファミリーを使用できます
@msg {_1} has no {_2} style {_1} には {_2} スタイルがありません
@msg Copied the CSS of {rules} object(s) {rules} 個のオブジェクトの CSS をコピーしました
@msg Exported {path} {path} を書き出しました
@msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください
@msg unknown highlight `{h}` `{h}` は不明なハイライトの指定です
@msg unknown overprints `{o}` (preserve, simulate or discard) `{o}` は不明なオーバープリントの指定です (preserve、simulate、discard のいずれか)
@msg unknown preset `{name}` (see flattener.presets.list) `{name}` は不明なプリセットです (flattener.presets.list を参照してください)
@msg Select text or click into text with the Type tool to insert glyphs 字形を挿入するには、テキストを選択するか、文字ツールでテキスト内をクリックしてください
@msg `library` is a library id or name (see {list}) `library` にはライブラリの ID または名前を指定してください ({list} を参照)
@msg no library `{key}` (see {list}) ライブラリ `{key}` が見つかりません ({list} を参照)
@msg select a linked image: an embedded one has no file リンク画像を選択してください: 埋め込み画像にはファイルがありません
@msg {path} can't be found: relink it first {path} が見つかりません: 先に再リンクしてください
@msg Embedded {n} image(s); {missing} missing: relink them first 画像を {n} 枚埋め込みましたが、{missing} 枚は見つかりません: 先に再リンクしてください
@msg Relinked {_1} image(s) 画像を {_1} 枚再リンクしました
@msg Relinked {n} image(s) 画像を {n} 枚再リンクしました
@msg Relinked {n} image(s); not in that folder: {_1} 画像を {n} 枚再リンクしましたが、次の画像はそのフォルダーにありません: {_1}
@msg Unembedded to {_1} 埋め込みを解除して {_1} に保存しました
@msg Updated {_1} image(s) 画像を {_1} 枚更新しました
@msg no swatch library `{l}` (see swatch.library.list) スウォッチライブラリ `{l}` が見つかりません (swatch.library.list を参照)
@msg Couldn't place {name}: the document it was dropped on was closed {name} を配置できませんでした: ドロップ先のドキュメントは閉じられています
@msg no files to place 配置するファイルがありません
@msg paths: give at least one file paths: ファイルを 1 つ以上指定してください
@msg Couldn't place {name}: {e} {name} を配置できませんでした: {e}
@msg no print service プリントサービスがありません
@msg the print job has no data プリントジョブにデータがありません
@msg there are no printer settings to open here この環境では開けるプリンター設定がありません
@msg Couldn't save recovery data: {e} 復帰用データを保存できませんでした: {e}
@msg Saved recovery data for {title} {title} の復帰用データを保存しました
@msg Discarded {_1} recovered document(s) 復帰用データのドキュメントを {_1} 件破棄しました
@msg Restored {_1} recovered document(s): save them to keep them 復帰用データからドキュメントを {_1} 件復元しました: 残すには保存してください
@msg Saving recovery data for {_1} {_1} の復帰用データを保存中
@msg bad shortcut ショートカットが正しくありません
@msg can't parse shortcut `{c}` ショートカット `{c}` を解釈できません
@msg can't parse shortcut `{s}` for `{k}` `{k}` のショートカット `{s}` を解釈できません
@msg no dialog open ダイアログが開かれていません
@msg no file reader ファイルの読み込み機能がありません
@msg no file writer ファイルの書き込み機能がありません
@msg not a VectorCraft shortcut set (missing `overrides`) VectorCraft のショートカットセットではありません (`overrides` がありません)
@msg shortcut for `{k}` must be a string `{k}` のショートカットは文字列で指定してください
@msg tool shortcuts must be a single key (optionally with Shift) ツールのショートカットには 1 つのキーを指定してください (Shift との組み合わせも可)
@msg unknown preset (one of {_1}) 不明なプリセットです ({_1} のいずれかを指定してください)
@msg unknown tool or command `{key}` `{key}` は不明なツールまたはコマンドです
@msg {_1} is already used by {_2} {_1} はすでに {_2} で使用されています
@msg Couldn't copy to the system clipboard: {e} システムのクリップボードにコピーできませんでした: {e}
@msg Couldn't paste from the clipboard: {e} クリップボードから貼り付けられませんでした: {e}
@msg nothing selected 何も選択されていません
@msg the {tool} tool has no options {tool} ツールにはオプションがありません
@msg unknown tool `{tool}` `{tool}` は不明なツールです
@msg {tool} isn't in a toolbar group of several tools {tool} は複数のツールからなるツールグループに含まれていません
@msg no such document 指定されたドキュメントが見つかりません
@msg {_1}: not saved, so not closed {_1}: 保存されていないため、閉じませんでした
@msg `{name}` is a built-in workspace; choose another name `{name}` は組み込みのワークスペースなので、別の名前を指定してください
@msg `{to}` is not an available name `{to}` という名前は使用できません
@msg no user workspace `{from}` ユーザーワークスペース `{from}` が見つかりません
@msg unknown workspace (one of {_1}) 不明なワークスペースです ({_1} のいずれかを指定してください)
@msg workspace name can't be empty ワークスペース名を入力してください
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -2
View File
@@ -84,8 +84,8 @@ fn plural_east_slavic(n: u64) -> usize {
/// The registry. English first: it is the fallback and the source language.
pub static LANGUAGES: [LangInfo; 11] = [
LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() },
// Japanese: the whole interface (every menu string and `tl!` literal), keeping the product,
// workspace and perspective preset names in English (`MENU_KEEP_AS_IS`).
// Japanese: the whole interface (every menu string and `tl!` literal) and the status and error
// messages, keeping the product, workspace and perspective preset names in English (`MENU_KEEP_AS_IS`).
LangInfo { code: "ja", name: "日本語", source: include_str!("ja.tsv"), plural: plural_none, complete_menus: true, catalog: OnceLock::new() },
// Czech: every menu label (`menu_catalogs_translate_every_menu_label`); panels and dialogs not yet.
LangInfo { code: "cs", name: "Čeština", source: include_str!("cs.tsv"), plural: plural_czech, complete_menus: false, catalog: OnceLock::new() },
+2
View File
@@ -2297,6 +2297,7 @@
Swatch Options Opções de Amostra
Swatch Options… Opções de Amostra…
Swatch Tiles Blocos de Amostra
Swatch exchange files keep solid colors only. Arquivos de intercâmbio de amostras mantêm apenas cores sólidas.
Swatches Amostras
Switch workspace Trocar espaço de trabalho
Symbol Instance Instância de Símbolo
@@ -2590,6 +2591,7 @@
to para
{count} file(s) in {folder}{note}. Show the package folder? {count} arquivo(s) em {folder}{note}. Mostrar a pasta do pacote?
{count} linked file(s) not found {count} arquivo(s) vinculado(s) não encontrado(s)
fonts not copied: {fonts} fontes não copiadas: {fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? {count} imagem(ns) vinculada(s) alterada(s) desde que este documento foi salvo. Mostrar as novas versões?
{count} more rules: Export writes every one. {count} regras a mais: a Exportação escreve cada uma.
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} objetos sem nome deixados de fora: nomeie-os, ou ative Objetos Sem Nome no menu do painel.
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -159,6 +159,7 @@
Appearance panel Панель «Оформление»
Applies when the linked file is relinked or updated. Применяется при повторной привязке или обновлении связанного файла.
Applies the next time VectorCraft starts. Применяется при следующем запуске VectorCraft.
Apply Применить
Apply Brush Применить кисть
Apply Character Style Применить стиль символа
Apply Effect Применить эффект
@@ -2635,6 +2636,7 @@
Swash Росчерк
Swatch Conflict Конфликт образцов
Swatch Conflicts Конфликты образцов
Swatch exchange files keep solid colors only. Файлы обмена образцами сохраняют только сплошные цвета.
Swatch Libraries Библиотеки образцов
Swatch Libraries Menu Меню «Библиотеки образцов»
Swatch Library Библиотека образцов
@@ -2985,6 +2987,7 @@
Scrub Numeric Fields by Dragging Изменять числовые поля перетаскиванием
{count} file(s) in {folder}{note}. Show the package folder? Файлов: {count} в {folder}{note}. Показать папку пакета?
{count} linked file(s) not found Не найдено связанных файлов: {count}
fonts not copied: {fonts} шрифты не скопированы: {fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? Связанных изображений ({count}) изменились с момента сохранения этого документа. Показать новые версии?
{count} more rules: Export writes every one. Ещё правил: {count}: экспорт записывает все.
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Пропущено объектов без имени: {count}: назовите их или включите «Объекты без имени» в меню панели.
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1 -1
View File
@@ -872,7 +872,7 @@ fn complete_languages_translate_every_message() {
}
/// Languages whose catalogs cover every status and error message.
const COMPLETE_MESSAGES: &[&str] = &["es", "fr", "it", "ru", "uk"];
const COMPLETE_MESSAGES: &[&str] = &["es", "fr", "it", "ja", "ru", "uk"];
/// Crates whose error and status messages reach the status bar.
const MESSAGE_CRATES: &[&str] = &["ui-egui", "engine", "doc", "format", "svg", "pdf", "eps", "text", "plugins", "metafile", "cad", "trace"];
+95 -92
View File
@@ -155,6 +155,7 @@
Appearance panel Панель «Оформлення»
Applies when the linked file is relinked or updated. Використовується при повторній прив’язці або оновленні пов’язаного файлу.
Applies the next time VectorCraft starts. Застосовується при наступному запуску VectorCraft.
Apply Застосувати
Apply Brush Застосувати пензель
Apply Character Style Застосувати стиль символу
Apply Effect Застосувати ефект
@@ -215,7 +216,7 @@
Auto Spell Check Автоматична перевірка орфографії
Auto-Collapse Iconic Panels Автоматично згортати значки панелей
Show Tool Group Labels Показувати назви груп інструментів
Auto-Rotate (turn the paper to each artboard) Автоповорот (повертати лист по кожній монтажній області)
Auto-Rotate (turn the paper to each artboard) Автоматичний поворот (повертати аркуш відповідно до кожної монтажної області)
Automatic flatness Автоматична площинність
Automatically Автоматично
Automatically Save Recovery Data Автоматично зберігати дані відновлення
@@ -239,7 +240,7 @@
Black Чорний
Black and White Чорно-білий
Black and White Logo Чорно-білий логотип
BLANK DOCUMENT PRESETS НАБОРИ ПОРОЖНИХ ДОКУМЕНТІВ
BLANK DOCUMENT PRESETS НАБОРИ ПОРОЖНІХ ДОКУМЕНТІВ
Bleed Виліт
Bleed: Виліт:
Bleeds Вильоти
@@ -434,7 +435,7 @@
Compatible Gradient and Gradient Mesh Printing Сумісний друк градієнтів та градієнтних сіток
Complement Додатковий
Complexity: Складність:
Composite colours are converted to it; separations separate with it when it is a CMYK profile. Складові кольори перетворюються на нього; кольороподіли розділяються з ним, якщо це профіль CMYK.
Composite colours are converted to it; separations separate with it when it is a CMYK profile. Складові кольори перетворюються за цим профілем; кольороподіл також виконується за ним, якщо це профіль CMYK.
Compound Path Складений контур
Compress (RLE) Стиснути (RLE)
Compress text and line art Стискати текст та штриховий малюнок
@@ -476,7 +477,7 @@
Convert to Shape Перетворити на фігуру
Convert to sRGB Перетворити на sRGB
Convert: Перетворити:
Copied the CSS of {rules} object(s) Скопійовано CSS для {rules} об’єкта(ів)
Copied the CSS of {rules} object(s) Скопійовано CSS об’єктів: {rules}
Copies: Копії:
Copy Копіювати
Copy (make a transformed copy) Копіювати (створити перетворену копію)
@@ -541,11 +542,11 @@
CSS Properties Властивості CSS
Ctrl Ctrl
Currency & Symbols Валюти та символи
Current Brush Поточна пензель
Current Brush Поточний пензель
Current Colors ({total}) Поточні кольори ({total})
Current Symbol Поточний символ
Curvature Кривизна
Curvature Tool Інструмент «Кривізна»
Curvature Tool Інструмент «Кривизна»
Curves… Криві…
Custom Користувацький
Customize… Налаштувати…
@@ -614,7 +615,7 @@
Delete these {n} graphic styles? Видалити ці графічні стилі ({n})?
Delete this saved preset Видалити цей збережений набір
Delete this {n} graphic style? Видалити цей графічний стиль ({n})?
Delete Transparency Flattener Preset Видалити набір об’єднання прозоростей
Delete Transparency Flattener Preset Видалити набір зведення прозорості
Delete Width Point Видалити точку ширини
Delete Workspace Видалити робоче середовище
Delete {kind} Style Видалити стиль {kind}
@@ -784,21 +785,21 @@
Ellipse Еліпс
Ellipse Tool Інструмент «Еліпс»
Ellipse… Еліпс…
Ellipsis Багатокрапка
Em Box Bottom/Left Низ/ліво кегельного майданчика
Ellipsis Трикрапка
Em Box Bottom/Left Нижній/лівий край кегельного майданчика
Em Box Center Центр кегельного майданчика
Em Box Top/Right Верх/право кегельного майданчика
ICF Top/Right Верх/право ICF
ICF Bottom/Left Низ/ліво ICF
ICF Bottom/Left Нижній/лівий край ICF
Em Dash Довге тире
Em Space Кругла шпація
Embed Вбудувати
Embed Fonts (for other applications) Вбудувати шрифти (для інших програм)
Embed Fonts (Glyphs Used) Вбудувати шрифти (використані гліфи)
Embed ICC Profile Використати профіль ICC
Embed ICC Profiles Використати профілі ICC
Embed Image Використати зображення
Embed Image(s) Використати зображення(и)
Embed ICC Profile Вбудувати профіль ICC
Embed ICC Profiles Вбудувати профілі ICC
Embed Image Вбудувати зображення
Embed Image(s) Вбудувати зображення
Embed page thumbnails Вбудувати мініатюри сторінок
Embedded Вбудовано
Embedded Image Впроваджене зображення
@@ -865,7 +866,7 @@
Expand… Розібрати…
Export Експорт
Export All… Експортувати все…
Export and Clipboard Transparency Flattener Settings Параметри об’єднання прозоростей для експорту та буфера обміну
Export and Clipboard Transparency Flattener Settings Параметри зведення прозорості для експорту та буфера обміну
Export Artboard Експортувати монтажну область
Export As Експортувати як
Export As PNG… Експортувати як PNG…
@@ -893,7 +894,7 @@
Export Settings Параметри експорту
Export the selected assets (else all of them) Експортувати виділені ресурси (інакше все)
Export to: Експортувати до:
Export Transparency Flattener Presets Експортувати набори поєднання прозоростей
Export Transparency Flattener Presets Експортувати набори зведення прозорості
Export {count} Selected Експортувати вибрані ({count})
Export: Експорт:
Exported {count} file(s) to {folder} Експортовано файли: {count} до {folder}
@@ -966,18 +967,18 @@
Fit to Artwork Bounds Вписати у межі малюнка
Fit to Selected Art Вписати у виділений малюнок
Flag… Прапор…
Flare Блік
Flare Tool Інструмент «Блик»
Flare Tool Options Параметри інструменту «Блик»
Flare Відблиск
Flare Tool Інструмент «Відблиск»
Flare Tool Options Параметри інструменту «Відблиск»
Flat Image Плоске зображення
Flat Logo Плоский логотип
Flatness: Площинність:
Flatten Artwork Об’єднати малюнок
Flatten Transparency Об’єднати прозорості
Flatten Transparency… Поєднати прозорості…
Flattener preset: Набір об’єднання:
Flattener presets Набори об’єднання
Flattener Preview Попередній перегляд об’єднання
Flatten Transparency Звести прозорість
Flatten Transparency… Звести прозорість…
Flattener preset: Набір зведення:
Flattener presets Набори зведення
Flattener Preview Попередній перегляд зведення
Flip Across Відобразити поперек
Flip Along Відобразити вздовж
Flip Along Horizontal Axis Відобразити по горизонтальній осі
@@ -1113,9 +1114,9 @@
More Options Додаткові параметри
Show Properties Panel Показати панель «Властивості»
Hide Corner Widget Приховати кутовий віджет
Hide Corner Widget for angles greater than Приховувати кутовий віджет для кутів.
Hide Corner Widget for angles greater than Приховувати кутовий віджет для кутів, більших за
Hide Edges Приховати краї
Hide Gradient Annotator Сховати анотатор градієнта
Hide Gradient Annotator Приховати маркер градієнта
Hide Grid Приховати сітку
Hide Guides Приховати напрямні
Hide Hidden Characters Приховати приховані символи
@@ -1169,7 +1170,7 @@
Ignore White Ігнорувати білий
Palette: Палітра:
Limited Обмежена
Full Tone Повнотонова
Full Tone Повний діапазон тонів
Document Library Бібліотека документа
Library: Бібліотека:
Image Зображення
@@ -1187,7 +1188,7 @@
Import PDF Presets Імпортувати набори PDF
Import Perspective Grid Presets Імпортувати набори сітки перспективи
Import Print Presets Імпортувати набори друку
Import Transparency Flattener Presets Імпортувати набори поєднання прозоростей
Import Transparency Flattener Presets Імпортувати набори зведення прозорості
Imported {what}: {} Імпортовано: {what}: {}
Import… Імпорт…
In Tangent Handles Маркери вхідної дотичної
@@ -1241,11 +1242,11 @@
Join the ArtCraft community on Discord (discord.gg/artcraft) Приєднуйтесь до спільноти ArtCraft Discord (discord.gg/artcraft)
Join the lines of each paragraph Поєднувати рядки кожного абзацу
Join Tool Інструмент «З’єднання»
Justification… Виняток…
Justify all lines Вимкнути всі рядки
Justify with last line aligned center Вимкнути з останнім рядком по центру
Justify with last line aligned left Вимкнути з останнім рядком по лівому краю
Justify with last line aligned right Вимкнути з останнім рядком з правого краю
Justification… Вирівнювання за шириною…
Justify all lines Вирівняти всі рядки за шириною
Justify with last line aligned center Вирівняти за шириною, останній рядок — по центру
Justify with last line aligned left Вирівняти за шириною, останній рядок — ліворуч
Justify with last line aligned right Вирівняти за шириною, останній рядок — праворуч
Keep a link to an image file instead of only embedding it Зберігати зв’язок із файлом зображення замість простого впровадження
Keep both sides the same width Зберігати однакову ширину обох сторін
Keep Formatting Зберігати форматування
@@ -1301,7 +1302,7 @@
Left-to-Right Paragraph Direction Напрямок абзацу зліва направо
Left: Зліва:
Legacy Macintosh RGB (Gamma 1.8) Застарілий Macintosh RGB (гама 1.8)
Legacy vector clipboard Застарілий вектор буфер обміну
Legacy vector clipboard Застарілий векторний буфер обміну
Legacy vector clipboard (no transparency) Застарілий векторний буфер обміну (без прозорості)
Less Менше
Letter Letter
@@ -1423,7 +1424,7 @@
Matte: Підкладка:
Maximize Розгорнути
Maximum Максимум
Maximum Editability Максимальна редагованість
Maximum Editability Максимальні можливості редагування
Measure Tool Інструмент «Вимірювання»
Measurement Labels Мітки вимірів
Media Носій
@@ -1448,7 +1449,7 @@
Meters Метри
Method: Метод:
Millimeters Міліметри
Minify Мініфікувати
Minify Мінімізувати
Minimal Мінімальний
Minimize Згорнути
Minus Back Мінус нижній
@@ -1537,8 +1538,8 @@
New Graphic Style… Новий графічний стиль…
New Layer Options… Параметри нового шару…
New Layer… Новий шар…
New Opacity Masks Are Clipping Нові непрозорі маски обрізають
New Opacity Masks Are Inverted Нові непрозорі маски інвертуються
New Opacity Masks Are Clipping Нові маски непрозорості відсікають
New Opacity Masks Are Inverted Нові маски непрозорості інвертуються
New Paragraph Style Новий стиль абзацу
New Pattern Brush from Selection Новий візерунковий пензель з виділеного
New PDF Preset Новий набір PDF
@@ -1574,7 +1575,7 @@
No Document Немає документа
No document open Немає відкритого документа
No document open. Документ не відкрито.
No filter plug-ins installed Фільтруючі модулі не встановлені
No filter plug-ins installed Модулі фільтрів не встановлено
No fonts are available. Шрифти недоступні.
No gradient swatches Немає градієнтних зразків
No graphic styles Немає графічних стилів
@@ -1648,7 +1649,7 @@
Opacity Mask Info Відомості про маску непрозорості
Opacity Mask Options Параметри маски непрозорості
Opacity: Непрозорість:
Opacity: 50% Multiply Непрозорість: 50 % Збільшення
Opacity: 50% Multiply Непрозорість: 50 % Множення
Opacity: Default Непрозорість: за замовчуванням
Opacity: {value} Непрозорість: {value}
Opaque Непрозорий
@@ -1730,22 +1731,22 @@
Outline Stroke Обвести обведення
Outline Text Обвести текст
Outlines and Rules Контури та лінійки
Output Висновок
Output Виведення
Output All Blacks Accurately Виводити всі чорні точно
Output All Blacks as Rich Black Виводити всі чорні як складовий чорний
Output Black Вихідний чорний
Output condition: Умова висновку:
Output Intent Призначення висновку
Output intent profile: Профіль призначення висновку:
Output condition: Умова виведення:
Output Intent Призначення виведення
Output intent profile: Профіль призначення виведення:
Output White Вихідний білий
Output › Mode Висновок › Режим
Output: Висновок:
Output › Mode Виведення › Режим
Output: Виведення:
Overlap: Перекриття:
Overlapping Перекривається
Overlay Накладання
Overprint Накладення
Overprint and Transparency Flattener Накладання та поєднання прозоростей
Overprint and Transparency Flattener Options Параметри накладання та об’єднання прозоростей
Overprint and Transparency Flattener Накладання та зведення прозорості
Overprint and Transparency Flattener Options Параметри накладання та зведення прозорості
Overprint Black… Накладення чорного…
Overprint Fill Накладання заливки
Overprint Preview Перегляд накладання
@@ -1800,7 +1801,7 @@
Pattern Options Параметри візерунка
Pattern options are available in pattern editing mode. Параметри візерунка доступні у режимі редагування візерунка.
PDF PDF
PDF 1.3 files have no transparency: the preset flattens it. Файли PDF 1.3 не підтримують прозорість: набір поєднує її.
PDF 1.3 files have no transparency: the preset flattens it. Файли PDF 1.3 не підтримують прозорість: набір зводить її.
PDF Info Відомості про PDF
PDF Preset Набір PDF
PDF Preset: Набір PDF:
@@ -1932,10 +1933,10 @@
Profile: Профіль:
Progressive Прогресивний
Projecting Cap Закінчення, що виступає
Proof Colors Коліропроба
Proof Colors Пробні кольори
Proof Setup Налаштування кольоропроби
Properties Властивості
Proportional Oldstyle Пропорційні старий стиль
Proportional Oldstyle Пропорційні цифри старого стилю
Pucker & Bloat… Зморщування та роздування …
Pucker Tool Інструмент «Зморщування»
Punctuation Пунктуація
@@ -1949,7 +1950,7 @@
Quick Actions Швидкі дії
Quickly start a new file Швидко створити новий файл
Quit VectorCraft Вийти з VectorCraft
Radar Graph Tool Інструмент «Пелюсточна діаграма»
Radar Graph Tool Інструмент «Пелюсткова діаграма»
Radial Радіальний
Radial Glows Радіальні світіння
Radial Gradient Радіальний градієнт
@@ -2138,12 +2139,12 @@
Restored {} recovered document(s): save them to keep them Відновлено документів: {}: збережіть їх, щоб залишити
Restrict printing, editing and other tasks Обмежити друк, редагування та інші завдання
Reverse Front to Back Зворотний порядок спереду назад
Reverse Gradient Звернути градієнт
Reverse Gradient Змінити напрям градієнта
Reverse Order Зворотний порядок
Reverse Path Direction Звернути напрям контуру
Reverse Path Direction Off Звернути напрям контуру вимкнено
Reverse Path Direction On Звернути напрямок контуру увімкнено
Reverse Spine Звернути кістяк
Reverse Path Direction Змінити напрям контуру
Reverse Path Direction Off Зміна напряму контуру вимкнена
Reverse Path Direction On Зміна напряму контуру увімкнена
Reverse Spine Змінити напрям осі
Revert Повернути
Revert to the saved version of “{name}”? Повернутися до збереженої версії «{name}»?
Replace “{name}”, the file this document was opened from? Замінити «{name}» — файл, з якого відкрито цей документ?
@@ -2167,7 +2168,7 @@
Rotate View Tool Інструмент «Поворот виду»
Rotate… Повернути…
Rotation Поворот
Roughen… Огрубління…
Roughen… Надати нерівності…
Round Cap Кругле закінчення
Round Corners… Заокруглити кути…
Round Join Заокруглене з’єднання
@@ -2237,8 +2238,8 @@
Save these settings as a print preset Зберегти ці параметри як набір друку
Save to Swatches Зберегти у зразки
Save To: Зберегти у:
Save Transparency Flattener Preset Зберегти набір об’єднання прозоростей
Save Transparency Flattener Preset… Зберегти набір об’єднання прозоростей…
Save Transparency Flattener Preset Зберегти набір зведення прозорості
Save Transparency Flattener Preset… Зберегти набір зведення прозорості…
SAVED ЗБЕРЕЖЕНІ
Saved Збережено
Saved recovery data for {title} Збережено дані відновлення для {title}
@@ -2337,14 +2338,14 @@
Select Anchors Виділити опорні точки
Select Appearance Item Виділити елемент оформлення
Select Art Виділити малюнок
Select art and choose Object › Pattern › Make. Перейдіть до малюнка та оберіть «Об’єкт › Візерунок › Створити».
Select art and click New Symbol to make one. Перейдіть до малюнка і натисніть «Новий символ», щоб створити його.
Select art and choose Object › Pattern › Make. Виділіть малюнок та виберіть «Об’єкт › Візерунок › Створити».
Select art and click New Symbol to make one. Виділіть малюнок і натисніть «Новий символ», щоб створити його.
Select art and use New Brush to make one. Виділіть малюнок та використовуйте «Новий пензель», щоб створити його.
Select Freeform Point Виділити довільну точку
Select Gradient Stop Виділити точку переходу градієнта
Select Guides Виділити напрямні
Select Objects Виділити об’єкти
Select objects to see their CSS, or Generate CSS for the whole document. Перейдіть до об’єктів, щоб побачити CSS, або створіть CSS для всього документа.
Select objects to see their CSS, or Generate CSS for the whole document. Виділіть об’єкти, щоб побачити їхній CSS, або створіть CSS для всього документа.
Select Same Tint % Виділити з тим же % відтінку
Select Slices Виділити фрагменти
Select styled art and click New Graphic Style. Виділіть оформлений малюнок та натисніть «Новий графічний стиль».
@@ -2363,14 +2364,14 @@
Selection & Anchor Display Відображення виділення та опорних точок
Selection Only Тільки виділення
Selection Tool Інструмент «Виділення»
Send Backward На один рівень тому
Send Backward На один рівень назад
Send to Back На задній план
Send to Current Layer Надіслати на поточний шар
Sentence case Як у реченні
Separate colors into rows Розділити кольори по рядках
Separate several keywords with commas. Розділяйте ключові слова комами.
Separations list the document's inks here: one page per ink that prints. Кольорові поділу перераховують тут фарби документа: одна сторінка на кожну фарбу, що друкується.
Separations Preview Перегляд кольороподілів
Separations list the document's inks here: one page per ink that prints. Тут перелічено фарби документа для кольороподілу: одна сторінка на кожну фарбу, що друкується.
Separations Preview Перегляд кольороподілу
Serialize Document Серіалізувати документ
Serif / Mincho Serif / Mincho
Server-side (.map) Серверна частина (.map)
@@ -2432,7 +2433,7 @@
Show Embedded Показати впроваджені
Show Find Field Показати поле пошуку
Show Font Names in English Показувати назви шрифтів англійською
Show Gradient Annotator Показати анотатор градієнта
Show Gradient Annotator Показати маркер градієнта
Show Gradient Swatches Показати градієнтні зразки
Show Grid Показати сітку
Show Grid (⌘') Показати сітку (⌘')
@@ -2631,6 +2632,7 @@
Swash Розчерк
Swatch Conflict Конфлікт зразків
Swatch Conflicts Конфлікти зразків
Swatch exchange files keep solid colors only. Файли обміну зразками зберігають лише суцільні кольори.
Swatch Libraries Бібліотеки зразків
Swatch Libraries Menu Меню "Бібліотеки зразків"
Swatch Library Бібліотека зразків
@@ -2659,7 +2661,7 @@
Use Library Item Використати елемент бібліотеки
Graphic Графіка
Show all open documents Показати всі відкриті документи
Symbol Instance Примірник символ
Symbol Instance Екземпляр символу
Symbol Libraries Бібліотеки символів
Symbol Libraries (on the roadmap) Бібліотеки символів (у плані розвитку)
Symbol Screener Tool Інструмент «Прозорість символів»
@@ -2678,7 +2680,7 @@
Tab Stops Табуляції
Tabs Табуляції
Tabular Lining Табличні цифри
Tabular Oldstyle Таблиці старого стилю
Tabular Oldstyle Табличні цифри старого стилю
Target Об’єкт
Target Contents Вміст об’єкта
Target: Об’єкт:
@@ -2687,7 +2689,7 @@
Temperature/Tint… Температура/відтінок…
Template Шаблон
Templates Шаблони
Templates Folder Шаблони папки
Templates Folder Папка шаблонів
Templates… Шаблони…
Text Displayed in Cell: Текст, що відображається в комірці:
Text Export Options Параметри експорту тексту
@@ -2772,12 +2774,12 @@
Transforms Трансформування
Transform… Трансформувати…
Transparency Прозорість
Transparency Flattener Presets Набори поєднання прозоростей
Transparency Flattener Presets… Набори поєднання прозоростей…
Transparency Flattener Presets Набори зведення прозорості
Transparency Flattener Presets… Набори зведення прозорості…
Transparency Grid Сітка прозорості
Transparency Info Відомості про прозорість
Transparency is flattened with the preset. Type is written as outlines; gradients as bands of colour. Прозорість поєднується з набором. Текст записується як контури; градієнти – як колірні смуги.
Transparency is flattened with the preset. Type is written as outlines; gradients stay smooth. Прозорість поєднується з набором. Текст записується як контури; градієнти залишаються гладкими.
Transparency is flattened with the preset. Type is written as outlines; gradients as bands of colour. Прозорість зводиться за параметрами набору. Текст записується як контури; градієнти — як колірні смуги.
Transparency is flattened with the preset. Type is written as outlines; gradients stay smooth. Прозорість зводиться за параметрами набору. Текст записується як контури; градієнти залишаються гладкими.
Transparency Options Параметри прозорості
Transparent Прозорий
Transparent (Default) Прозорий (за замовчуванням)
@@ -2859,7 +2861,7 @@
Use document bleed settings Використовувати параметри вильоту документа
Use Even-Odd Fill Rule Використовувати правило заливки «парне–непарне»
Use Japanese Crop Marks Використовувати японські мітки обрізання
Use Low Resolution Proxy for Linked EPS Використовувати низькодозволений проксі для пов’язаних EPS
Use Low Resolution Proxy for Linked EPS Використовувати попередній перегляд низької роздільної здатності для пов’язаних EPS
Use Non-Zero Winding Fill Rule Використовувати правило заливки «ненульове заповнення»
Use Precise Cursors Використовувати точні курсори
Use Pressure Pen Використовувати перо з натиском
@@ -2981,6 +2983,7 @@
Scrub Numeric Fields by Dragging Змінювати числові поля перетягуванням
{count} file(s) in {folder}{note}. Show the package folder? файлів: {count} {folder}{note}. Показати папку пакета?
{count} linked file(s) not found не знайдено пов’язаних файлів: {count}
fonts not copied: {fonts} шрифти не скопійовано: {fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? пов’язані зображення ({count}) змінилися з моменту збереження цього документа. Показати нові версії?
{count} more rules: Export writes every one. ще правил: {count}: експорт записує все.
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. пропущено об’єкти без імені: {count}: назвіть їх або увімкніть «Об’єкти без імені» у меню панелі.
@@ -3098,15 +3101,15 @@
Merged PRs Об’єднані PR
Commits Коміти
Lines added Додані рядки
Lines deleted Віддалені рядки
Lines deleted Видалені рядки
Line delta Різниця рядків
Binary assets added Додані бінарні ресурси
Binary assets removed Віддалені бінарні ресурси
Binary assets removed Видалені бінарні ресурси
First commit Перший коміт
Last commit Останній коміт
First Перший
Last Останній
{people} contributors · {commits} commits {people} учасників · {commits} коммітів
{people} contributors · {commits} commits {people} учасників · {commits} комітів
No contributor data was built into this copy. Ця копія не містить даних про учасників.
No model credits were built into this copy. Ця копія не містить відомостей про моделі.
Company Компанія
@@ -3122,15 +3125,15 @@ axis Horizontal Горизонтальна
axis Vertical Вертикальна
axis Both Обидві
Drag to move Перетягніть для переміщення
Drag to float as a toolbar Перетягніть, щоб зробити плаваючою панеллю інструментів
Drag to float as a toolbar Перетягніть, щоб від’єднати панель інструментів
Put back in the toolbar Повернути на панель інструментів
Float Panel Зробити панель плаваючою
Float Panel Від’єднати панель
Dock Panel Прикріпити панель
Drag to float the panel group Перетягніть, щоб зробити групу панелей плаваючою
Drag to float the panel group Перетягніть, щоб від’єднати групу панелей
Put back in the dock Повернути у док
Drag to float the toolbar Перетягніть, щоб зробити панель інструментів плаваючою
Drag to float the toolbar Перетягніть, щоб від’єднати панель інструментів
Drag to the window's left edge to dock Перетягніть до лівого краю вікна для прикріплення
Float Tool Group Зробити групу інструментів плаваючою
Float Tool Group Від’єднати групу інструментів
@msg no library `{id}` немає бібліотеки `{id}`
@msg select some type first спочатку виділіть текст
@msg {_1} has no {_2} style {_1} не має накреслення {_2}
@@ -3152,7 +3155,7 @@ axis Both Обидві
@msg Combine Slices: the slices have no bounds Об’єднання фрагментів: фрагменти не мають кордонів
@msg Convert to Artboards: selection has no area Перетворення на монтажні області: виділення не має області
@msg Convert to Shape: no rectangles or ellipses selected Перетворення на фігуру: не виділено прямокутники або еліпси
@msg Copied the CSS of {rules} object(s) Скопійовано CSS для {rules} об’єкта(ів)
@msg Copied the CSS of {rules} object(s) Скопійовано CSS об’єктів: {rules}
@msg Corners edits the corners of a path «Кути» редагує кути контуру
@msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e}
@msg Couldn't open {name}: {e} Не вдалося відкрити {name}: {e}
@@ -3175,8 +3178,8 @@ axis Both Обидві
@msg Expand: nothing to expand Розбір: нема чого розбирати
@msg Exported {count} file(s) to {folder} Експортовано файли: {count} до {folder}
@msg Exported {path} Експортовано: {path}
@msg Flatten Transparency: select objects to flatten Об’єднання прозоростей: виділіть об’єкти для об’єднання
@msg Flatten Transparency: {e} Об’єднання прозоростей: {e}
@msg Flatten Transparency: select objects to flatten Зведення прозорості: виділіть об’єкти для зведення
@msg Flatten Transparency: {e} Зведення прозорості: {e}
@msg Image Trace: the traced image is missing Трасування зображення: зображення, що трасується, відсутнє
@msg Imported {what}: {_1} Імпортовано: {what}: {_1}
@msg Installed plug-in {_1} Встановлено модуль {_1}
@@ -3328,7 +3331,7 @@ axis Both Обидві
@msg image would be too large; lower the resolution зображення буде завеликим; зменште роздільну здатність
@msg index must be a number or first, previous, next or last index має бути числом або first, previous, next, last
@msg index must be a number or first, previous, next or last, not `{other}` index повинен бути числом або first, previous, next, last, а не `{other}`
@msg installing from a path is not available on the web; pass the module as `dataBase64` встановлення з файла недоступне у вебверсії; передайте модуль як `dataBase64`
@msg installing from a path is not available on the web; pass the module as `dataBase64` встановлення з файлу недоступне у вебверсії; передайте модуль як `dataBase64`
@msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) внутрішня помилка `{cmd}`: {msg} (документ залишений у попередньому стані; будь ласка, повідомте про цю помилку)
@msg internal error: {msg} (please report this bug) внутрішня помилка: {msg} (будь ласка, повідомте про цю помилку)
@msg invalid PDF setting: {0} неприпустимий параметр PDF: {0}
@@ -3474,7 +3477,7 @@ axis Both Обидві
@msg plug-in exceeded its {0} модуль перевищив свій {0}
@msg plug-in failed: {0} модуль завершився помилково: {0}
@msg plug-in manifest: {0} маніфест модуля: {0}
@msg plug-in output: {0} висновок модуля: {0}
@msg plug-in output: {0} виведення модуля: {0}
@msg plug-in parameters: {0} параметри модуля: {0}
@msg plug-in trapped: {0} модуль зупинено з помилкою: {0}
@msg print settings are not an object параметри друку не є об’єктом
@@ -3499,9 +3502,9 @@ axis Both Обидві
@msg select a symbol instance виділіть екземпляр символу
@msg select an Image Trace object виділіть об’єкт трасування зображення
@msg could not decode image: {0} не вдалося декодувати зображення: {0}
@msg image is empty зображення порожньо
@msg image is empty зображення порожнє
@msg the image is {width} × {height} pixels, more than Image Trace takes ({max} megapixels) зображення має розмір {width} × {height} пікселів, що більше, ніж приймає трасування зображення ({max} мегапікселів)
@msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset це трасування створило б більше {max} опорних точок, що більше, ніж документ може плавно відобразити: збільшіть «Шум», зменшіть «Контури» або «Кольори» або виберіть набір з меншою точністю
@msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset це трасування створило б більше {max} опорних точок, що більше, ніж документ може плавно відобразити: збільште «Шум», зменште «Контури» або «Кольори» або виберіть набір з меншою точністю
@msg select an envelope виділіть оболонку
@msg select an image виділіть зображення
@msg select an object in perspective виділіть об’єкт у перспективі
@@ -3663,7 +3666,7 @@ axis Both Обидві
@msg A browser with WebGPU or WebGL2 is required. Потрібен браузер із WebGPU або WebGL2.
@msg The graphics were lost and couldn't be restarted. Графіку було втрачено, і її не вдалося перезапустити.
@msg Your unsaved changes are kept in this browser: reload the page to get them back. Ваші незбережені зміни зберігаються у цьому браузері: перезавантажте сторінку, щоб повернути їх.
@msg Reload the page to go on (changes not saved yet may be lost). Перезавантажте сторінку, щоб продовжити.
@msg Reload the page to go on (changes not saved yet may be lost). Перезавантажте сторінку, щоб продовжити (незбережені зміни можуть бути втрачені).
@msg tool (a tool id) is required потрібно tool (ідентифікатор інструменту)
@msg {tool} isn't in a toolbar group of several tools {tool} не входить до групи панелі інструментів з кількох інструментів
@msg onto must name a panel floating in another group onto має називати панель, що плаває в іншій групі
@@ -3694,7 +3697,7 @@ axis Both Обидві
Settings Налаштування
Break Link Розірвати зв’язок
On: one locked object showing the document, updated when it changes. Увімк.: один заблокований об’єкт, який показує документ і оновлюється під час його зміни.
Off: an editable copy of its art, embedded in this document. Вимк.: редагована копія зображення, введена в цей документ.
Off: an editable copy of its art, embedded in this document. Вимк.: редагована копія графіки, вбудована в цей документ.
Images: link to the file instead of only embedding it. Зображення: пов’язувати із файлом замість простого впровадження.
VectorCraft documents: one locked object, updated when the file changes. Документи VectorCraft: один заблокований об’єкт, який оновлюється під час зміни файлу.
A file dialog is open: choose there first Відкрито вікно вибору файлу: спочатку зробіть вибір у ньому
Can't render this file because it contains an unexpected character in line 622 and column 40.
+3
View File
@@ -144,6 +144,7 @@
Appearance Panel 外观面板
Appearance panel 外观面板
Applies when the linked file is relinked or updated. 在重新链接或更新链接文件时应用。
Apply 应用
Apply Brush 应用画笔
Apply Character Style 应用字符样式
Apply Effect 应用效果
@@ -2556,6 +2557,7 @@
Swash 花饰字
Swatch Conflict 色板冲突
Swatch Conflicts 色板冲突
Swatch exchange files keep solid colors only. 色板交换文件仅保留纯色。
Swatch Libraries 色板库
Swatch Libraries Menu 色板库菜单
Swatch Library 色板库
@@ -2909,6 +2911,7 @@
Scrub Numeric Fields by Dragging 拖动以调整数值字段
{count} file(s) in {folder}{note}. Show the package folder? {folder} 中有 {count} 个文件{note}。要显示打包文件夹吗?
{count} linked file(s) not found 找不到 {count} 个链接文件
fonts not copied: {fonts} 未复制的字体:{fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? 自存储此文档后,有 {count} 个链接图像已更改。要显示新版本吗?
{count} more rules: Export writes every one. 另有 {count} 条规则:导出时会全部写出。
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略过 {count} 个未命名对象:请为它们命名,或在面板菜单中开启“未命名对象”。
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -155,6 +155,7 @@
Appearance panel 外觀面板
Applies when the linked file is relinked or updated. 重新連結或更新連結檔案時套用。
Applies the next time VectorCraft starts. 下次啟動 VectorCraft 時生效。
Apply 套用
Apply Brush 套用筆刷
Apply Character Style 套用字元樣式
Apply Effect 套用效果
@@ -2642,6 +2643,7 @@
Swash 花體字
Swatch Conflict 色票衝突
Swatch Conflicts 色票衝突
Swatch exchange files keep solid colors only. 色票交換檔案僅保留純色。
Swatch Libraries 色票資料庫
Swatch Libraries Menu 色票資料庫選單
Swatch Library 色票資料庫
@@ -2997,6 +2999,7 @@
Scrub Numeric Fields by Dragging 拖曳以調整數值欄位
{count} file(s) in {folder}{note}. Show the package folder? {folder} 中有 {count} 個檔案{note}。要顯示封裝資料夾嗎?
{count} linked file(s) not found 找不到 {count} 個連結檔案
fonts not copied: {fonts} 未複製的字體:{fonts}
{count} linked image(s) changed since this document was saved. Show the new versions? 自儲存此文件後,有 {count} 個連結影像已變更。要顯示新版本嗎?
{count} more rules: Export writes every one. 另有 {count} 條規則:匯出時會全部寫出。
{count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. 已略過 {count} 個未命名物件:請為它們命名,或在面板選單中開啟「未命名物件」。
Can't render this file because it contains an unexpected character in line 6 and column 47.
+24 -8
View File
@@ -516,6 +516,29 @@ pub fn save_command_output(app: &mut VectorcraftApp, id: &str, ext: &str, params
Ok(path)
}
/// Run an engine command that returns `{data}` or `{dataBase64}` and write the bytes to a file
/// picked with file name `name` suggested next to the document (the web downloads them as `name`)
/// → where they went.
pub(crate) fn save_command_output_named(app: &mut VectorcraftApp, id: &str, name: &str, params: Value) -> Result<String, String> {
let mut v = app.session.execute(id, &params).map_err(|e| e.to_string())?;
let bytes = take_output(&mut v)?;
let path = write_named(app, None, name, &bytes)?;
app.status(format!("Saved {path}"));
Ok(path)
}
/// The bytes a command returned, taken out of its result `v`, which keeps the rest: binary output
/// comes as base64, text (swatch libraries) as is.
fn take_output(v: &mut Value) -> Result<Vec<u8>, String> {
let o = v.as_object_mut().ok_or("no data")?;
let bytes = match (o.remove("dataBase64"), o.remove("data")) {
(Some(Value::String(b64)), _) => vectorcraft_format::base64_decode(&b64),
(_, Some(Value::String(text))) => Some(text.into_bytes()),
_ => None,
};
bytes.ok_or_else(|| "no data".into())
}
/// Run an engine command that returns `{dataBase64}` without its `path` and write the bytes to
/// that path (else a picked or suggested name) → (path, the command's result without the data).
/// The command runs before a path is asked for, so bad params never open a save dialog, except
@@ -532,14 +555,7 @@ pub(crate) fn run_to_file(app: &mut VectorcraftApp, id: &str, ext: &str, mut par
path = Some(picked);
}
let mut v = app.session.execute(id, &params).map_err(|e| e.to_string())?;
// Binary output comes as base64, text (swatch libraries) as is; the result keeps the rest.
let o = v.as_object_mut().ok_or("no data")?;
let bytes = match (o.remove("dataBase64"), o.remove("data")) {
(Some(Value::String(b64)), _) => vectorcraft_format::base64_decode(&b64),
(_, Some(Value::String(text))) => Some(text.into_bytes()),
_ => None,
};
let bytes = bytes.ok_or("no data")?;
let bytes = take_output(&mut v)?;
let path = match path {
Some(p) => p,
None => target_path(app, None, ext)?,
+14 -2
View File
@@ -285,6 +285,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name, or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
),
(
"ui.cropImage",
"Crop Image",
"",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box",
),
("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"),
(
"file.export.pdf",
@@ -365,7 +371,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.saveSwatchLibrary",
"Save Swatch Library…",
"",
"{names?: [the swatches selected in the Swatches panel]} open Save Swatch Library (dialog `saveSwatchLibrary`: name, format: vcswatches|gpl|css, user: save to the user library folder, selectedOnly); OK runs swatch.library.save",
"{names?: [the swatches selected in the Swatches panel]} open Save Swatch Library (dialog `saveSwatchLibrary`: name, format: vcswatches|gpl|ase|css, user: save to the user library folder, selectedOnly); OK runs swatch.library.save",
),
("window.userSwatchLibrary1", "User Swatch Library 1", "", "{} open the 1. User Defined swatch library (swatch.library.list, category user)"),
("window.userSwatchLibrary2", "User Swatch Library 2", "", "{} open the 2. User Defined swatch library"),
@@ -1140,6 +1146,11 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
"tool.setOption" => app.session.set_tool_option_cmd(p),
"effect.dialog" => crate::dialogs::open_effect_dialog(app, p),
"ui.recolorDialog" => crate::dialogs::recolor::open(app, p),
"ui.cropImage" if !selected_image(app, |_| true) => Err("select an image".into()),
"ui.cropImage" => {
app.select_tool(vectorcraft_tools::cropimage::ID);
Ok(json!({"tool": app.session.tool_id()}))
}
"ui.paramDialog" => {
let cmd = s("command").unwrap_or_default();
let mut fields = p.get("params").and_then(Value::as_object).cloned().unwrap_or_default();
@@ -1839,6 +1850,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
id["view.goto".len()..].parse::<usize>().is_ok_and(|n| n >= 1 && app.session.active().is_some_and(|d| n <= d.doc.views.len()))
}
"effect.dialog" | "ui.recolorDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
"ui.cropImage" => selected_image(app, |_| true),
"effect.applyLast" | "effect.last" => app.last_effect.is_some() && app.session.active().is_some_and(|d| !d.selection.is_empty()),
"file.export.pdf" | "ui.savePdfDialog" | "ui.fileInfoDialog" | "ui.rasterEffectsSettingsDialog" => app.session.active().is_some(),
"ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" => app.session.active().is_some(),
@@ -2057,7 +2069,7 @@ pub fn menu_tree() -> Vec<(&'static str, Vec<Item>)> {
Sep,
c("Expand…", "ui.expandDialog"),
c("Expand Appearance", "effect.expandAppearance"),
c("Crop Image", "object.cropImage"),
c("Crop Image", "ui.cropImage"),
c("Rasterize…", "object.rasterize"),
cp("Create Gradient Mesh…", "object.mesh.create", json!({"rows": 4, "cols": 4, "appearance": "flat", "highlight": 100})),
cp(
@@ -617,6 +617,47 @@ mod tests {
assert!(!builtin_library(&open.id) && builtin_library(vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES));
}
#[test]
fn the_save_dialog_writes_swatch_exchange_files() {
let written = std::rc::Rc::new(std::cell::RefCell::new(vec![]));
let w = written.clone();
let services = crate::Services {
pick_save: Some(Box::new(|p: &crate::FilePick| Some(format!("/tmp/{}", p.name)))),
write: Some(Box::new(move |p: &str, b: &[u8]| {
w.borrow_mut().push((p.to_string(), b.to_vec()));
Ok(())
})),
..Default::default()
};
let mut app = VectorcraftApp::new(Session::new(), services);
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("ui.saveSwatchLibrary", json!({})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("format".into(), json!("ase"));
d.fields.insert("name".into(), json!("Brand Kit"));
let text = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
assert!(text.contains("Swatch Exchange (.ase)") && text.contains("Swatch exchange files keep solid colors only."), "{text}");
crate::dialogs::confirm(&mut app).unwrap();
let (path, bytes) = written.borrow()[0].clone();
assert_eq!(path, "/tmp/Brand Kit.ase", "the save panel suggests the name");
let lib = vectorcraft_color::palette_io::read_bytes(&bytes, "x").unwrap();
let solid = app.session.doc().unwrap().doc.swatches_iter().filter(|w| w.paint.color().is_some()).count();
assert_eq!(lib.len(), solid, "every solid color of the document");
// The web downloads the file under that name.
let downloads = std::rc::Rc::new(std::cell::RefCell::new(vec![]));
let dl = downloads.clone();
let services =
crate::Services { download: Some(Box::new(move |name: &str, _: &[u8]| dl.borrow_mut().push(name.to_string()))), ..Default::default() };
let mut web = VectorcraftApp::new(Session::new(), services);
web.run("file.new", json!({"width": 100, "height": 100})).unwrap();
web.run("ui.saveSwatchLibrary", json!({})).unwrap();
let d = web.ui.dialog.as_mut().unwrap();
d.fields.insert("format".into(), json!("ase"));
d.fields.insert("name".into(), json!(" Brand: Kit. "));
crate::dialogs::confirm(&mut web).unwrap();
assert_eq!(*downloads.borrow(), ["Brand- Kit.ase"], "the name made safe as a file name, as for User Defined");
}
#[test]
fn swatch_exchange_files_without_a_path_open_in_the_library_panel() {
// A file opened on the web has no path; open_bytes passes its bytes as dataBase64.
+1 -1
View File
@@ -119,7 +119,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
if is_image {
crate::panels::image_trace::trace_button(app, ui, ui.available_width());
actions.push((tl!("Crop Image"), "object.cropImage"));
actions.push((tl!("Crop Image"), "ui.cropImage"));
actions.push((tl!("Mask"), "object.maskImage"));
}
actions.push((tl!("Offset Path"), "object.path.offsetPath"));
+1 -1
View File
@@ -436,7 +436,7 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool
ui.separator();
link_buttons(app, ui, id, linked, &name, None);
crate::panels::image_trace::trace_button(app, ui, crate::panels::image_trace::TRACE_BUTTON_W);
for (label, cmd, w) in [(tl!("Mask"), "object.maskImage", 52.0), (tl!("Crop Image"), "object.cropImage", 84.0)] {
for (label, cmd, w) in [(tl!("Mask"), "object.maskImage", 52.0), (tl!("Crop Image"), "ui.cropImage", 84.0)] {
if widgets::flat_button(ui, label, w).clicked() {
crate::menus::invoke(app, cmd, json!({}));
}
+39 -2
View File
@@ -414,12 +414,18 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) {
{
let _ = app.run("edit.clear", json!({}));
}
// Single-key tool shortcuts (no Cmd/Ctrl/Alt).
// Single-key tool shortcuts (no Cmd/Ctrl/Alt). With a layout without Latin letters (Persian,
// Arabic, Russian, Greek…) the key's position stands in for what it types (#793).
let events: Vec<(String, Modifiers)> = ctx.input(|i| {
let mut physical = None;
i.events
.iter()
.filter_map(|e| match e {
egui::Event::Text(t) => Some((t.clone(), i.modifiers)),
egui::Event::Key { physical_key, pressed: true, .. } => {
physical = *physical_key;
None
}
egui::Event::Text(t) => Some((latin(t, physical), i.modifiers)),
_ => None,
})
.collect()
@@ -445,6 +451,16 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
}
/// What a single-key shortcut reads for `text`, typed by the key at `physical`: the text itself,
/// or, when it holds no ASCII character (a layout without Latin letters), what that key types on a
/// US layout, so V selects the Selection tool whatever the V key types.
fn latin(text: &str, physical: Option<Key>) -> String {
match physical {
Some(k) if !text.is_ascii() => k.symbol_or_name().to_lowercase(),
_ => text.to_string(),
}
}
/// The digit a number-row or keypad key types.
fn digit_of(k: Key) -> Option<u8> {
const DIGITS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9];
@@ -678,6 +694,27 @@ mod tests {
assert_eq!(app.session.tool_id(), "curvature");
}
/// #793: with a layout without Latin letters the one-key shortcuts go by the key's position:
/// the P key typing Persian `ح` chooses the Pen, the V key typing Russian `м` the Selection
/// tool. A Latin layout keeps the letter typed: AZERTY's A (the Q key's place) is A.
#[test]
fn one_key_shortcuts_follow_the_key_on_layouts_without_latin_letters() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let typed = |key, physical, text: &str| {
vec![
egui::Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers: Modifiers::NONE },
egui::Event::Text(text.into()),
]
};
frame(&mut app, typed(Key::P, Key::P, "ح"));
assert_eq!(app.session.tool_id(), "pen");
frame(&mut app, typed(Key::V, Key::V, "м"));
assert_eq!(app.session.tool_id(), "selection");
frame(&mut app, typed(Key::A, Key::Q, "a"));
assert_eq!(app.session.tool_id(), "directSelection", "AZERTY: the letter typed");
}
#[test]
fn plus_typed_any_way_zooms_in() {
assert_eq!(parse("Cmd++"), parse("Cmd+="), "`+` and `=` are one chord key");
+12 -5
View File
@@ -348,11 +348,18 @@ fn key_equivalents_run_through_the_normal_shortcut_path_once() {
let before = undo(&m);
m.key_equivalent("Cmd+Z");
assert_eq!(undo(&m), before - 1, "⌘Z undid one step");
let synced = m.fake.synced();
assert!(synced >= 1, "the menus were built");
m.frame(vec![]);
m.frame(vec![]);
assert_eq!(m.fake.synced(), synced, "nothing changed: the menus weren't read again");
assert!(m.fake.synced() >= 1, "the menus were built");
// Idle frames don't read the menus again. The shortcut and plug-in generations are
// process-wide, and tests running alongside with other shortcuts bump them (rightly reading
// the menus again), so judge two idle frames in which they held still.
let globals = || (crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed), crate::menus::plugin_revision());
let quiet = (0..50).any(|_| {
let (before, synced) = (globals(), m.fake.synced());
m.frame(vec![]);
m.frame(vec![]);
globals() == before && m.fake.synced() == synced
});
assert!(quiet, "nothing changed: the menus weren't read again");
assert_eq!(crate::control::inspect(&m.app, &m.ctx)["nativeMenuBar"], json!(true));
}
+41
View File
@@ -407,3 +407,44 @@ fn a_vectorcraft_document_places_linked_and_edit_original_opens_it() {
let d = app.ui.dialog.as_ref().unwrap();
assert!(crate::dialogs::place::link_tip(d).contains("VectorCraft documents"));
}
/// Tool key `key` as the Control bar's Apply (Enter) and Cancel (Escape) send it.
fn tool_key(app: &mut VectorcraftApp, key: vectorcraft_tools::ToolKey) {
let view = app.view_info();
let r = app.session.tool_key(key, vectorcraft_tools::Mods::default(), view);
crate::canvas::apply_requests(app, r);
}
/// #734: Crop Image shows a crop box on the image instead of cropping to the artboard at once (an
/// image inside the artboard had nothing to cut); Apply crops to the box in one undo step, Cancel
/// leaves the image whole, and both go back to the Selection tool.
#[test]
fn crop_image_shows_a_box_that_apply_crops_to() {
use vectorcraft_tools::ToolKey;
let mut app = app();
place_picked(&mut app, &temp_file("crop.png", &png(100, 50, 72.0)));
app.ui.dialog.as_mut().unwrap().fields.insert("link".into(), json!(false));
crate::dialogs::confirm(&mut app).unwrap();
let whole = selected_image(&app).geometric_bounds().unwrap();
assert!(crate::menus::enabled(&app, "ui.cropImage"));
app.run("ui.cropImage", json!({})).unwrap();
assert_eq!(app.session.tool_id(), "cropImage");
tool_key(&mut app, ToolKey::Escape);
assert_eq!(app.session.tool_id(), "selection");
assert_eq!(selected_image(&app).geometric_bounds(), Some(whole), "Cancel leaves it whole");
// The box set to the image's left half, as the Control bar's fields set it, then Apply.
app.run("ui.cropImage", json!({})).unwrap();
app.run("tool.setOption", json!({"key": "rect", "value": [whole.x0, whole.y0, whole.width() / 2.0, whole.height()]})).unwrap();
tool_key(&mut app, ToolKey::Enter);
assert_eq!(app.session.tool_id(), "selection");
let b = selected_image(&app).geometric_bounds().unwrap();
assert!(
(b.x0 - whole.x0).abs() < 1e-6 && (b.width() - whole.width() / 2.0).abs() < 1e-6 && (b.height() - whole.height()).abs() < 1e-6,
"{b:?} of {whole:?}"
);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(selected_image(&app).geometric_bounds(), Some(whole), "one undo step");
// Without an image selected there's nothing to crop.
app.run("select.none", json!({})).unwrap();
assert!(!crate::menus::enabled(&app, "ui.cropImage") && app.run("ui.cropImage", json!({})).is_err());
}
+41 -2
View File
@@ -5,9 +5,9 @@
//! Bottom: fill/stroke proxy, colour/gradient/none, drawing modes, screen mode, Edit Toolbar.
use egui::{Color32, CornerRadius, Sense, Stroke, Ui, pos2, vec2};
use serde_json::json;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_tools::{TOOL_GROUPS, ToolInfo, tool_info};
use vectorcraft_tools::{Mods, TOOL_GROUPS, ToolInfo, ToolKey, tool_info};
use crate::theme::{self, Tokens};
use crate::{VectorcraftApp, icons, widgets};
@@ -350,6 +350,9 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.session.tool_id() == "puppetWarp" {
return puppet_warp_options(app, ui);
}
if app.session.tool_id() == vectorcraft_tools::cropimage::ID {
return crop_options(app, ui);
}
if app.session.tool_id() == "artboard" {
crate::panels::artboards::art_options(app, ui);
ui.separator();
@@ -372,6 +375,42 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.separator();
}
/// Crop Image's box: its centre (X, Y) and size (W, H) in the general unit, set through the tool's
/// `rect` option, then Apply (Enter) and Cancel (Escape).
fn crop_options(app: &mut VectorcraftApp, ui: &mut Ui) {
let set = app.session.tool_options()["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::<Vec<_>>()[..] {
[x, y, w, h] => Some(vectorcraft_geom::Rect::new(x, y, x + w, y + h)),
_ => None,
});
let Some((_, _, r)) = app.session.active().and_then(|st| vectorcraft_tools::cropimage::crop_box(&st.doc, &st.selection, set)) else { return };
let t = Tokens::get(ui.ctx());
let units = app.session.general_unit();
let c = r.center();
for (k, lbl, v) in [("x", "X:", c.x), ("y", "Y:", c.y), ("width", "W:", r.width()), ("height", "H:", r.height())] {
widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim));
if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0) {
let (mut c, mut w, mut h) = (c, r.width(), r.height());
match k {
"x" => c.x = nv,
"y" => c.y = nv,
"width" => w = nv.max(0.0),
_ => h = nv.max(0.0),
}
let rect = [c.x - w / 2.0, c.y - h / 2.0, w, h];
app.run("tool.setOption", json!({ "key": "rect", "value": rect })).ok();
}
}
ui.separator();
for (label, key) in [(tl!("Apply"), ToolKey::Enter), (tl!("Cancel"), ToolKey::Escape)] {
if widgets::flat_button(ui, label, 64.0).clicked() {
let view = app.view_info();
let r = app.session.tool_key(key, Mods::default(), view);
crate::canvas::apply_requests(app, r);
}
}
ui.separator();
}
fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens) {
ui.vertical_centered(|ui| crate::panels::proxy(app, ui, 36.0));
ui.add_space(5.0);
+154
View File
@@ -0,0 +1,154 @@
# Affinity 3 `.af`: source audit and validation boundaries
Audit date: 2026-10-09. This audit focuses on the unified `.af` document format,
not on increasing the number of legacy `.afdesign`, `.afphoto` or `.afpub` files.
The source expansion adds 28 original Affinity 3.2.3 saves and one derived
regression input to the four existing current-version `.af` illustrations.
Passing a reader test, retaining editable objects and matching a saved picture
are separate claims. None demonstrates compatibility with every Affinity feature.
## Clean-room evidence
The inputs for this work are public documentation, fixture licensing/provenance
notices and public document data. No Affinity executable, installation resources,
private API or third-party Affinity parser implementation was read. No Adobe
application was run or used as an oracle. Existing project restrictions still
apply to Adobe-authored assets and software.
The additional Patchy files below were fetched as individual document blobs.
Only its fixture directory listing, MIT license and third-party notice were read;
its importer, tests and authoring scripts were not consulted. These files provide
independently authored input data, not an implementation to translate.
The upstream notice attributes the ordinary `tiny-*.af` files to the Patchy team,
using licensed Affinity 3.2.3 through its public JavaScript SDK, and describes the
content as original, with no third-party content. It separately identifies
`tiny-lazy-placed.af` as a deterministic byte-level derivation. That file is a
regression/hostile-input case, not evidence that Affinity saved the derived layout.
See the pinned [provenance notice](https://github.com/SethRobinson/Patchy/blob/de84eab550758b30fa062e479f5778cce7693b73/NOTICE-THIRD-PARTY.md)
and [MIT license](https://github.com/SethRobinson/Patchy/blob/de84eab550758b30fa062e479f5778cce7693b73/LICENSE).
An audit using this project's parser found absolute personal-path metadata in all
33 current `.af` files, including the four existing CC0 illustrations. These
values were not copied into reports or source, and are not imported into the
engine document. Do not claim that the downloadable inputs contain no personal
paths. Inspection of archive-entry names/signatures and stream byte/blob values
found no TTF, OTF, TTC, WOFF or WOFF2 binaries; this signature check is not a
complete font-file validation.
## Public-source decisions
| Source | Current `.af` evidence | Features or equivalent files advertised | Rights and decision |
|---|---|---|---|
| [samuel-etver/vector-art](https://github.com/samuel-etver/vector-art/tree/255f8add3c8f0740196e22bd59502b811b532f0b/simple) | Four `.af` files already pinned by this project | Mexican character illustrations and playing cards; real vector art | CC0. Retain the current-version vector examples; no paired PSD identified. |
| [SethRobinson/Patchy fixture data](https://github.com/SethRobinson/Patchy/tree/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af) | 29 `.af` blobs at commit `de84eab550758b30fa062e479f5778cce7693b73`; author states Affinity 3.2.3, with one separately identified derived file | Artboards, text, placed images, groups, vectors, masks, shapes, transforms, raster depth, color spaces and unsupported-feature examples | MIT, copyright Seth A. Robinson, 2026; original fixture content per notice. Fetch pinned data only, SHA-256 verify, preserve attribution. No paired PSD identified in this directory. |
Other public `.af` sources found while searching (commercial templates and mockups, and
pages offering files without a redistribution licence) were left out: a downloadable
template, or a free font it uses, isn't permission to redistribute it. Files published
before the unified format aren't current-version evidence. This is a sample of
discovered sources, not a claim that every public file was found.
No openly redistributable, inspected Affinity 3 `.af`/PSD pair covering complex
typography and artboards was located in this audit.
## Additional current-version fixture inventory
The corpus names below map to upstream `test-fixtures/af/tiny-<suffix>.af`.
For example, `patchy-artboards.af` comes from
[tiny-artboards.af](https://github.com/SethRobinson/Patchy/blob/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af/tiny-artboards.af).
The source pin, filenames and SHA-256 digest manifest are the reproducibility
boundary; never fetch a floating branch for CI.
| Area | Corpus files | What the file selection can test |
|---|---|---|
| Artboards and units | `patchy-artboards.af`, `patchy-dpi300.af` | Board identity, rectangles, content association, clipping and conversion from document resolution to points |
| Editable typography | `patchy-text-artistic.af`, `patchy-text-frame.af`, `patchy-text-runs.af`, `patchy-text-rotated.af` | Native text retention, per-run styling, frame geometry and composed transforms |
| Paragraph/character differences | `patchy-text-indent.af`, `patchy-text-para-spacing.af`, `patchy-text-caps.af` | Detect unsupported text layout and case features; a passing parse is insufficient evidence of layout fidelity |
| Curves, shapes and masks | `patchy-vector.af`, `patchy-vector-mask.af`, `patchy-shapes.af`, `patchy-shapes-2.af` | Editable paths, mask attachment and known/fallback parametric shapes |
| Structure and transforms | `patchy-group.af`, `patchy-transform.af` | Nested groups, names, stacking and transform composition |
| Images and pixels | `patchy-embedded-jpeg.af`, `patchy-rgba8.af`, `patchy-rgba16.af`, `patchy-cmyk.af`, `patchy-lab.af` | Original image retention, tiled pixels, supported depths and explicit color-space limitations |
| Effects/adjustments/blends | `patchy-fx.af`, `patchy-fx-blur.af`, `patchy-fx-gradient.af`, `patchy-adjust-curves.af`, `patchy-adjust-hsl.af`, `patchy-live-filter.af`, `patchy-blend-affinity.af` | Warnings and safe fallbacks for unsupported visual operations; not automatic feature support |
| Saved revisions and derived input | `patchy-incremental-chain.af`, `patchy-lazy-placed.af` | Revision selection and bounded handling of a derived placement case |
These are focused feature probes. They complement the larger vector illustrations
but do not replace a large production document with many interacting features.
Fixture filenames alone do not prove the imported model preserved those features;
assert native model structure and imported engine behavior independently.
## PSD compatibility oracle design
Affinity's public [PSD-import guide](https://www.affinity.studio/blog/how-to-open-a-psd-file)
documents import settings that change the result: smart objects can be rasterized
or retained, and text can be imported as text or bitmap. It also describes artboard
mapping and profile conversion. Therefore, a same-looking PSD is not inherently
an equivalent editable document, and an export can lose features before our
reader sees it.
For a future paired oracle, record the original author, license for all embedded
art, Affinity version, platform, import settings, profile, resolution, fonts,
export preset and each expected semantic loss. Keep an original `.af`, a native
Affinity-rendered PNG per board at full resolution, an Affinity-exported PSD and
a human-readable object/layout inventory. Do not run Photoshop or another Adobe
application to generate or validate the comparison. A PSD written by VectorCraft
after import tests our writer/round trip; it is not an independent Affinity oracle.
Compare board dimensions and names, object counts/ordering/visibility, text and
run boundaries, placed-image transforms, mask geometry and transparency, then
render each board with the documented background. Document which PSD objects
are rasterized, approximated or absent. A flat full-document thumbnail can hide
lost boards, editable text or misplaced children. Require native-import success
where native support is claimed; preview fallback must never satisfy that test.
## Typography and complex-document coverage still required
Affinity publicly documents [variable fonts, OpenType features, path text,
artistic/frame text and precision spacing](https://www.affinity.studio/typography-software).
The discovered real-file set does not establish faithful support for all of them.
| Required independent fixture | Evidence needed before claiming support |
|---|---|
| Variable fonts and named instances | Font family plus axes/instance settings preserved; exact pinned font version; non-default weight/width/optical-size rendering |
| OpenType feature combinations | Ligatures, discretionary ligatures, stylistic sets, alternate glyphs, small caps, numeric forms and kerning controls; compare both text content and glyph output |
| Mixed scripts and direction | Arabic joining/RTL, Hebrew, Devanagari conjuncts, Thai combining marks, CJK line breaks, bidi mixed numbers, combining accents and supplementary-plane characters |
| Mixed runs and font fallback | Multiple families, sizes, colors and baseline shifts within one paragraph; missing font and missing glyph outcomes reported without silently changing text |
| Advanced frames and flow | Columns, insets, linked frames, overflow, tabs/indents, paragraph spacing, justified text, wrapping around objects and text on a transformed path |
| Font representations | TrueType, CFF/OpenType, collection faces, variable outlines and color glyph formats; avoid treating family-name retention as outline support |
| Large interacting document | Multiple unequal/overlapping boards, off-board artwork, nested clips/masks, rotations/skews, repeated placed/embedded documents, symbols, images and text at non-72 dpi |
| Pixel/vector interaction | Raster depths/color spaces, blend/opacity combinations, effects, live adjustments, brushes and pressure profiles with explicit warnings for unsupported cases |
Acquire these as original contributor documents with explicit redistribution
rights, or add independently published originals with complete provenance.
Fonts belong in [storytold/craft-fonts](https://github.com/storytold/craft-fonts),
not this repository; a fixture's font names do not grant redistribution rights
to font binaries. Synthetic containers remain useful for parser limits and
precise regression tests, but cannot establish real Affinity saves or rendering
semantics for an unobserved feature.
Tests must distinguish supported behavior, approximated behavior with warnings,
rejected input and unvalidated behavior. Keep the unmet rows above visible when
reporting results: there is no evidence for universal `.af` compatibility.
## Checks added in this change
The pinned corpus contains 51 documents, including 33 current `.af` files with
34 artboards. Native model signatures freeze retained geometry, paints, masks,
images, text runs, fonts, bounds and warnings. Every current board is saved and
reloaded in `.vectorcraft`, then exported through SVG, PDF and PSD. SVG/PDF
dimensions and reimport are checked; a test-only decoder written from the public
PSD specification compares merged pixels and alpha with VectorCraft's PNG output.
These export checks establish internal consistency, not independent Affinity fidelity.
A headless VectorCraft MCP session also opens the real two-board `.af`, saves
and reopens `.vectorcraft` with the complete saved model unchanged, exports both
boards as SVG/PSD, then reopens and exports the two-page PDF again with embedded
editing data disabled, exercising the PDF reader rather than native restoration. The normal
save command adds creation/modification metadata for the new native file.
Saved-thumbnail comparisons cover 36 board crops across 31 documents. Both boards
in the Affinity 3 artboard probe match exactly; the embedded JPEG probe has a mean
difference of 0.50/255. Per-file ceilings preserve measured regression limits;
unsupported text layout and effects are tested structurally and through warnings.
No check reopens VectorCraft's output in Affinity yet, and no `.af` export is
claimed by this change: the independent reopen procedure above needs Affinity on a
supported desktop.
+4 -3
View File
@@ -155,8 +155,9 @@ one with Alt), so one undo step adds and applies it; Shift/Cmd-clicks select swa
Add to Swatches.
`window.swatchLibrary.other {path?}` loads a library file (or another document's swatches) and opens it there;
opening a `.vcswatches`, `.gpl` or `.ase` file with `app.open` does the same. `ui.saveSwatchLibrary {names?}` opens the
`saveSwatchLibrary` dialog (fields `name`, `format`: `vcswatches`/`gpl`/`css`, `user`: save to the user library
folder, `selectedOnly` with `names`); `ui.dialog.confirm` runs `swatch.library.save` (to a file it asks for a path).
`saveSwatchLibrary` dialog (fields `name`, `format`: `vcswatches`/`gpl`/`ase`/`css`, `user`: save to the user library
folder, `selectedOnly` with `names`); `ui.dialog.confirm` runs `swatch.library.save` (to a file it asks for a path
and suggests `name` with the format's extension as the file name; the web downloads the file under that name).
Graphic style libraries open in the same panel: `window.graphicStyleLibrary {library}` (`library_panel: {kind:
"graphicStyles", id}`; `library: null` closes it). Clicking a style there runs `graphicStyle.addFromLibrary {library,
@@ -166,7 +167,7 @@ document's graphic styles) and opens it there; opening a `.vcstyles` file with `
Defined libraries are `window.userGraphicStyleLibrary1`…`10` in Window → Graphic Style Libraries.
`ui.saveGraphicStyleLibrary {names?}` opens the `saveGraphicStyleLibrary` dialog (fields `name`, `user`: save to the
user library folder, `selectedOnly` with `names`); `ui.dialog.confirm` runs `graphicStyle.saveLibrary` (to a file it
asks for a path).
asks for a path and suggests `name` with `.vcstyles` as the file name; the web downloads the file under that name).
Tile Edge Color: Object → Pattern → Tile Edge Color… (`ui.tileEdgeColor`) opens the `tileEdgeColor` dialog (field
`color`: `#rrggbb` or a preset name such as "Light Blue"); `ui.dialog.confirm` sets the preference
+5 -3
View File
@@ -193,10 +193,10 @@ locale such as `ru-RU`, `ru-BY` or `ru-KZ` resolves to it), Ukrainian (`uk`, com
control channel, MCP and tests read them) and are translated only where the status bar draws them
(`i18n::msg`). `@msg` catalog rows hold a whole message or a template such as
`Couldn't open {name}: {e}`; `{_1}`, `{_2}` … stand for the format string's `{}`, and the values in the
placeholders are translated in turn (the reason after `: {e}` is often a message too). Spanish, French, Italian, Russian and Ukrainian cover every
placeholders are translated in turn (the reason after `: {e}` is often a message too). Spanish, French, Italian, Japanese, Russian and Ukrainian cover every
message literal the test scan finds (`complete_languages_translate_every_message`, languages listed in
`COMPLETE_MESSAGES`): a new `Err("…")`, `Other(…)`, `#[error(…)]` or `status(…)` message needs an `es.tsv`,
a `fr.tsv`, an `it.tsv`, a `ru.tsv` and a `uk.tsv` row (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui
a `fr.tsv`, an `it.tsv`, a `ja.tsv`, a `ru.tsv` and a `uk.tsv` row (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui
complete_languages_translate_every_message` lists them all). Other languages show messages in English
until they add `@msg` rows.
- Not translated on purpose: names that are user data (layers, swatches, fonts, documents), the tab
@@ -220,7 +220,9 @@ parameters. Shipped code therefore never panics. Anything that can fail returns
### Enforced by lints
`Cargo.toml` denies these clippy lints for the whole workspace, and `cargo xtask ci` runs clippy with
`-D warnings`:
`-D warnings`. The gate targets the current stable Rust (`rust-version` in `Cargo.toml` is only the
minimum that builds the app, and no toolchain is pinned): when a new stable adds lints, they are fixed
in the code:
| Banned in shipped code | Use instead |
|---|---|
+30 -6
View File
@@ -612,6 +612,23 @@ the one highlighted layer or group row, else the one selected group, else the cu
so art added later is clipped too); called again it releases the mask. It returns `{clip}`, and the Layers panel
underlines clipping-path names.
## Object selection
`select.set {ids}` replaces the selection, `select.add {ids}` adds to it, and
`select.toggle {id}` or `select.toggle {ids}` toggles each target.
Every id must be a non-negative integer naming an existing object.
A malformed or unknown id is an error naming that value; the entire selection is left unchanged.
All three commands return `{count, ids}` for the resulting selection, in selection order.
An empty array clears the selection for `select.set` and leaves it alone for Add and Toggle.
`edit.clear {ids?}` deletes the exact selected objects, including individual compound-path members;
their unselected siblings remain in the compound. Supplying `ids` works without a selection and
overrides selected anchors or guides. Every explicit id is validated before any deletion; a malformed
or unknown id leaves the document unchanged. An empty `ids` array does nothing. Layers themselves
are kept, and selecting an ancestor together with its descendants deletes that subtree once.
Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior.
Cut still removes the objects it copied, including a whole compound when a member is selected.
## Saved selections
Select → Save Selection… keeps the selected objects under a name, in the document: `select.save {name?}` (default
@@ -778,9 +795,12 @@ swatch in the library panel does). `swatch.resetDefaults {replace?}` brings back
{"name":"run_command","arguments":{"command":"swatch.library.get","params":{"library":"earth-tones"}}}
{"name":"run_command","arguments":{"command":"swatch.library.add","params":{"library":"earth-tones","names":["Clay"]}}}
```
`swatch.library.save {path?, format?: "vcswatches"|"gpl"|"css", names?, name?, user?}` writes the document's swatches
as a library (`.vcswatches` keeps colour models, global, spot, gradients and colour groups; `.gpl` is 8-bit RGB;
CSS writes custom properties); without `path` it returns `{data}`, and `user: true` saves into the user library
`swatch.library.save {path?, format?: "vcswatches"|"gpl"|"ase"|"css", names?, name?, user?}` writes the document's
swatches as a library (`.vcswatches` keeps colour models, global, spot, gradients and colour
groups; `.gpl` is 8-bit RGB; a swatch exchange `.ase` file keeps solid colors in their own model
(RGB, CMYK, Lab or Gray) as global, spot or process colors, and color groups, writes a tint swatch
as the color it shows and leaves gradients out; CSS writes custom properties); without `path`
it returns `{data}`, or `{dataBase64}` for `.ase`, and `user: true` saves into the user library
folder of the desktop app (listed as category `user`, User Defined). `swatch.library.load {path? | data? |
dataBase64?, name?}` loads a `.vcswatches`, `.gpl` or swatch exchange (`.ase`) file, or another document's swatches,
as a library to add from. From an `.ase` file it reads RGB, CMYK, Lab and Gray colors as global, spot or process
@@ -1150,7 +1170,8 @@ or pulls handles out in line with the neighbouring anchors (a smooth anchor keep
(Cut Path at Selected Anchor Points) cuts there and answers `{ids}`: a closed path opens at the cut, its two ends
on top of each other, and an open path becomes one path per piece. Each cut leaves one of its two anchors selected,
so `path.moveAnchors {dx, dy}` (or a Direct Selection drag) pulls the path apart there; `path.join {}` (Connect
Selected End Points) joins the ends again. `path.convertAnchor {id, subpath?, anchor, to, x?, y?}` and
Selected End Points) joins the ends again; `path.join {ids: [a, b], ends: ["last", "first"]}` joins the ends asked for
(the Pen's join, #776: drawing on from one open path, a click on another's end makes them one path). `path.convertAnchor {id, subpath?, anchor, to, x?, y?}` and
`path.split {id, subpath?, anchor}` do the same to one anchor (the Anchor Point and Scissors tools); the Pen with Alt
held over a selected path's handle, anchor or segment works as the Anchor Point tool. `path.reshapeSegment {id,
subpath?, segment, t, dx, dy}` (a segment dragged with Direct Selection or the Anchor Point tool) moves the segment's
@@ -2516,9 +2537,12 @@ Type can use the bundled fonts, fonts added to the session and the fonts install
the system's and the user's font folders (Windows: `Fonts` and `%LOCALAPPDATA%\Microsoft\Windows\Fonts`, plus fonts
registered outside them, such as fonts installed as shortcuts, and in the desktop app and `vectorcraft-cli` (MCP
included) the fonts in DirectWrite's system font collection, such as those Adobe Fonts activates while Creative Cloud runs; macOS: `/System/Library/Fonts`, `/Library/Fonts`,
`/Network/Library/Fonts`, `~/Library/Fonts` and downloaded system fonts; Linux and BSD: `/usr/share/fonts`,
`/Network/Library/Fonts`, `~/Library/Fonts` and downloaded system fonts, plus in the desktop app and `vectorcraft-cli`
the fonts CoreText's font manager lists outside them, such as those apps and font managers register from their own
folders; Linux and BSD: `/usr/share/fonts`,
`/usr/local/share/fonts`, `~/.fonts` and the XDG data folders' `fonts`, `~/.local/share/fonts` among them, and in a
Flatpak sandbox the host's fonts). The installed fonts are cataloged once per session (in the background when the app starts, else on the first lookup
Flatpak sandbox the host's fonts). Faces without outlines VectorCraft draws (no `glyf`, `CFF`, `CFF2` or `VARC` table, such
as bitmap-only fonts) are left out. The installed fonts are cataloged once per session (in the background when the app starts, else on the first lookup
by family name), so opening, placing, pasting and importing files find them whatever ran before. `text.fontList`
lists every family available, the installed ones included, as the font menus do: without the system's hidden
families, whose names start with "." (macOS's ".SF NS", ".LastResort"), which still resolve when a document names
+31
View File
@@ -20,3 +20,34 @@ fbb196e918e302c16f8de9f2e6dffaef70ab3c317b32a9f44607fd4b2ead0206 jac21-SimpleLo
9d874245936483de3ec04cca48b383028d33666801dff1814246a44e695e29b8 jac21-SimpleLogoBanner.afdesign
e1b121d7c3d02356baa5dea512f5aa1fe77249c28d7b227e29cab2bc67ec323a eviltwo-AssetStore.aftemplate
ec1072cb03fcd0ed7ac1dfc7e087f4920df545fe9c84a386a7dac2fd33fbbe1f leakcanary-vector_icon.afdesign
9bea4e2ceddc2438943c3b26505299389d07c64bbe2821be01eba9e69a06ce1e patchy-adjust-curves.af
3141df41efeab7a250782e1418d96d4faf3b15107763df8002714aa8a8edd259 patchy-adjust-hsl.af
0361284661e1376b91675cb5f7705b1d560711c9f86aa53e255ee5365e023680 patchy-artboards.af
7239c42b6f9fb25b6ad9c12397afb4e0c1361a505e8126855d3a8cb45b192b87 patchy-blend-affinity.af
4d1fd761dd1508a31d37c4f4acbe01ca0d336ef3cb9bfdcddfc40ad4102f9d74 patchy-cmyk.af
75975eea4c325b90beac5015f6c2731156e90a5ec0f4c0a22aa6324e5dcb4ffc patchy-dpi300.af
bd15ca80e322eb38460176e1b9b187247c3b9e455e55624f71ae5db1122a1eed patchy-embedded-jpeg.af
62c9a5c4cff475a1a47ad6582d24b4fcb56ac84e94641b7ca44c9f8b05053bf1 patchy-fx-blur.af
d515c84a702aee19359740e61f4ff16b02e363533f24287be5e1ba4b3539ef54 patchy-fx-gradient.af
eeb8f0988a7effe2088ead4015916bed13875d9aaa88a3bf477127214831e820 patchy-fx.af
3da524362f70f316c3be4beab2022e2ae7275bbd153cc7204bc328a7dc8a538a patchy-group.af
25ee650339e7951a4db76932e889e0558134bd6b55be7c5b5c7d54b601c053bf patchy-incremental-chain.af
f83c1bd0108315c95f55ddbfb84b7188e73c301dbeb0e3a209ddf991075737b0 patchy-lab.af
da724875124ca2dea2ab69671198c9e0af87f8e325d634c8f6d4256210b00dcc patchy-lazy-placed.af
59da2bb7d58a356e09ca1819020af85bb05217b1b24ec55df9f9f2ff5235c68a patchy-live-filter.af
9e505e5dc5f0854d2a13ae30699b000b32f40b80d80afd570f00a33952ca895e patchy-rgba16.af
9f2a838484399dfc4da4af893facf9d0cd33ed40173aa88264fe8f3756d81a42 patchy-rgba8.af
5dab9c128aa791558ccb8e995e6bf89cc1c50bfcd907dfdce9c764163503e17a patchy-shapes-2.af
dba88c1c2e1c1cca947af6ebc82e32457301b228c8f6a9483edbae7c4ef32653 patchy-shapes.af
f03afbf8965a137439f2fb5d228e2c3349ca81d26e4e7e426b2fcc191348a7f4 patchy-text-artistic.af
66b4fadba91cdf974c1ddef021ce073ecc09b5b25d8c273d400d6c71265b7b75 patchy-text-caps.af
0cf93a1105878ad237e7f3d724be8e85619efd91d2c7fc6ae63b121e0930fc72 patchy-text-frame.af
dfb6ca947e0d33091a7d6d9466f379cc22e3e8847ae7722d8e93bd89a0e8b813 patchy-text-indent.af
56c5d030b9956151110e57fe83aebc47d141efce4df424f6ff5643312c4a7549 patchy-text-para-spacing.af
a5ccb62ee8d7e36d1a19a037aba989a5ba0232767e9f3305f7d9f7d4603291dd patchy-text-rotated.af
07c54ed90e49c4d791964228bee638fbff95a7b06dc3eccbedb3016f9fcef05e patchy-text-runs.af
87e1dee23769932b7e414116233063a8d68726cbffdebb975b3cd0ef447c602a patchy-transform.af
fa5dd80f44ae0712a9888c62953fd442a28119034d343db93b7892d5d2a61328 patchy-vector-mask.af
8ab1995ecbd9306ebcb7a4d2cd81701f34401e67f08b242f14dc3e3d04c94803 patchy-vector.af
bbc50c8c376e0e5980939be7df6769feed1a30289c7efc6391b204dfb15de88d patchy-LICENSE.txt
150e423be0c5eb22f252a38c2de68ab3ccec7e20bfba166f7ddd622ac243d8f4 patchy-NOTICE.txt
+44 -3
View File
@@ -3,8 +3,9 @@
//! They land in `corpus/affinity/` (gitignored, never committed). `vectorcraft-affinity`'s
//! `real_files` test and the engine's `affinity_corpus` test use them when present.
//!
//! Only permissively licensed files (CC0, MIT, Apache-2.0) whose metadata holds no personal paths
//! are listed. Moving a pin: change the commit, re-run, review the manifest diff.
//! Only permissively licensed files (CC0, MIT, Apache-2.0) are listed. Fixture provenance and
//! exclusions are documented in docs/affinity-validation.md. Moving a pin: change the commit,
//! re-run, review the manifest diff. Metadata is never imported or published by the app.
use std::path::Path;
use std::process::Command;
@@ -15,6 +16,44 @@ use crate::{root, run, sha256};
type Source = (&'static str, &'static str, &'static str, &'static [(&'static str, &'static str)]);
const SOURCES: &[Source] = &[
(
"SethRobinson/Patchy",
"de84eab550758b30fa062e479f5778cce7693b73",
"MIT",
&[
("LICENSE", "patchy-LICENSE.txt"),
("NOTICE-THIRD-PARTY.md", "patchy-NOTICE.txt"),
("test-fixtures/af/tiny-adjust-curves.af", "patchy-adjust-curves.af"),
("test-fixtures/af/tiny-adjust-hsl.af", "patchy-adjust-hsl.af"),
("test-fixtures/af/tiny-artboards.af", "patchy-artboards.af"),
("test-fixtures/af/tiny-blend-affinity.af", "patchy-blend-affinity.af"),
("test-fixtures/af/tiny-cmyk.af", "patchy-cmyk.af"),
("test-fixtures/af/tiny-dpi300.af", "patchy-dpi300.af"),
("test-fixtures/af/tiny-embedded-jpeg.af", "patchy-embedded-jpeg.af"),
("test-fixtures/af/tiny-fx-blur.af", "patchy-fx-blur.af"),
("test-fixtures/af/tiny-fx-gradient.af", "patchy-fx-gradient.af"),
("test-fixtures/af/tiny-fx.af", "patchy-fx.af"),
("test-fixtures/af/tiny-group.af", "patchy-group.af"),
("test-fixtures/af/tiny-incremental-chain.af", "patchy-incremental-chain.af"),
("test-fixtures/af/tiny-lab.af", "patchy-lab.af"),
("test-fixtures/af/tiny-lazy-placed.af", "patchy-lazy-placed.af"),
("test-fixtures/af/tiny-live-filter.af", "patchy-live-filter.af"),
("test-fixtures/af/tiny-rgba16.af", "patchy-rgba16.af"),
("test-fixtures/af/tiny-rgba8.af", "patchy-rgba8.af"),
("test-fixtures/af/tiny-shapes-2.af", "patchy-shapes-2.af"),
("test-fixtures/af/tiny-shapes.af", "patchy-shapes.af"),
("test-fixtures/af/tiny-text-artistic.af", "patchy-text-artistic.af"),
("test-fixtures/af/tiny-text-caps.af", "patchy-text-caps.af"),
("test-fixtures/af/tiny-text-frame.af", "patchy-text-frame.af"),
("test-fixtures/af/tiny-text-indent.af", "patchy-text-indent.af"),
("test-fixtures/af/tiny-text-para-spacing.af", "patchy-text-para-spacing.af"),
("test-fixtures/af/tiny-text-rotated.af", "patchy-text-rotated.af"),
("test-fixtures/af/tiny-text-runs.af", "patchy-text-runs.af"),
("test-fixtures/af/tiny-transform.af", "patchy-transform.af"),
("test-fixtures/af/tiny-vector-mask.af", "patchy-vector-mask.af"),
("test-fixtures/af/tiny-vector.af", "patchy-vector.af"),
],
),
(
"samuel-etver/vector-art",
"255f8add3c8f0740196e22bd59502b811b532f0b",
@@ -97,7 +136,9 @@ pub fn fetch() -> Result<(), String> {
}
}
sources.push_str(&format!("| {name} | https://github.com/{repo}/blob/{commit}/{path} | {licence} |\n"));
count += 1;
if out.extension().is_some_and(|e| e != "txt") {
count += 1;
}
}
}
std::fs::write(dest.join("SOURCES.md"), sources).map_err(|e| format!("SOURCES.md: {e}"))?;
+3 -3
View File
@@ -19,10 +19,10 @@ pub fn hex(data: &[u8]) -> String {
msg.push(0);
}
msg.extend(bits.to_be_bytes());
for block in msg.chunks_exact(64) {
for block in msg.as_chunks::<64>().0.iter() {
let mut w = [0u32; 64];
for (i, word) in block.chunks_exact(4).enumerate() {
w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
for (i, word) in block.as_chunks::<4>().0.iter().enumerate() {
w[i] = u32::from_be_bytes(*word);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);