diff --git a/Cargo.lock b/Cargo.lock index 65cc426291..9acedd45bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,6 +1009,15 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" @@ -6741,6 +6750,7 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ + "craft-cms", "kurbo 0.13.1", "moxcms", "proptest", diff --git a/Cargo.toml b/Cargo.toml index fea9cdda55..d60edf2af7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index a007ede39f..1273b5d0ad 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,6 +9,7 @@ description = "VectorCraft color" workspace = true [dependencies] +craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 9be00b4b21..c14075bd2e 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -6,6 +6,8 @@ use std::collections::{HashMap, HashSet}; +pub use craft_cms::palette::css_property; +use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteError, PaletteGroup, PaletteSwatch}; use serde::{Deserialize, Serialize}; use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary}; @@ -83,18 +85,93 @@ struct NativeFile { const NATIVE_FORMAT: &str = "vcswatches"; const GPL_HEADER: &str = "GIMP Palette"; -const GPL_GROUP: &str = "# Group:"; const ASE_SIGNATURE: &[u8] = b"ASEF"; -const ASE_GROUP_START: u16 = 0xC001; -const ASE_GROUP_END: u16 = 0xC002; -const ASE_COLOR: u16 = 0x0001; -/// The most colors and groups read from one `.ase` file. -const ASE_MAX_ENTRIES: usize = 100_000; -/// The most UTF-16 code units of a name that are kept. -const ASE_MAX_NAME: usize = 1024; -const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short"; const ACB_SIGNATURE: &[u8] = b"8BCB"; -const ACB_CUT_SHORT: &str = "the color book is cut short"; +#[cfg(test)] +const ASE_GROUP_START: u16 = 0xC001; +#[cfg(test)] +const ASE_MAX_ENTRIES: usize = 100_000; + +fn color_to_cms(c: Color) -> PaletteColor { + match c { + Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b }, + Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k }, + Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b }, + Color::Gray { k } => PaletteColor::Gray { k }, + } +} + +fn color_from_cms(c: PaletteColor) -> Color { + match c { + PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b), + PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k), + PaletteColor::Lab { l, a, b } => Color::lab(l, a, b), + PaletteColor::Gray { k } => Color::gray(k), + } +} + +// GPL must retain the app-managed display conversion; ASE preserves authoring models. +fn swatches_to_cms(list: &[Swatch], rgb_only: bool) -> Vec { + list.iter() + .filter_map(|w| { + w.paint.color().map(|c| PaletteSwatch { + name: w.name.clone(), + color: if rgb_only { + let [r, g, b, _] = c.to_rgba8(1.0); + PaletteColor::rgb8(r, g, b) + } else { + color_to_cms(c) + }, + global: w.global, + spot: w.spot, + }) + }) + .collect() +} + +fn swatches_from_cms(list: Vec) -> Vec { + list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() +} + +fn to_cms_palette(lib: &SwatchLibrary, rgb_only: bool) -> Palette { + Palette { + name: lib.name.clone(), + swatches: swatches_to_cms(&lib.swatches, rgb_only), + groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches, rgb_only) }).collect(), + } +} + +fn from_cms_palette(p: Palette) -> SwatchLibrary { + SwatchLibrary { + name: p.name, + swatches: swatches_from_cms(p.swatches), + groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(), + } +} + +/// Maps structured shared palette errors to VectorCraft's translatable messages. +fn palette_error(err: PaletteError) -> String { + match err { + PaletteError::UnsupportedFormat => "not a supported palette (.gpl, .ase, or .acb)".into(), + PaletteError::TruncatedAse => "the swatch exchange file is cut short".into(), + PaletteError::TruncatedAcb => "the color book is cut short".into(), + PaletteError::AseWriteEntryLimit { limit, entries } => format!( + "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}", + ASE_MAX_ENTRIES = limit + ), + PaletteError::AseReadEntryLimit { limit } => { + format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups", ASE_MAX_ENTRIES = limit) + } + PaletteError::AseBlockCount => "too many swatch exchange blocks".into(), + PaletteError::AseBlockLength => "a swatch exchange block is too long".into(), + PaletteError::AseNameLength => "a swatch exchange name is too long".into(), + PaletteError::AseVersion { major, minor } => format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"), + PaletteError::AcbVersion { version } => format!("color book version {version} isn't supported (only 1)"), + PaletteError::AcbEntryLimit { limit } => format!("the color book holds more than {ASE_MAX_ENTRIES} colors", ASE_MAX_ENTRIES = limit), + PaletteError::AcbColorSpace { space: other } => format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)"), + PaletteError::AcbNameBytes { limit } => format!("the color book's names take more than {} MB", limit >> 20), + } +} /// 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 @@ -113,8 +190,12 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library }; serde_json::to_string_pretty(&file).unwrap_or_default() } - PaletteFormat::Gpl => write_gpl(lib), - PaletteFormat::Ase => return write_ase(lib), + PaletteFormat::Gpl => { + return cms_palette::write_palette_typed(&to_cms_palette(lib, true), cms_palette::PaletteFormat::Gpl).map_err(palette_error); + } + PaletteFormat::Ase => { + return cms_palette::write_palette_typed(&to_cms_palette(lib, false), cms_palette::PaletteFormat::Ase).map_err(palette_error); + } PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) @@ -125,49 +206,6 @@ fn one_line(s: &str) -> String { s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() } -fn write_gpl(lib: &SwatchLibrary) -> String { - let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name)); - let colors = |out: &mut String, list: &[Swatch]| { - for w in list { - if let Some(c) = w.paint.color() { - let [r, g, b, _] = c.to_rgba8(1.0); - out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name))); - } - } - }; - colors(&mut out, &lib.swatches); - for g in &lib.groups { - out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name))); - colors(&mut out, &g.swatches); - } - out -} - -/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as -/// hyphens, other characters an identifier can't hold escaped with a backslash. -pub fn css_property(name: &str) -> String { - let mut out = String::from("--"); - for word in name.split_whitespace() { - if out.len() > 2 { - out.push('-'); - } - for ch in word.chars().flat_map(char::to_lowercase) { - if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() { - out.push(ch); - } else if ch.is_ascii_graphic() { - out.push('\\'); - out.push(ch); - } else { - out.push_str(&format!("\\{:x} ", ch as u32)); - } - } - } - if out.len() == 2 { - out.push_str("swatch"); - } - out -} - /// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity). fn css_color(c: &Color, opacity: f32) -> String { let [r, g, b, a] = c.to_rgba8(opacity); @@ -265,108 +303,12 @@ 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, 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::(); - 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, list: &[Swatch]) -> Result { - 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) = 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, 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, name: &str) -> Result<(), String> { - let mut units: Vec = 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 { let text = text.trim_start_matches('\u{feff}').trim_start(); if text.starts_with(GPL_HEADER) { - return Ok(read_gpl(text, name)); + return cms_palette::read_palette_typed(text.as_bytes(), name).map(from_cms_palette).map_err(palette_error); } if text.starts_with('{') { let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?; @@ -391,11 +333,8 @@ pub fn sniff(text: &str) -> bool { /// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or /// `.gpl` library ([`read`]). `name` names it when the file doesn't. pub fn read_bytes(bytes: &[u8], name: &str) -> Result { - if bytes.starts_with(ASE_SIGNATURE) { - return read_ase(bytes, name); - } - if bytes.starts_with(ACB_SIGNATURE) { - return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e }); + if bytes.starts_with(ASE_SIGNATURE) || bytes.starts_with(ACB_SIGNATURE) { + return cms_palette::read_palette_typed(bytes, name).map(from_cms_palette).map_err(palette_error); } read(&String::from_utf8_lossy(bytes), name) } @@ -409,303 +348,5 @@ pub fn sniff_bytes(bytes: &[u8]) -> bool { || sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes))) } -/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and -/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are -/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets -/// a number ([`UniqueNames`]). -fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary { - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - for line in text.lines().skip(1) { - let line = line.trim(); - if let Some(g) = line.strip_prefix(GPL_GROUP) { - lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] }); - continue; - } - if let Some(n) = line.strip_prefix("Name:") { - if !n.trim().is_empty() { - lib.name = n.trim().to_string(); - } - continue; - } - // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped. - let words: Vec<&str> = line.split_whitespace().collect(); - let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect(); - let [r, g, b] = rgb[..] else { continue }; - let rest = words[3..].join(" "); - let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest }; - let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false }; - match lib.groups.last_mut() { - Some(grp) => grp.swatches.push(w), - None => lib.swatches.push(w), - } - } - lib -} - -/// `.ase`, from public descriptions of the format: the layout from -/// , the component ranges from -/// . After the signature come, big-endian, a `u16` major (1) and -/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and -/// the body. A group start's body is a name. A color's body is a name, a four-character model -/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16` -/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a -/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness -/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero -/// included, then the units. -/// -/// Color groups become groups: a group start inside an open group ends that group, and a group -/// left open ends with the file. Blocks of other types and colors in other models are skipped. -/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or -/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than -/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn read_ase(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ASE_SIGNATURE.len())?; - let (major, minor) = (data.u16()?, data.u16()?); - if major != 1 { - return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)")); - } - let blocks = data.u32()?; - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - let (mut in_group, mut entries) = (false, 0usize); - for _ in 0..blocks { - let kind = data.u16()?; - let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX); - let mut body = AseData(data.bytes(len)?); - if matches!(kind, ASE_GROUP_START | ASE_COLOR) { - entries += 1; - if entries > ASE_MAX_ENTRIES { - return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups")); - } - } - match kind { - ASE_GROUP_START => { - lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] }); - in_group = true; - } - ASE_GROUP_END => in_group = false, - ASE_COLOR => { - let Some(mut w) = ase_swatch(&mut body)? else { continue }; - w.name = names.unique(std::mem::take(&mut w.name)); - match lib.groups.last_mut().filter(|_| in_group) { - Some(g) => g.swatches.push(w), - None => lib.swatches.push(w), - } - } - // Other blocks are skipped. - _ => {} - } - } - Ok(lib) -} - -/// `.acb` (a color book, read only), from public descriptions of the format: after the signature -/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description -/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0 -/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its -/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab -/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of -/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand -/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot -/// or process colors (a book without it is a spot color book). -/// -/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a -/// name (the padding of a book's pages) are left out. A version other than 1, a color space other -/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error. -fn read_acb(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ACB_SIGNATURE.len())?; - let version = data.u16()?; - if version != 1 { - return Err(format!("color book version {version} isn't supported (only 1)")); - } - let _book_id = data.u16()?; - let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; - let count = usize::from(data.u16()?); - if count > ASE_MAX_ENTRIES { - return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors")); - } - let (_page_size, _page_offset) = (data.u16()?, data.u16()?); - let space = data.u16()?; - let mut colors = Vec::with_capacity(count); - for _ in 0..count { - let name = data.acb_string()?; - let _code = data.bytes(6)?; - let color = match space { - 0 => { - let [r, g, b] = data.array::<3>()?; - Color::rgb8(r, g, b) - } - 2 => { - let ink = |v: u8| f32::from(255 - v) / 255.0; - let [c, m, y, k] = data.array::<4>()?; - Color::cmyk(ink(c), ink(m), ink(y), ink(k)) - } - 7 => { - let [l, a, b] = data.array::<3>()?; - Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) - } - other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")), - }; - colors.push((name, color)); - } - // Spot colors unless the book says process ones. - let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); - let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; - let mut names = UniqueNames::default(); - // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of - // names taken): a megabyte book of long affixes and many colors came to hundreds of MB. - let mut kept = 0usize; - for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { - kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); - if kept > ACB_MAX_NAME_BYTES { - return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); - } - let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); - lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot }); - } - Ok(lib) -} - -/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted -/// twice as they are kept twice. -const ACB_MAX_NAME_BYTES: usize = 64 << 20; - -/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray. -/// Components are clamped to their ranges. -fn ase_swatch(body: &mut AseData) -> Result, String> { - let name = body.name()?; - let unit = |v: f32| v.clamp(0.0, 1.0); - let color = match &body.array::<4>()? { - b"RGB " => { - let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?]; - Color::rgb(unit(r), unit(g), unit(b)) - } - b"CMYK" => { - let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?]; - Color::cmyk(unit(c), unit(m), unit(y), unit(k)) - } - // Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a - // value above 1. - b"LAB " => { - let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?]; - let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 }; - Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0)) - } - // A gray level (1 is white); a gray color holds its ink. - b"Gray" => Color::gray(1.0 - unit(body.f32()?)), - _ => return Ok(None), - }; - // Some writers leave the color type out, which makes a process color. - let kind = if body.0.len() >= 2 { body.u16()? } else { 2 }; - // Spot colors are global. - let (global, spot) = match kind { - 0 => (true, false), - 1 => (true, true), - _ => (false, false), - }; - let name = if name.is_empty() { value_name(color) } else { name }; - Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot })) -} - -/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0", -/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30"). -fn value_name(c: Color) -> String { - let pct = |v: f32| (v * 100.0).round(); - let byte = |v: f32| (v * 255.0).round(); - match c { - Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), - Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), - Color::Gray { k } => format!("Gray K={}", pct(k)), - // `+ 0.0` turns a rounded -0 into 0. - Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0), - } -} - -/// `.ase` data, read field by field; reading past its end is an error. -struct AseData<'a>(&'a [u8]); - -impl<'a> AseData<'a> { - fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { - let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(head) - } - fn array(&mut self) -> Result<[u8; N], String> { - let (head, rest) = self.0.split_first_chunk::().ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(*head) - } - fn u16(&mut self) -> Result { - self.array().map(u16::from_be_bytes) - } - fn u32(&mut self) -> Result { - self.array().map(u32::from_be_bytes) - } - /// A component; one that isn't a finite number reads as 0. - fn f32(&mut self) -> Result { - let v = f32::from_be_bytes(self.array()?); - Ok(if v.is_finite() { v } else { 0.0 }) - } - /// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units, - /// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units - /// are kept. - fn acb_string(&mut self) -> Result { - let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); - let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - let s = String::from_utf16_lossy(&units); - let s = match s.strip_prefix("$$$/") { - Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(), - None => s, - }; - Ok(s.replace("^R", "®").replace("^C", "©")) - } - /// A name up to its terminating zero, trimmed. A block that ends before it has no name. - fn name(&mut self) -> Result { - if self.0.is_empty() { - return Ok(String::new()); - } - let n = usize::from(self.u16()?); - let (units, _) = self.bytes(n * 2)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - Ok(String::from_utf16_lossy(&units).trim().to_string()) - } -} - -/// A group's name as a file gives it, trimmed; "Color Group" when it has none. -fn group_name(name: &str) -> String { - let name = name.trim(); - if name.is_empty() { "Color Group".into() } else { name.to_string() } -} - -/// The swatch and group names a reader has handed out. Swatches and color groups share one set of -/// names, as in a document, and a name already taken gets the first free number ("Black 2"). -#[derive(Default)] -struct UniqueNames { - taken: HashSet, - /// The last number tried for each repeated name. - last: HashMap, -} - -impl UniqueNames { - fn unique(&mut self, base: String) -> String { - if self.taken.insert(base.clone()) { - return base; - } - // Each pass tries the next number, and only finitely many names are taken. - let n = self.last.entry(base.clone()).or_insert(1); - loop { - *n += 1; - let name = format!("{base} {n}"); - if self.taken.insert(name.clone()) { - return name; - } - } - } -} - #[cfg(test)] mod tests; diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index bbbae16a53..b0036b6fc6 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,6 +2,9 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; +const ASE_COLOR: u16 = 0x0001; +const ASE_GROUP_END: u16 = 0xC002; + #[test] fn gpl_blank_name_keeps_fallback() { let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n"; @@ -700,3 +703,52 @@ proptest! { } } } + +#[test] +fn shared_gpl_adapter_uses_app_color_conversion() { + let colors = [Color::cmyk(0.2, 0.4, 0.6, 0.1), Color::lab(55.0, 30.0, -25.0), Color::gray(0.3)]; + let lib = SwatchLibrary { + name: "Managed".into(), + swatches: colors + .iter() + .enumerate() + .map(|(i, &color)| Swatch { name: format!("Color {i}"), paint: Paint::solid(color), global: false, spot: false }) + .collect(), + groups: vec![], + }; + let mut expected = String::from("GIMP Palette\nName: Managed\nColumns: 0\n#\n"); + for (i, color) in colors.iter().enumerate() { + let [r, g, b, _] = color.to_rgba8(1.0); + expected.push_str(&format!("{r:3} {g:3} {b:3}\tColor {i}\n")); + } + assert_eq!(write(&lib, PaletteFormat::Gpl).unwrap(), expected.as_bytes()); + assert!(to_cms_palette(&lib, true).swatches.iter().all(|w| matches!(w.color, PaletteColor::Rgb { .. }))); + assert!(matches!(to_cms_palette(&lib, false).swatches[0].color, PaletteColor::Cmyk { .. })); + assert!(matches!(to_cms_palette(&lib, false).swatches[1].color, PaletteColor::Lab { .. })); +} + +#[test] +fn typed_palette_errors_keep_app_wording() { + let cases = [ + (PaletteError::UnsupportedFormat, "not a supported palette (.gpl, .ase, or .acb)"), + (PaletteError::TruncatedAse, "the swatch exchange file is cut short"), + (PaletteError::TruncatedAcb, "the color book is cut short"), + ( + PaletteError::AseWriteEntryLimit { limit: 3, entries: 4 }, + "VectorCraft reads at most 3 colors and groups from a swatch exchange file, and this library has 4", + ), + (PaletteError::AseReadEntryLimit { limit: 3 }, "the swatch exchange file holds more than 3 colors and groups"), + (PaletteError::AseBlockCount, "too many swatch exchange blocks"), + (PaletteError::AseBlockLength, "a swatch exchange block is too long"), + (PaletteError::AseNameLength, "a swatch exchange name is too long"), + (PaletteError::AseVersion { major: 2, minor: 3 }, "swatch exchange version 2.3 isn't supported (only 1.x)"), + (PaletteError::AcbVersion { version: 2 }, "color book version 2 isn't supported (only 1)"), + (PaletteError::AcbEntryLimit { limit: 3 }, "the color book holds more than 3 colors"), + (PaletteError::AcbColorSpace { space: 5 }, "color books in color space 5 aren't supported (only RGB, CMYK and Lab)"), + (PaletteError::AcbNameBytes { limit: 64 << 20 }, "the color book's names take more than 64 MB"), + ]; + for (error, expected) in cases { + assert_eq!(palette_error(error), expected); + } + assert_eq!(read_bytes(b"8BCB\0\x01\0\0\0\0\0\x03\0x", "fallback").unwrap_err(), "the color book is cut short"); +} diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index c6a9860189..107ac1dab9 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -38,7 +38,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; +pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 63b763423d..1a3229138e 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -669,6 +669,34 @@ fn area_type() -> TextObject { t } +#[test] +fn a_wrap_object_below_every_area_type_object_makes_no_outline() { + use crate::{Appearance, Document, Node, NodeKind}; + let mut d = Document::new(300.0, 300.0); + let l = d.layers[0].id; + let wrap = |d: &mut Document, r: Rect| { + let id = d.alloc_id(); + let mut n = Node::path(id, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art()); + n.extras_mut().wrap = Some(TextWrap::default()); + n + }; + // Bottom to top: a wrap object, the area type, then a wrap object. + let below = wrap(&mut d, Rect::new(0.0, 0.0, 250.0, 250.0)); + d.insert(Some(l), 9, below).unwrap(); + let id = d.alloc_id(); + d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(area_type())))).unwrap(); + let above = wrap(&mut d, Rect::new(60.0, 40.0, 80.0, 60.0)); + d.insert(Some(l), 9, above).unwrap(); + wrap::OUTLINES_MADE.with(|c| c.set(0)); + let mut sources = 0; + wrap_sources(&d, |_, objects, shapes| { + sources += 1; + assert_eq!((objects.len(), shapes.len()), (1, 1)); + }); + assert_eq!(sources, 1); + assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined"); +} + #[test] fn area_resizes_its_frame_and_keeps_its_type() { let mut t = area_type(); diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 15a0fbbd40..33fdcb4687 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -7,6 +7,12 @@ use vectorcraft_geom::{PathData, shapes}; use super::{TextKind, TextObject, WrapShape}; use crate::{Document, Node, NodeId, NodeKind}; +#[cfg(test)] +thread_local! { + /// How many wrap outlines [`each_text`] has made on this thread (for tests). + pub(super) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. fn outline(n: &Node, out: &mut PathData) { match &n.kind { @@ -66,10 +72,45 @@ fn collect<'a>(n: &'a Node, out: &mut Vec>) { } } +/// The anchors and subpaths [`outline`] would collect for wrap object `n`, counted without copying +/// them. +fn outline_size(n: &Node) -> (usize, usize) { + match &n.kind { + NodeKind::Path { path, guide: false, .. } => path + .subpaths + .iter() + .filter(|sp| sp.closed || sp.anchors.len() > 2) + .fold((0usize, 0usize), |(a, s), sp| (a.saturating_add(sp.anchors.len()), s.saturating_add(1))), + NodeKind::Compound { children, .. } | NodeKind::Group { children, clip: false } => children + .iter() + .filter(|c| c.visible) + .map(|c| outline_size(c)) + .fold((0, 0), |(a, s), (ca, cs)| (a.saturating_add(ca), s.saturating_add(cs))), + NodeKind::Group { children, clip: true } => children.first().map_or((0, 0), |c| outline_size(c)), + // A rectangle of the object's bounds. + _ => { + if n.geometric_bounds().is_some() { + (4, 1) + } else { + (0, 0) + } + } + } +} + /// How much [`resolve_wrap`] would copy into the wrap shapes of every area text object in `doc`: /// each wrap object's outline (its anchors, plus one for the shape) once for each area text object /// below it in its layer. pub fn wrap_work(doc: &Document) -> usize { + work(doc, false) +} + +/// [`wrap_work`], with one more for each subpath of each outline, empty ones included. +pub fn wrap_copy_units(doc: &Document) -> usize { + work(doc, true) +} + +fn work(doc: &Document, count_subpaths: bool) -> usize { let mut total = 0usize; for layer in &doc.layers { let mut items = vec![]; @@ -78,11 +119,10 @@ pub fn wrap_work(doc: &Document) -> usize { for it in items.iter().rev() { match it { Item::Wrap(n) => { - let mut pd = PathData::default(); - outline(n, &mut pd); - if !pd.is_empty() { - let anchors: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); - above = above.saturating_add(anchors.saturating_add(1)); + let (anchors, subpaths) = outline_size(n); + if anchors > 0 { + let subpaths = if count_subpaths { subpaths } else { 0 }; + above = above.saturating_add(anchors).saturating_add(subpaths).saturating_add(1); } } Item::Text(_) => total = total.saturating_add(above), @@ -99,9 +139,15 @@ fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapS let mut items = vec![]; collect(layer, &mut items); let mut above: Vec<(&Node, WrapShape)> = vec![]; - for it in items.iter().rev() { + // A wrap object below every area text object of the layer wraps none of them: its outline is + // not made. + let first_text = items.iter().position(|it| matches!(it, Item::Text(_))); + for (i, it) in items.iter().enumerate().rev() { match it { + Item::Wrap(_) if first_text.is_none_or(|t| i < t) => {} Item::Wrap(n) => { + #[cfg(test)] + OUTLINES_MADE.with(|c| c.set(c.get() + 1)); let mut pd = PathData::default(); outline(n, &mut pd); if !pd.is_empty() { diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index bef56dfd94..fc5bbe120a 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -188,6 +188,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows }, BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush }, BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic }, + BuiltinBrushLibrary { id: "vector-packs", name: "Vector Packs", make: vector_packs }, ]; /// Built-in library `id`, made once. @@ -866,6 +867,38 @@ fn scatter_shapes() -> BrushLibrary { built("Scatter Shapes", doc, brushes) } +/// Vector Packs: four original, editable vector marks that follow the stroke color. +fn vector_packs() -> BrushLibrary { + let compass = group(vec![black(shapes::star(Point::ZERO, 10.0, 3.0, 8, 0.0)), black(shapes::ellipse(Rect::new(-1.5, -1.5, 1.5, 1.5)))]); + let sprig = group(vec![ + black(polygon(&[(-0.7, 10.0), (0.7, 10.0), (0.7, -10.0), (-0.7, -10.0)])), + black(polygon(&[(0.0, 5.0), (5.0, 2.0), (7.0, -1.0), (3.0, 0.0)])), + black(polygon(&[(0.0, 0.0), (-5.0, -3.0), (-7.0, -6.0), (-3.0, -5.0)])), + black(polygon(&[(0.0, -5.0), (5.0, -8.0), (7.0, -10.0), (3.0, -9.0)])), + ]); + let diamond = group(vec![ + black(polygon(&[(-9.0, 0.0), (-1.0, -9.0), (-1.0, -1.0)])), + black(polygon(&[(1.0, -9.0), (9.0, 0.0), (1.0, -1.0)])), + black(polygon(&[(9.0, 0.0), (1.0, 9.0), (1.0, 1.0)])), + black(polygon(&[(-1.0, 9.0), (-9.0, 0.0), (-1.0, 1.0)])), + ]); + let tide = group(vec![ + black(band(20.0, 1.2, 32, |x| -3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())), + black(band(20.0, 1.2, 32, |x| 3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())), + ]); + let settings = Scatter { size: (90.0, 110.0), spacing: (130.0, 160.0), colorization: Colorization::Tints, ..Default::default() }; + built( + "Vector Packs", + Document::new(100.0, 100.0), + vec![ + scatter("Compass Rose", compass, settings.clone()), + scatter("Botanical Sprig", sprig, settings.clone()), + scatter("Facet Diamond", diamond, settings.clone()), + scatter("Tide Crest", tide, settings), + ], + ) +} + /// Stipple: original dot-based scatter brushes for fine and broad shading along a path. fn stipple() -> BrushLibrary { let dot = |x: f64, y: f64, r: f64, opacity: f32| { diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index e9cee68e01..605ddd08ec 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -11,8 +11,9 @@ //! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched //! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object //! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced -//! apart takes that spacing as its tracking ([`Line::tracked`]). Shapes that match no font stay as -//! they are and are reported. +//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading +//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). Shapes +//! that match no font stay as they are and are reported. //! //! With a `tolerance`, a shape that matches no glyph exactly may still nearly match one: another //! version of the font, or the outline simplified or built another way @@ -47,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a contour narrower than three times the outline tolerance, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, tracking (1/1000 em), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a contour narrower than three times the outline tolerance, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -395,18 +396,15 @@ impl Line { /// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, /// more space than whole spaces make); `None` when the type draws every glyph in its place. fn first_mismatch(&self, t: &TextObject) -> Option { - let lay = vectorcraft_text::layout(FontDb::global(), t); - let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); - for (k, m) in self.matches.iter().enumerate() { - let Some(g) = drawn.next() else { return Some(k) }; - let tol = (self.scale * self.face.units_per_em() * (0.01 + self.slack_for(m))).max(0.01); - let at = t.xf * (g.xf * Point::ORIGIN); - if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { - return Some(k); - } - } - // Ink the outlines did not have: the last glyph is where it went wrong. - drawn.next().map(|_| self.matches.len().saturating_sub(1)) + first_mismatch(t, &self.matches, self.size(), self.slack) + } + + /// Along the line, where its first glyph starts and its last glyph's advance ends, from + /// `from` (the tracking after the last glyph left out). + fn span_from(&self, from: Point) -> (f64, f64) { + let dir = self.dir(); + let last = self.matches.last().map_or(self.end, |m| m.origin + dir * (m.face.advance(m.gid) * m.scale)); + ((self.origin - from).dot(dir), (last - from).dot(dir)) } /// This line with the tracking its glyphs are spaced by, when it has at least three glyphs. @@ -623,6 +621,27 @@ fn round_tracking(t: f64) -> f64 { if (t - t.round()).abs() < 0.05 { t.round() } else { t } } +/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another +/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, +/// more space than whole spaces make); `None` when the type draws every glyph in its place. +fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) -> Option { + let lay = vectorcraft_text::layout(FontDb::global(), t); + let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); + // With a tolerance, a near-matched glyph, or any glyph of a line whose first glyph is one, + // may sit that much further (as a fraction of the size) from where the type draws it. + let first_exact = matches.first().is_none_or(|f| f.exact); + for (k, m) in matches.iter().enumerate() { + let Some(g) = drawn.next() else { return Some(k) }; + let tol = (size * (0.01 + if m.exact && first_exact { 0.0 } else { slack })).max(0.01); + let at = t.xf * (g.xf * Point::ORIGIN); + if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { + return Some(k); + } + } + // Ink the outlines did not have: the last glyph is where it went wrong. + drawn.next().map(|_| matches.len().saturating_sub(1)) +} + /// `lines` checked against their own layout: a line splits where its type stops drawing the /// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). /// The glyphs laid out are bounded by a multiple of the number of glyphs. @@ -715,6 +734,294 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) out } +/// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes +/// of the area type on the layers Retype changes +/// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type. +const MAX_WRAP_WORK: usize = 2_000_000; + +#[cfg(not(test))] +fn max_wrap_work() -> usize { + MAX_WRAP_WORK +} + +#[cfg(test)] +thread_local! { + /// [`MAX_WRAP_WORK`], lowered by tests on their own thread. + static WRAP_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_WRAP_WORK) }; +} + +#[cfg(test)] +fn max_wrap_work() -> usize { + WRAP_LIMIT.with(|c| c.get()) +} + +/// Lines farther apart than this many times their size do not join into one object. +const MAX_LEADING: f64 = 3.0; + +/// What Retype makes: one type object and the shapes it replaces. +struct Made { + t: TextObject, + /// For area type, the point type that also draws the glyphs in place: the type kept when + /// Text Wrap objects above it change the area type's layout. + point: Option, + /// The glyphs the type must draw, in order. + matches: Vec, + pieces: Vec, + text: String, + face: Arc, + size: f64, + /// The tolerance near matches were taken with ([`Line::slack`]). + slack: f64, + tracking: f64, + /// The leading set on the type: None for Auto or a single line. + leading: Option, + opacity: f32, + blend: vectorcraft_color::BlendMode, +} + +impl Made { + fn line(l: &Line, system_layout: bool) -> Made { + Made { + t: l.text_object(system_layout), + point: None, + matches: l.matches.clone(), + pieces: l.pieces.clone(), + text: l.text.clone(), + face: l.face.clone(), + size: l.size(), + slack: l.slack, + tracking: l.tracking, + leading: None, + opacity: l.opacity, + blend: l.blend, + } + } +} + +/// The alignments lines can share, in the order one is chosen: their starts, their ends, their +/// centers. +const ALIGNS: [vectorcraft_doc::Justify; 3] = [vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Right, vectorcraft_doc::Justify::Center]; + +/// A run of lines that may become one object: lines after the first, each one leading further +/// across, in the same group, paint, transparency, font, size, turn and tracking, lined up alike. +struct Block { + lines: Vec, + /// The mean distance between baselines, from the first line's to the last line's. + leading: f64, + /// Which of [`ALIGNS`] every line so far shares. + aligns: [bool; 3], + /// The tracking of the first line that has one ([`Block::spaced`]). + tracking: Option, +} + +impl Block { + fn new(l: Line) -> Block { + let tracking = Block::spaced(&l).then_some(l.tracking); + Block { lines: vec![l], leading: 0.0, aligns: [true; 3], tracking } + } + + /// Does line `l` have a tracking of its own? A line of fewer than three glyphs that kept no + /// tracking has no gaps to measure it by ([`Line::tracked`]): it takes the block's. + fn spaced(l: &Line) -> bool { + l.pieces.len() >= 3 || l.tracking != 0.0 + } + + /// Add `l` when it continues the block; `l` back when it does not. `follows` tells whether the + /// shape `l` starts with comes right after the block's last shape, with nothing between them + /// in paint order. + fn take(&mut self, l: Line, follows: impl Fn(NodeId, NodeId) -> bool) -> Option { + let (Some(first), Some(prev)) = (self.lines.first(), self.lines.last()) else { return Some(l) }; + let (Some(a), Some(b)) = (prev.pieces.last(), l.pieces.first()) else { return Some(l) }; + let size = first.size(); + let tol = (size * 0.01).max(0.01); + let same = follows(*a, *b) + && l.parent == first.parent + && l.appearance == first.appearance + && l.opacity == first.opacity + && l.blend == first.blend + && l.face.id() == first.face.id() + && (l.scale - first.scale).abs() <= first.scale * 1e-4 + && ((l.angle - first.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + // The lines' estimates may differ a little; the layout check decides. + && (!Block::spaced(&l) || self.tracking.is_none_or(|t| (l.tracking - t).abs() < 1.0)) + // Lines whose ink overlaps, or a gradient spanning them, would paint otherwise as one. + && paints_as_one(first); + if !same { + return Some(l); + } + // Across the lines, down from the first line's baseline. + let across = Vec2::new(-first.angle.sin(), first.angle.cos()); + let down = (l.origin - first.origin).dot(across); + let n = self.lines.len() as f64; + // The mean distance between the baselines so far, which this line's must continue. + let leading = if self.lines.len() == 1 { down } else { self.leading }; + // A quarter of the size is the least leading; the outlines' positions are rounded. + if !(leading >= size * 0.25 * (1.0 - 1e-6) && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol { + return Some(l); + } + let leading = down / n; + let (s0, e0) = first.span_from(first.origin); + let (s, e) = l.span_from(first.origin); + let fits = [(s - s0).abs() <= tol, (e - e0).abs() <= tol, ((s + e) - (s0 + e0)).abs() * 0.5 <= tol]; + let aligns = [self.aligns[0] && fits[0], self.aligns[1] && fits[1], self.aligns[2] && fits[2]]; + if !aligns.contains(&true) { + return Some(l); + } + self.leading = leading; + self.aligns = aligns; + if self.tracking.is_none() && Block::spaced(&l) { + self.tracking = Some(l.tracking); + } + self.lines.push(l); + None + } + + /// The block as one area type object when type draws every glyph in its place as area type, + /// else as one point type object when that does. When neither does, the lines before the line + /// of the first glyph the type moves are made again as a block, and the lines from that one on + /// are joined again ([`blocks`]); the first line on its own stays one object. Area type whose + /// frame would reach past [`crate::MAX_COORD`] stays point type, and point type whose bounds + /// would stays one object per line. Each try takes six times the + /// block's glyphs from `budget` (point and area type are each laid out, measured and checked); + /// without enough left, each line is one object. + fn made(self, system_layout: bool, budget: &mut usize) -> Vec { + let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::>(); + let (Some(first), true) = (self.lines.first(), self.lines.len() > 1) else { return single(&self.lines) }; + let Some(justify) = ALIGNS.iter().zip(self.aligns).find(|(_, ok)| *ok).map(|(j, _)| *j) else { return single(&self.lines) }; + let glyphs = self.lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add); + let Some(left) = budget.checked_sub(glyphs.saturating_mul(6)) else { return single(&self.lines) }; + *budget = left; + let mut all = first.clone(); + all.tracking = self.tracking.unwrap_or(first.tracking); + all.text = self.lines.iter().map(|l| l.text.as_str()).collect::>().join("\n"); + let mut t = all.probe(system_layout); + t.para.justify = justify; + let size = first.size(); + let mut set_leading = None; + if let Some(r) = t.runs.first_mut() { + // The leading that puts the last baseline where the last line's is: Auto when Auto + // does, else the mean distance between baselines, to a thousandth of a point (as + // typed leading is) when that still puts the last baseline in place. + let gaps = self.lines.len().saturating_sub(1) as f64; + let across = Vec2::new(-first.angle.sin(), first.angle.cos()); + let span = self.lines.last().map_or(0.0, |l| (l.origin - first.origin).dot(across)); + if (t.para.effective_leading(&r.style) * gaps - span).abs() > size * 1e-4 { + let exact = span / gaps; + let rounded = (exact * 1000.0).round() / 1000.0; + let leading = if ((rounded - exact) * gaps).abs() <= size * 1e-4 { rounded } else { exact }; + r.style.leading = Some(leading); + set_leading = Some(leading); + } + } + let matches: Vec = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect(); + // Aligned at its end or center, point type starts its first line elsewhere: the type moves + // so its first glyph is where the first outline is. + let lay = vectorcraft_text::layout(FontDb::global(), &t); + if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) { + let at = t.xf * (g.xf * Point::ORIGIN); + t.xf = kurbo::Affine::translate(m.origin - at) * t.xf; + } + super::typecmd::refresh_bounds(&mut t); + if let Some(k) = first_mismatch(&t, &matches, size, first.slack) { + // The line that holds glyph `k`. + let mut seen = 0usize; + let at = self.lines.iter().position(|l| { + seen = seen.saturating_add(l.pieces.len()); + k < seen + }); + let Block { mut lines, leading, aligns, .. } = self; + let rest = lines.split_off(at.unwrap_or(0).clamp(1, lines.len())); + let mut out = if lines.len() > 1 { + let tracking = lines.iter().find(|l| Block::spaced(l)).map(|l| l.tracking); + Block { lines, leading, aligns, tracking }.made(system_layout, budget) + } else { + single(&lines) + }; + // The lines of the rest followed each other in the block. + out.extend(blocks(rest, |_, _| true, system_layout, budget)); + return out; + } + // The edit is refused when an object's bounds reach past the coordinate limit. A turned + // block's box can reach a corner that none of its lines does: the lines then stay apart. + let in_range = + |t: &TextObject| Node::new(NodeId(0), NodeKind::Text(Box::new(t.clone()))).geometric_bounds().is_none_or(crate::sanity::rect_in_range); + if !in_range(&t) { + return single(&self.lines); + } + let mut area = t.clone(); + super::typemenu::point_to_area(&mut area); + let mut point = None; + if in_range(&area) && first_mismatch(&area, &matches, size, first.slack).is_none() { + point = Some(std::mem::replace(&mut t, area)); + } + vec![Made { + t, + point, + matches, + pieces: self.lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(), + text: all.text, + face: first.face.clone(), + size, + slack: first.slack, + tracking: all.tracking, + leading: set_leading, + opacity: first.opacity, + blend: first.blend, + }] + } +} + +/// A line of two untracked glyphs has one gap, too few to measure a tracking by +/// ([`Line::tracked`]). It is set at the tracking of the nearest tracked line of the same font, +/// size and turn, so the layout check ([`verified`]) tries it as that line is set: the check falls +/// back to the line untracked, and then splits it, when the pair is not spaced so. A pair that +/// untracked type already draws in place keeps its text, and negative tracking goes only to a pair +/// that paints the same as one object ([`paints_as_one`]). +fn share_tracking(lines: &mut [Line], system_layout: bool) { + for i in 0..lines.len() { + let Some(l) = lines.get(i).filter(|l| l.pieces.len() == 2 && l.tracking == 0.0) else { continue }; + if l.first_mismatch(&l.probe(system_layout)).is_none() { + continue; + } + let like = |o: &Line| { + o.tracking != 0.0 + && o.parent == l.parent + && o.face.id() == l.face.id() + && (o.scale - l.scale).abs() <= l.scale * 1e-4 + && ((o.angle - l.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + }; + let nearest = lines.iter().enumerate().filter(|(_, o)| like(o)).min_by_key(|(j, _)| j.abs_diff(i)).map(|(_, o)| o.tracking); + if let Some(p) = nearest.filter(|t| *t > 0.0 || paints_as_one(l)).and_then(|t| l.respaced(0, 2, t)) { + lines[i] = p; + } + } +} + +/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of +/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after +/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`]. +fn blocks(lines: Vec, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec { + let mut out = vec![]; + let mut block: Option = None; + for l in lines { + let l = match block.as_mut() { + Some(b) => match b.take(l, &follows) { + None => continue, + Some(l) => l, + }, + None => l, + }; + if let Some(b) = block.take() { + out.extend(b.made(system_layout, budget)); + } + block = Some(Block::new(l)); + } + if let Some(b) = block { + out.extend(b.made(system_layout, budget)); + } + out +} + /// Puts parts of a line at the front of the work list, in order. trait FrontParts { fn extend_front_parts(&mut self, l: &Line, ranges: [(usize, usize); N]); @@ -1130,7 +1437,8 @@ fn retype(s: &mut Session, p: &Value) -> Result { // glyphs), so every line has what its measure can take. let mut budget = lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add); - let lines = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect(); + let mut lines: Vec = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect(); + share_tracking(&mut lines, system_layout); let mut lines = verified(lines, system_layout, &mut unmatched); if pieces.len() > 1 || glyphs_of.values().any(|n| *n > 1) { lines.retain(|l| { @@ -1155,12 +1463,22 @@ fn retype(s: &mut Session, p: &Value) -> Result { let kept: std::collections::HashSet = lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(); let mut seen = std::collections::HashSet::new(); unmatched.retain(|id| !kept.contains(id) && seen.insert(*id)); - (lines, unmatched, truncated) + let at: std::collections::HashMap = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect(); + let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) { + (Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier), + _ => false, + }; + // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room + // for small blocks. + let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256); + (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated) }; if lines.is_empty() { return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); } let made = s.edit("Retype", |d, sel| { + // The layers as they were, for the Text Wrap check below. + let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone()); let mut ids = vec![]; let mut emptied = vec![]; // Every line's type goes in before the shapes go: a shape of several glyphs is the first @@ -1169,9 +1487,8 @@ fn retype(s: &mut Session, p: &Value) -> Result { for l in &lines { let Some(first) = l.pieces.first() else { continue }; let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?; - let t = l.text_object(system_layout); let id = d.alloc_id(); - let mut node = Node::new(id, NodeKind::Text(Box::new(t))); + let mut node = Node::new(id, NodeKind::Text(Box::new(l.t.clone()))); // The glyphs' own transparency (the group's, kept, still applies over it). node.opacity = l.opacity; node.blend = l.blend; @@ -1222,23 +1539,66 @@ fn retype(s: &mut Session, p: &Value) -> Result { } } } + // Text Wrap objects above new area type flow it once the edit is done: area type they + // would move a glyph of becomes the point type that draws it in place. + if let Some(before) = &before { + // Worked out on a copy, so the edit's own Text Wrap refresh still sees every other + // area type whose wrap changes, and only on the layers this edit changed, as that + // refresh is. The copy holds only the changed layers while the work is counted; past + // the limit, the new area type is not flowed and all of it becomes its point type. + let mut probe = d.clone(); + let all = std::mem::take(&mut probe.layers); + probe.layers = all + .iter() + .enumerate() + .filter(|(i, layer)| { + // As resolve_wrap tells an unchanged layer: the same layer at its index first. + !(before.layers.get(*i).is_some_and(|b| Arc::ptr_eq(b, layer)) + || before.layers.iter().any(|b| b.id == layer.id && Arc::ptr_eq(b, layer))) + }) + .map(|(_, layer)| layer.clone()) + .collect(); + let units = vectorcraft_doc::text::wrap_copy_units(&probe); + let flowed = units <= max_wrap_work(); + probe.layers = all; + if flowed && units > 0 { + vectorcraft_doc::text::resolve_wrap(Some(before), &mut probe); + } + // With nothing to copy, no area type on those layers has a wrap shape. + for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) { + let Some(point) = &l.point else { continue }; + let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue }; + if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size, l.slack).is_none()) { + continue; + } + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + **t = point.clone(); + } + } + } let mut keep: Vec = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect(); keep.extend(&ids); sel.set(keep); Ok(ids) })?; + let d = &s.doc()?.doc; + let area = + |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })); Ok(json!({ "ids": made.iter().map(|i| i.0).collect::>(), "texts": lines.iter().map(|l| l.text.clone()).collect::>(), "fonts": lines .iter() - .map(|l| { + .zip(&made) + .map(|(l, id)| { let score = l.matches.iter().map(GlyphMatch::score).fold(1.0, f64::min); json!({ "family": l.face.family, "style": l.face.style, - "size": l.size(), + "size": l.size, "tracking": l.tracking, + "leading": l.leading, + "area": area(id), "score": (score * 1000.0).round() / 1000.0, }) }) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 46352f22aa..05c8210542 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -750,6 +750,224 @@ fn turned_near_matched_round_glyphs_keep_the_line_turn() { } } +#[test] +fn several_lines_become_one_area_type_object() { + let mut s = session(); + let text = "First line\nSecond one\nThird"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(true), "{r}"); + assert_eq!(r["fonts"][0]["leading"], json!(null), "Auto leading gives the lines' spacing: {r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })); + assert_eq!(t.plain_text(), text); + assert_same_places(&before, &t); +} + +#[test] +fn lines_a_quarter_of_the_size_apart_join_and_closer_ones_do_not() { + // At 20 pt, 5 pt is the least leading that joins lines. + // 4.9999999 pt is 5 pt to the rounding of the outlines' positions. + for (leading, objects) in [(5.0, 1), (4.9999999, 1), (4.9, 2)] { + let mut s = session(); + let text = "One\nTwo"; + let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 20}), &[json!({"leading": leading})]); + assert_eq!(r["texts"].as_array().unwrap().len(), objects, "{leading}: {r}"); + } +} + +#[test] +fn a_two_glyph_line_takes_the_tracking_of_the_lines_around_it() { + let mut s = session(); + let text = "MMM\nMM\nMMM"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 50})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn lines_keep_their_leading_and_alignment() { + for justify in ["left", "center", "right"] { + let mut s = session(); + let text = "Wide first line\nmid\nlast one"; + let (before, r) = retyped(&mut s, json!({"x": 300, "y": 100, "text": text, "size": 20, "justify": justify}), &[json!({"leading": 31})]); + assert_eq!(r["texts"], json!([text]), "{justify}: {r}"); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 31.0, 1e-3), "{justify}: {r}"); + assert_eq!(r["fonts"][0]["area"], json!(true), "{justify}: {r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "{justify}"); + assert_eq!(t.para.justify, before.para.justify, "{justify}"); + assert_same_places(&before, &t); + } +} + +#[test] +fn a_long_block_near_auto_leading_keeps_its_own_leading() { + // 24.001 pt is Auto's 24 pt within a ten-thousandth of the size per line, but 250 lines + // move the last one a quarter of a point. + let mut s = session(); + let text = vec!["ab"; 250].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 24.001})]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.001, 1e-4), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_long_block_at_auto_leading_of_a_fractional_size_keeps_auto() { + // Auto leading of 20.002 pt is 24.0024 pt, finer than the thousandth of a point the leading + // between two lines is read to. + let mut s = session(); + // Six hundred lines: read to a thousandth, each gap would be 0.0004 pt short, and the last + // line 0.24 pt off. + let text = vec!["ab"; 600].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20.002}), &[]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert_eq!(r["fonts"][0]["leading"], json!(null), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_long_block_at_a_leading_finer_than_a_thousandth_keeps_it() { + // 23.9996 pt read to a thousandth is 24 pt, Auto for 20 pt type: over 600 lines the last one + // would be 0.24 pt off. + let mut s = session(); + let text = vec!["ab"; 600].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 23.9996})]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 23.9996, 1e-6), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_block_whose_first_gap_is_a_little_off_stays_one_object() { + // The second line moved up 0.004 pt: its gap read alone, carried over 100 lines, would put + // the last one 0.4 pt off. + let mut s = session(); + let text = ["ab"; 100].join("\n"); + let id = s.execute("text.create", &json!({"x": 40, "y": 40, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "leading": 24.004})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let kids = children_of(&s, g); + s.execute("select.set", &json!({"ids": kids[2..4]})).unwrap(); + s.execute("object.move", &json!({"dx": 0, "dy": -0.004})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.004, 1e-3), "{}", r["fonts"][0]); +} + +#[test] +fn lines_whose_frame_would_pass_the_coordinate_limit_stay_point_type() { + let mut s = session(); + let text = "Wide line\nWide"; + let id = s.execute("text.create", &json!({"x": 3_999_000, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap(); + let right = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x1; + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // The ink ends 2 pt short of the limit; Convert To Area Type's slack would reach past it. + s.execute("object.move", &json!({"dx": vectorcraft_doc::MAX_COORD - 2.0 - right, "dy": 0})).unwrap(); + let before = text_of(&s, id); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(false), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_line_type_cannot_join_ends_the_block_there() { + // The fourth line keeps a fraction of a unit of tracking that the others do not: joined, it + // moves, so the lines before it stay one object and the lines after it join again. + let mut s = session(); + let line = "M".repeat(40); + let text = [line.as_str(); 6].join("\n"); + let start = 3 * 41; + let (before, r) = + retyped(&mut s, json!({"x": 20, "y": 40, "text": text, "size": 20}), &[json!({"start": start, "end": start + 40, "tracking": 0.6})]); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.len(), 3, "{texts:?} {}", r["fonts"]); + assert_eq!(texts.join("\n"), text); + let places: Vec = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect(); + let want = glyph_places(&before); + assert_eq!(places.len(), want.len()); + for (x, y) in places.iter().zip(&want) { + assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}"); + } +} + +/// The glyphs of the outline groups `others` moved to the end of group `g`, in order, and the +/// emptied groups removed. +fn into_one_group(s: &mut Session, g: u64, others: &[u64]) { + s.edit("test", |d, _| { + for o in others { + let kids: Vec<_> = d.node(NodeId(*o)).unwrap().children().unwrap().to_vec(); + d.remove(NodeId(*o))?; + for k in kids { + let at = d.node(NodeId(g)).unwrap().children().unwrap().len(); + d.insert(Some(NodeId(g)), at, (*k).clone())?; + } + } + Ok(()) + }) + .unwrap(); +} + +#[test] +fn lines_that_do_not_stack_as_a_paragraph_stay_apart() { + let mut s = session(); + // Far apart, then lined up at nothing. + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Top", "size": 20})); + let b = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Far", "size": 20})); + let c = outlined(&mut s, json!({"x": 75, "y": 324, "text": "Askew", "size": 20})); + into_one_group(&mut s, a, &[b, c]); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}"); + assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}"); +} + +#[test] +fn a_shape_between_lines_keeps_them_apart() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB\nCD", "size": 30})); + let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.edit("test", |d, _| { + let n = d.node(NodeId(rect)).unwrap().clone(); + d.remove(NodeId(rect))?; + d.insert(Some(NodeId(g)), 2, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["AB", "CD"]), "the rectangle is painted between the lines: {r}"); +} + +#[test] +fn tracked_lines_keep_their_tracking_and_spaces() { + let mut s = session(); + let text = "SPACED OUT\nTITLE"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_short_line_takes_the_tracking_of_its_block() { + // One glyph has no gap to measure tracking by: it joins the tracked lines. + for text in ["TITLE\nB", "B\nTITLE", "TITLE\nB\nTITLE"] { + let mut s = session(); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + #[test] fn unevenly_tracked_type_still_becomes_type() { let mut s = session(); @@ -1419,3 +1637,112 @@ fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() { assert_eq!(r["texts"], json!(["M", "M", "M", "M"]), "{r}"); assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["tracking"] == json!(0.0)), "{r}"); } + +#[test] +fn translucent_gradient_or_stroked_lines_stay_apart() { + for case in ["opacity", "blend", "gradient", "stroke"] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "One\nTwo", "size": 30})); + let kids = children_of(&s, g); + match case { + "gradient" => { + let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("paint.setFill", &json!({"gradient": gradient, "ids": kids})).unwrap(); + } + "stroke" => { + s.execute("paint.setStroke", &json!({"color": "#ff0000", "ids": kids})).unwrap(); + } + _ => { + s.edit("test", |d, _| { + for k in &kids { + let n = d.node_mut(NodeId(*k)).unwrap(); + if case == "opacity" { + n.opacity = 0.5; + } else { + n.blend = vectorcraft_color::BlendMode::Multiply; + } + } + Ok(()) + }) + .unwrap(); + } + } + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["One", "Two"]), "{case}: one object would composite or fill the lines as one: {r}"); + } +} + +#[test] +fn lines_stay_point_type_past_the_text_wrap_limit_of_their_layer() { + // A Text Wrap object above the lines that moves no glyph, on their layer or on another one, + // with the limit lowered to nothing: only on their layer does it count. + for same_layer in [true, false] { + let mut s = session(); + let text = "First line\nSecond one"; + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap(); + let before = text_of(&s, id); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + if !same_layer { + // Area type below the Text Wrap object on the other layer: work there, none on this one. + s.execute("layer.new", &json!({})).unwrap(); + let other = s.execute("text.create", &json!({"x": 450, "y": 300, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("type.convertToAreaType", &json!({"ids": [other]})).unwrap(); + } + let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 330, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + super::WRAP_LIMIT.with(|c| c.set(0)); + let r = s.execute("type.retype", &json!({})); + super::WRAP_LIMIT.with(|c| c.set(super::MAX_WRAP_WORK)); + let r = r.unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(!same_layer), "{same_layer}: {r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + +#[test] +fn empty_subpaths_of_a_text_wrap_object_count_as_wrap_work() { + // Each one is copied into the wrap shapes of the area type below it. + let mut s = session(); + let t = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Area", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("type.convertToAreaType", &json!({"ids": [t]})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + let base = vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc); + let file_work = vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc); + s.edit("test", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(rect)).unwrap().kind { + for _ in 0..100 { + path.subpaths.push(vectorcraft_geom::SubPath::new(vec![], true)); + } + } + Ok(()) + }) + .unwrap(); + assert!(vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc) >= base + 100); + // The count file import and the `.ai` editing copy use stays anchors and shapes only. + assert_eq!(vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc), file_work); +} + +#[test] +fn lines_under_a_text_wrap_object_stay_point_type() { + let mut s = session(); + let text = "First line\nSecond one"; + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap(); + let before = text_of(&s, id); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + // Above the outlines, over the end of both lines: area type would wrap round it. + let rect = s.execute("shape.rectangle", &json!({"x": 90, "y": 70, "width": 60, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(false), "{r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Point)); + assert_same_places(&before, &t); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index e9c316157f..b66a50bc19 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -634,34 +634,40 @@ fn to_area(s: &mut Session, p: &Value) -> Result { if !matches!(t.kind, TextKind::Point) { continue; } - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - // The frame is worked out in line space, where the lines are; vertical type turns it - // into text space with the lines. - let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; - let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds); - // Across, the frame spans the lines as they are aligned: from their starts to their ends - // without the tracking after their last characters (`LineInfo::trailing`), not to the - // ink, which tracking can pull past an advance. Area type aligns them alike. - let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing))); - if x0.is_finite() && x1.is_finite() && x0 <= x1 { - (b.x0, b.x1) = (x0, x1); - } - // Line breaking counts that tracking: the slack holds the most of it. - let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max); - let size = t.first_style().size; - // A little slack on the right so the text doesn't rewrap. - let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0); - let slack = size * 0.5 + trailing; - let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack); - let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0))); - t.kind = TextKind::Area { frame: shapes::rectangle(frame) }; - refresh_bounds(t); + point_to_area(t); } Ok(()) })?; Ok(ids_json(&ids)) } +/// Point type `t` turned into area type in a frame around its lines, with a little slack where its +/// alignment leaves room, so the text stays where it is and does not rewrap. +pub(super) fn point_to_area(t: &mut TextObject) { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + // The frame is worked out in line space, where the lines are; vertical type turns it + // into text space with the lines. + let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; + let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds); + // Across, the frame spans the lines as they are aligned: from their starts to their ends + // without the tracking after their last characters (`LineInfo::trailing`), not to the + // ink, which tracking can pull past an advance. Area type aligns them alike. + let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing))); + if x0.is_finite() && x1.is_finite() && x0 <= x1 { + (b.x0, b.x1) = (x0, x1); + } + // Line breaking counts that tracking: the slack holds the most of it. + let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max); + let size = t.first_style().size; + // A little slack on the right so the text doesn't rewrap. + let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0); + let slack = size * 0.5 + trailing; + let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack); + let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0))); + t.kind = TextKind::Area { frame: shapes::rectangle(frame) }; + refresh_bounds(t); +} + /// How `slack` added to point type's lines in a frame is shared before and after them: where the /// alignment leaves room, so the text doesn't move or rewrap. fn slack_sides(justify: Justify, rtl: bool, slack: f64) -> (f64, f64) { diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 090c28e988..756db7a859 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -124,7 +124,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "engraving", "arrows", "image-brush", - "artistic" + "artistic", + "vector-packs" ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); @@ -204,6 +205,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() { ("arrows", "art"), ("image-brush", "scatter"), ("artistic", "art"), + ("vector-packs", "scatter"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); @@ -272,6 +274,48 @@ fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn vector_packs_marks_are_editable_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "vector-packs").unwrap(); + let names = ["Compass Rose", "Botanical Sprig", "Facet Diamond", "Tide Crest"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); + for b in &lib.brushes { + let BrushKind::Scatter(sc) = &b.kind else { panic!("{} is not a scatter brush", b.name) }; + assert!(art_paths(&sc.art).len() >= 2, "{} has no editable vector mark", b.name); + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &black_stroke()); + assert!(pieces.len() >= 3, "{} does not repeat along a path", b.name); + // The black marks take a non-black stroke color as their fill. + let teal = vectorcraft_color::Color::rgb(0.1, 0.6, 0.5); + let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(teal), 1.0); + let mut fills = vec![]; + for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke) { + piece.walk(&mut |c| { + if c.path_data().is_some() { + fills.push(c.appearance.fill().map(|f| f.paint.clone())); + } + }); + } + assert!(!fills.is_empty(), "{} draws no paths", b.name); + for fill in fills { + let Some(vectorcraft_color::Paint::Solid { color, .. }) = fill else { panic!("{} draws a path without a solid fill: {fill:?}", b.name) }; + let (got, want) = (color.to_rgb(), teal.to_rgb()); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{} fills {got:?}, not the stroke color {want:?}", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "vector-packs", "name": b.name, "apply": true, "ids": [line]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([line])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(line)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + #[test] fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() { let mut s = session(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 4e061919a9..1f8936e58e 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7911,6 +7911,11 @@ breakText Glyphs Глифи @msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. @msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Vector Packs Векторни пакети + Compass Rose Роза на компаса + Botanical Sprig Ботаническо клонче + Facet Diamond Фасетиран ромб + Tide Crest Гребен на вълна Leaf Vine Листна лоза Blossom Chain Цветна верига Pennant Garland Гирлянд от знаменца diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6377d2ba1a..974634b503 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7966,6 +7966,11 @@ shape Open Otvoren @msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. @msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Vector Packs Vektorski paketi + Compass Rose Ruža kompasa + Botanical Sprig Botanička grančica + Facet Diamond Fasetirani romb + Tide Crest Vrh vala Leaf Vine Lisnata loza Blossom Chain Cvjetni lanac Pennant Garland Girlanda zastavica diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 323b8f6638..fabf012149 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8954,6 +8954,11 @@ breakText Glyphs Glifs @msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. @msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Vector Packs Paquets vectorials + Compass Rose Rosa dels vents + Botanical Sprig Branqueta botànica + Facet Diamond Diamant facetat + Tide Crest Cresta de l'onada Leaf Vine Enfiladissa de fulles Blossom Chain Cadena de flors Pennant Garland Garlanda de banderins diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index abf34f7517..4978a4c2be 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -10778,6 +10778,11 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Vector Packs Vektorové balíčky + Compass Rose Směrová růžice + Botanical Sprig Botanická větvička + Facet Diamond Fazetový diamant + Tide Crest Hřeben vlny Leaf Vine Listová liána Blossom Chain Květinový řetěz Pennant Garland Girlanda praporků diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b679e704b7..fa53829311 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10840,6 +10840,11 @@ breakText Glyphs Glyffer @msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. @msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Vector Packs Vektorpakker + Compass Rose Kompasrose + Botanical Sprig Botanisk kvist + Facet Diamond Facetteret diamant + Tide Crest Bølgetop Leaf Vine Bladranke Blossom Chain Blomsterkæde Pennant Garland Vimpelguirlande diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index a1506cc95e..3e756045e6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -10419,6 +10419,11 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Vector Packs Vektorpakete + Compass Rose Kompassrose + Botanical Sprig Botanischer Zweig + Facet Diamond Facettierter Diamant + Tide Crest Wellenkamm Leaf Vine Blätterranke Blossom Chain Blütenkette Pennant Garland Wimpelgirlande diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 833d7edf6a..4b7b7b8324 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8927,6 +8927,11 @@ breakText Glyphs Γλύφοι @msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. @msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Vector Packs Διανυσματικά πακέτα + Compass Rose Ρόδο πυξίδας + Botanical Sprig Βοτανικό κλαδάκι + Facet Diamond Πολυεδρικό διαμάντι + Tide Crest Κορυφή κύματος Leaf Vine Κληματίδα φύλλων Blossom Chain Αλυσίδα λουλουδιών Pennant Garland Γιρλάντα σημαιών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2877211c1a..90d9a15aef 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -10671,6 +10671,11 @@ breakText Glyphs Glifos @msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. @msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Vector Packs Paquetes vectoriales + Compass Rose Rosa de los vientos + Botanical Sprig Ramita botánica + Facet Diamond Diamante facetado + Tide Crest Cresta de ola Leaf Vine Enredadera de hojas Blossom Chain Cadena de flores Pennant Garland Guirnalda de banderines diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 8bc5b257d0..f4b1ec8db1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -9010,6 +9010,11 @@ breakText Glyphs Merkit @msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. @msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Vector Packs Vektoripaketit + Compass Rose Kompassiruusu + Botanical Sprig Kasvinoksa + Facet Diamond Särmätty timantti + Tide Crest Aallonharja Leaf Vine Lehtiköynnös Blossom Chain Kukkaketju Pennant Garland Viiririvistö diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5a184597a3..c03693c7f7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -10741,6 +10741,11 @@ breakText Glyphs Glyphes @msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. @msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Vector Packs Packs vectoriels + Compass Rose Rose des vents + Botanical Sprig Rameau botanique + Facet Diamond Diamant facetté + Tide Crest Crête de vague Leaf Vine Liane feuillue Blossom Chain Chaîne de fleurs Pennant Garland Guirlande de fanions diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 33d52397f5..c3fb620344 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5653,6 +5653,11 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Vector Packs વેક્ટર પૅક + Compass Rose દિશાસૂચક ગુલાબ + Botanical Sprig વનસ્પતિ ડાળી + Facet Diamond પાસાદાર હીરો + Tide Crest તરંગ શિખર Leaf Vine પાંદડાની વેલ Blossom Chain ફૂલોની સાંકળ Pennant Garland ધ્વજપટ્ટીની માળા diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6eeec8d99c..64a3d21ddc 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -10384,6 +10384,11 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Vector Packs वेक्टर पैक + Compass Rose दिशासूचक गुलाब + Botanical Sprig वनस्पति टहनी + Facet Diamond पहलूदार हीरा + Tide Crest लहर की चोटी Leaf Vine पत्तों की बेल Blossom Chain फूलों की शृंखला Pennant Garland झंडियों की माला diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3ad8bb09ef..c028eeade9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -10767,6 +10767,11 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Vector Packs Vektorcsomagok + Compass Rose Iránytűrózsa + Botanical Sprig Növényi ágacska + Facet Diamond Csiszolt gyémánt + Tide Crest Hullámhegy Leaf Vine Leveles inda Blossom Chain Virágfüzér Pennant Garland Zászlófüzér diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 85ef6beb39..84d283408d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8612,6 +8612,11 @@ breakText Glyphs Glif @msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. @msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Vector Packs Paket Vektor + Compass Rose Mawar Kompas + Botanical Sprig Ranting Botani + Facet Diamond Berlian Berfaset + Tide Crest Puncak Gelombang Leaf Vine Sulur Daun Blossom Chain Rangkaian Bunga Pennant Garland Untaian Panji diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d900c1cada..c43360435b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -10453,6 +10453,11 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Vector Packs Pacchetti vettoriali + Compass Rose Rosa dei venti + Botanical Sprig Rametto botanico + Facet Diamond Diamante sfaccettato + Tide Crest Cresta dell'onda Leaf Vine Tralcio di foglie Blossom Chain Catena di fiori Pennant Garland Ghirlanda di bandierine diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 824dca728a..7d16db8581 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10516,6 +10516,11 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Vector Packs ベクターパック + Compass Rose 羅針盤のバラ + Botanical Sprig 植物の小枝 + Facet Diamond 多面体ダイヤ + Tide Crest 波の頂 Leaf Vine 葉のつる Blossom Chain 花の連なり Pennant Garland 三角旗のガーランド diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d2d4e56e24..e1eea3c5b7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -11064,6 +11064,11 @@ font-script Japanese იაპონური @msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. @msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Vector Packs ვექტორული პაკეტები + Compass Rose კომპასის ვარდი + Botanical Sprig ბოტანიკური ტოტი + Facet Diamond წახნაგოვანი ბრილიანტი + Tide Crest ტალღის ქედი Leaf Vine ფოთლების ვაზი Blossom Chain ყვავილების ჯაჭვი Pennant Garland ალმების გირლანდა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4a59572606..ab4f55e562 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -10416,6 +10416,11 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Vector Packs 벡터 팩 + Compass Rose 나침반 장미 + Botanical Sprig 식물 가지 + Facet Diamond 패싯 다이아몬드 + Tide Crest 파도 마루 Leaf Vine 잎 덩굴 Blossom Chain 꽃사슬 Pennant Garland 깃발 장식 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 51402d1964..6b0380cfc6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10817,6 +10817,11 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Vector Packs Vectorpakketten + Compass Rose Kompasroos + Botanical Sprig Botanisch takje + Facet Diamond Gefacetteerde diamant + Tide Crest Golfkam Leaf Vine Bladrank Blossom Chain Bloemenketting Pennant Garland Vlaggetjesslinger diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 128f165b52..9caa46f46f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -10642,6 +10642,11 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Vector Packs Pakiety wektorowe + Compass Rose Róża wiatrów + Botanical Sprig Gałązka botaniczna + Facet Diamond Fasetowany diament + Tide Crest Grzbiet fali Leaf Vine Liściasta winorośl Blossom Chain Łańcuch kwiatów Pennant Garland Girlanda proporczyków diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a86792c918..0db13e6f05 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -10850,6 +10850,11 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Vector Packs Pacotes vetoriais + Compass Rose Rosa dos ventos + Botanical Sprig Ramo botânico + Facet Diamond Diamante facetado + Tide Crest Crista da onda Leaf Vine Trepadeira de folhas Blossom Chain Corrente de flores Pennant Garland Guirlanda de bandeirolas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d924dfeb2a..cc44602666 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10834,6 +10834,11 @@ shape Open Открытый @msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Vector Packs Векторные наборы + Compass Rose Роза ветров + Botanical Sprig Ботаническая ветвь + Facet Diamond Гранёный бриллиант + Tide Crest Гребень волны Leaf Vine Лиственная лоза Blossom Chain Цветочная цепочка Pennant Garland Гирлянда флажков diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 042e4fd36d..0a64e62411 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -10871,6 +10871,11 @@ digits Hindi Hindi @msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. @msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Vector Packs Vektorpaket + Compass Rose Kompassros + Botanical Sprig Botanisk kvist + Facet Diamond Fasetterad diamant + Tide Crest Vågkam Leaf Vine Bladranka Blossom Chain Blomkedja Pennant Garland Vimpelgirlang diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index aabaebdb26..4285ea4e63 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10736,6 +10736,11 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Vector Packs Vektör Paketleri + Compass Rose Pusula Gülü + Botanical Sprig Botanik Dal + Facet Diamond Fasetli Elmas + Tide Crest Dalga Tepesi Leaf Vine Yapraklı sarmaşık Blossom Chain Çiçek zinciri Pennant Garland Bayrak süsü diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 21e33075ce..245c3aa686 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -10429,6 +10429,11 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Vector Packs Векторні набори + Compass Rose Роза вітрів + Botanical Sprig Ботанічна гілочка + Facet Diamond Гранований діамант + Tide Crest Гребінь хвилі Leaf Vine Листяна лоза Blossom Chain Квітковий ланцюжок Pennant Garland Гірлянда прапорців diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index fbe7fc0517..7b20e4e0cc 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8626,6 +8626,11 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Vector Packs Bộ cọ véc-tơ + Compass Rose Hoa la bàn + Botanical Sprig Cành cây + Facet Diamond Kim cương nhiều mặt + Tide Crest Đỉnh sóng Leaf Vine Dây leo lá Blossom Chain Chuỗi hoa Pennant Garland Dây cờ tam giác diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d421813a89..67c8ac5d9d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -10621,6 +10621,11 @@ breakText Glyphs 字形 @msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 @msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Vector Packs 矢量画笔包 + Compass Rose 罗盘玫瑰 + Botanical Sprig 植物枝条 + Facet Diamond 切面钻石 + Tide Crest 浪尖 Leaf Vine 叶藤 Blossom Chain 花链 Pennant Garland 旗帜花环 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f2a8306713..87ccb8c676 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -10436,6 +10436,11 @@ breakText Glyphs 字符 @msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 @msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Vector Packs 向量筆刷包 + Compass Rose 羅盤玫瑰 + Botanical Sprig 植物枝條 + Facet Diamond 切面鑽石 + Tide Crest 浪尖 Leaf Vine 葉藤 Blossom Chain 花鏈 Pennant Garland 旗幟花環 diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index fbbd067236..49b25e987b 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -209,7 +209,8 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("engraving"), json!("arrows"), json!("image-brush"), - json!("artistic") + json!("artistic"), + json!("vector-packs") ] ); let dry = entries.iter().find(|e| under(e) && e.params["library"] == "dry-media").map(|e| e.label.as_str()); @@ -250,6 +251,12 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Orbit Lines", Modifiers::NONE, 3.0); assert!(has(&app, "Orbit Lines") && !has(&app, "Facet Sweep")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Vector Packs"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("vector-packs"), Some(4))); + let undo = undo_len(&app); + click(&mut app, &ctx, "Compass Rose", Modifiers::NONE, 4.0); + assert!(has(&app, "Compass Rose") && !has(&app, "Facet Diamond")); + assert_eq!(undo_len(&app), undo + 1); // Without brushes there is nothing to save. let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); app.run("brush.delete", json!({ "names": all })).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 9e8773d907..30b2f3ea56 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12524,6 +12524,26 @@ tracking their own gaps give. These rules are VectorCraft's own. Each entry of t {"name":"run_command","arguments":{"command":"type.retype","params":{}}} ``` +## Retype several lines + +`type.retype` joins lines that follow each other in paint order, with the same group, paint, font, size, turn and +tracking (an untracked line of one or two glyphs takes the tracking of the others), into one type object when each +line's baseline is the same distance below the one before (between 0.25 and 3 times the size) and the lines line up at their starts, ends or centers. The object is area type with Convert To Area +Type's frame, its lines separated by line breaks, with left, right or center alignment, checked in that order. Its +leading is Auto when Auto puts the last baseline in place, else the mean distance between the baselines, to a +thousandth of a point when that still puts the last baseline in place. Lines with an opacity below 100%, a blend mode +other than Normal, a gradient or pattern fill, or a stroke stay one object per line. These rules are VectorCraft's own. + +Every joined object is laid out and compared with the outlines. When area type would not draw each glyph where its +outline was, including after Text Wrap objects above it reflow it, or when its frame would reach past the canvas's +coordinate limit, the lines become one multi-line point type object (one object per line when its bounds would reach +past that limit). When that also moves a glyph, the lines before that glyph's line stay one object, and the lines +from that line on are joined again from it. When the Text Wrap objects on the layers Retype changes would copy more +than 2,000,000 units into the wrap shapes of their area type (one for each anchor, subpath and shape, for each area +type object below them), Retype does not check the wrap and the lines become multi-line point type. Each entry of +the result's `texts` list holds an object's lines joined by `\n`, and each entry of its `fonts` list also has +`leading` (points; null for Auto leading or a single line) and `area`. + ## Retype panel `type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path diff --git a/docs/roadmap.md b/docs/roadmap.md index dc85852cde..406bc1f4f7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -184,7 +184,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 587acc5c54..15a993f2a8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1251,6 +1251,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. - **Engraving library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching make fine parallel-line textures along paths. These four 100 pt art brushes are original VectorCraft geometry, with Tints colorization; they can be added, applied and saved through the existing library controls. - **Image Brush library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Image Brush offers Soft Bloom, Halftone Field, Solar Grain and Color Flecks as original image stamp designs. Each preset places copies of its embedded, transparent PNG along a path as a scatter brush; adding a brush carries its image resource into the document, and saving a library keeps the pixels. The public page names the category but not these presets. Evidence: `image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved` in `crates/engine/src/tests/brushlib.rs` covers stamps, add/apply and reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the UI. + - **Vector Packs library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Vector Packs offers Compass Rose, Botanical Sprig, Facet Diamond and Tide Crest. Each is an original editable vector mark repeated along a path as a scatter brush and tinted by the stroke color. The public page names the category but does not specify its presets. Evidence: `vector_packs_marks_are_editable_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers geometry, repetition, add/apply, undo and saving; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the menu and panel. - **Pressure Sensitive library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Pressure Sensitive offers Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow. The first two are art brushes whose width follows recorded pen pressure; the other two are calligraphic nibs whose size follows it. They use the engine's existing pressure input where the device and platform deliver it, and a neutral width for a mouse path. These presets and names are VectorCraft's own. Evidence: `pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` checks light and heavy pressure, short and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Decorative library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Decorative offers Leaf Vine, Blossom Chain, Pennant Garland and Lantern String. The four original vector pattern brushes repeat plant, flower and hanging ornament tiles along paths and take the stroke color as tints. The public source identifies Decorative as a classic brush library; these preset designs are VectorCraft's own. Evidence: `decorative_brushes_repeat_distinct_art_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers distinct finite output, add/apply and saved-library reopening, and `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Paint library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Paint offers Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep. These original art brushes stretch broad, broken, loaded and fanned vector marks along a path and take the stroke color as tints. The public source describes the Paint category's varied thickness, textured edges and natural effects; the preset designs and names are VectorCraft's own. Evidence: `paint_brushes_draw_distinct_marks_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers finite output on short, long and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. @@ -3069,6 +3070,10 @@ The identify-fonts page has the Retype panel list ten matching fonts ordered by #4934 asks Retype to match the tracking of outlined text. `type.retype` now sets a line whose glyphs most gaps space evenly apart with that spacing as tracking, keeps gaps one space wide as word spaces when untracked type draws them, and sets negative tracking only on opaque, Normal lines with a solid fill or none and no stroke. These rules are VectorCraft's own. Each line is laid out and compared with the outlines before it is kept; a line its tracked type would move a glyph of is checked again untracked, and the glyphs after a split take the tracking their own gaps give. Tested by round trips through Create Outlines (a tracked line with a word space; uneven, tight and fractional tracking; kerned pairs in tight tracking; spaced letters that need no tracking; translucent overlapping glyphs) and by the measure's layout budget, in `crates/engine/src/cmd/retype_tests.rs`. +## Retype several lines (2026-11-19) + +#4934 asks for area text when outlined text has several lines, with its line spacing. `type.retype` now turns lines that follow each other, stack at one leading and line up at their starts, ends or centers into one area type object with that leading and left, right or center alignment. These rules are VectorCraft's own. Each object is laid out and compared with the outlines before it is kept; when area type would move a glyph, the lines become multi-line point type, and when that also would, the block ends at the line of that glyph and the lines after it join again. Tested by round trips through Create Outlines (three lines with Auto leading; set leading with left, center and right alignment; long blocks at leadings finer than a thousandth of a point; a line tracked apart from the others; tracked lines with word spaces; lines far apart or askew; a shape painted between two lines; translucent, blended, gradient and stroked lines; lines under a Text Wrap object) in `crates/engine/src/cmd/retype_tests.rs`. + ## Control bar: Paragraph section while type is selected (2026-11-06) With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). diff --git a/docs/type-parity.md b/docs/type-parity.md index 7fd38090dc..d8e2c1e474 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them; VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. |