Merge main into feat/circle-from-center

This commit is contained in:
dotCooCoo committed 2026-11-19 13:47:01 -08:00
commit 1bcb5bbfb0
111 files changed
+6334 -856

No files matched your search

Generated
+10
View File
@@ -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",
+1
View File
@@ -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" }
+1
View File
@@ -253,6 +253,7 @@ fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
prefs_dir::attach_arrowheads(&mut h.session);
prefs_dir::attach_bevels(&mut h.session);
h
}
+2
View File
@@ -567,6 +567,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_custom_dictionary(&mut app.session);
// The custom arrowheads, kept in their own file next to the preferences.
prefs_dir::attach_arrowheads(&mut app.session);
// The custom bevels, kept in their own file next to the preferences.
prefs_dir::attach_bevels(&mut app.session);
// Fit the window to its monitor, or put it back where it was (still hidden).
let winit_window = cc.winit_window().cloned();
if let Some(w) = &winit_window {
+8
View File
@@ -122,6 +122,14 @@ pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep the custom bevels (`threeD.bevels.edit`) in the `Bevels.vectorcraft` file next to the
/// settings, and list the bevels it holds.
pub fn attach_bevels(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir(vectorcraft_engine::cmd::bevels::FILE_NAME) {
session.attach_bevels_file(path.to_string_lossy().to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
+1
View File
@@ -9,6 +9,7 @@ description = "VectorCraft color"
workspace = true
[dependencies]
craft-cms = { workspace = true }
kurbo = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+96 -455
View File
@@ -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<PaletteSwatch> {
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<PaletteSwatch>) -> Vec<Swatch> {
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<Vec<u8>, 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::<Vec<_>>().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<Vec<u8>, String> {
let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count();
let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::<usize>();
if entries > ASE_MAX_ENTRIES {
return Err(format!(
"VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}"
));
}
let mut body = vec![];
let mut blocks = put_ase_colors(&mut body, &lib.swatches)?;
for g in &lib.groups {
let mut name = vec![];
put_ase_name(&mut name, &g.name)?;
put_ase_block(&mut body, ASE_GROUP_START, &name)?;
blocks += 2 + put_ase_colors(&mut body, &g.swatches)?;
put_ase_block(&mut body, ASE_GROUP_END, &[])?;
}
let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?;
let mut out = ASE_SIGNATURE.to_vec();
out.extend(1u16.to_be_bytes());
out.extend(0u16.to_be_bytes());
out.extend(blocks.to_be_bytes());
out.extend(body);
Ok(out)
}
/// The color blocks of the solid colors in `list` → how many were written.
fn put_ase_colors(out: &mut Vec<u8>, list: &[Swatch]) -> Result<usize, String> {
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 };
let mut n = 0;
for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) {
let mut body = vec![];
put_ase_name(&mut body, &w.name)?;
let (model, values): (&[u8; 4], Vec<f32>) = match color {
Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]),
Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]),
Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]),
Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]),
};
body.extend(model);
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
let kind: u16 = if w.spot {
1
} else if w.global {
0
} else {
2
};
body.extend(kind.to_be_bytes());
put_ase_block(out, ASE_COLOR, &body)?;
n += 1;
}
Ok(n)
}
/// A block: its type, the length of its body and the body.
fn put_ase_block(out: &mut Vec<u8>, kind: u16, body: &[u8]) -> Result<(), String> {
let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?;
out.extend(kind.to_be_bytes());
out.extend(len.to_be_bytes());
out.extend_from_slice(body);
Ok(())
}
/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included,
/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units
/// is cut before the character that would pass that limit.
fn put_ase_name(out: &mut Vec<u8>, name: &str) -> Result<(), String> {
let mut units: Vec<u16> = vec![];
for c in name.chars().filter(|&c| c != '\0') {
let mut buf = [0; 2];
let encoded = c.encode_utf16(&mut buf);
if units.len() + encoded.len() > ASE_MAX_NAME {
break;
}
units.extend_from_slice(encoded);
}
units.push(0);
let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?;
out.extend(count.to_be_bytes());
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
Ok(())
}
/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the
/// file doesn't.
pub fn read(text: &str, name: &str) -> Result<SwatchLibrary, String> {
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<SwatchLibrary, String> {
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<u8> = 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
/// <https://www.selapa.net/swatches/colors/fileformats.php>, the component ranges from
/// <https://github.com/nsfmc/swatch>. 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<SwatchLibrary, String> {
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<SwatchLibrary, String> {
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<Option<Swatch>, 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<const N: usize>(&mut self) -> Result<[u8; N], String> {
let (head, rest) = self.0.split_first_chunk::<N>().ok_or(ASE_CUT_SHORT)?;
self.0 = rest;
Ok(*head)
}
fn u16(&mut self) -> Result<u16, String> {
self.array().map(u16::from_be_bytes)
}
fn u32(&mut self) -> Result<u32, String> {
self.array().map(u32::from_be_bytes)
}
/// A component; one that isn't a finite number reads as 0.
fn f32(&mut self) -> Result<f32, String> {
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<String, String> {
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<u16> = 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<String, String> {
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<u16> = 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<String>,
/// The last number tried for each repeated name.
last: HashMap<String, usize>,
}
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;
+52
View File
@@ -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");
}
+1 -1
View File
@@ -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`.
///
+28
View File
@@ -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();
+52 -6
View File
@@ -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<usize> = 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<Item<'a>>) {
}
}
/// 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() {
+2 -2
View File
@@ -191,7 +191,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
@@ -212,7 +212,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
CLASSIC_EXTRUDE,
"Extrude & Bevel (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.",
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's points, as for threeD.extrude; bevel {custom: name} takes a bevel of the bevels file), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.",
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false,"mapArt":[],"mapShade":false,"mapInvisible":false}),
),
g(
+6 -6
View File
@@ -97,11 +97,11 @@ pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES,
ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading,
extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics,
mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art,
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics,
RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options,
classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d,
mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe,
solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
validate_three_d_params, view_options, with_graphic,
};
@@ -116,8 +116,8 @@ pub use solids::{
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
pub use trap::TRAP;
pub use vectorcraft_three_d::Mesh;
pub use vectorcraft_three_d::PlanarFace;
pub use vectorcraft_three_d::{BevelProfile, Mesh};
pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version};
mod catalog;
+68 -7
View File
@@ -8,7 +8,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
use vectorcraft_pathops::BoolOp;
use vectorcraft_three_d::{
Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View,
Bevel, BevelProfile, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View,
};
#[cfg(test)]
@@ -72,7 +72,9 @@ pub const THREE_D_TYPES: [(&str, &str); 4] = [("plane", ROTATE), ("extrude", EXT
/// The parameters of 3D effect `to` for an effect `from` with `params`, as switching the object
/// type keeps them: every setting `to` takes keeps its value from `params` (the defaults of `from`
/// under them), each rotation angle wrapped into -180° to 180° when `to` is not Revolve, and the
/// settings only `to` takes start at their defaults. Settings `to` does not take are dropped.
/// settings only `to` takes start at their defaults. Settings `to` does not take are dropped; a
/// custom bevel's name and points ([`BEVEL_NAME`], [`BEVEL_PROFILE`]) go with `bevel` when `to`
/// takes one.
pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
let current = crate::merged_params(from, params);
let mut out = crate::default_params(to).and_then(|v| v.as_object().cloned()).unwrap_or_default();
@@ -81,6 +83,13 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
value.clone_from(v);
}
}
if out.contains_key("bevel") {
for key in [BEVEL_NAME, BEVEL_PROFILE] {
if let Some(v) = current.get(key).filter(|v| !v.is_null()) {
out.insert(key.into(), v.clone());
}
}
}
if to != crate::REVOLVE {
for key in ["rotationX", "rotationY", "rotationZ"] {
if let Some(a) = out.get(key).and_then(Value::as_f64).filter(|a| !(-180.0..=180.0).contains(a)) {
@@ -168,14 +177,66 @@ pub fn view_options(p: &Value) -> View {
}
}
/// Extrude & Bevel's parameters. `bevel` is `"none"` or a [`BevelShape`] id.
/// The custom bevel's name parameter: the name the bevels file gave it, kept for the menus.
pub const BEVEL_NAME: &str = "bevelName";
/// The custom bevel's points parameter: `[[across, down], …]`, shares of the bevel's width and
/// height from the cap's edge `[0, 0]` to the side wall `[1, 1]` (a copy of the bevel's path, so
/// the document draws it without the bevels file).
pub const BEVEL_PROFILE: &str = "bevelProfile";
/// The points of `v`, a [`BEVEL_PROFILE`] value; `None` unless it is an array of `[x, y]` number
/// pairs that make a [`BevelProfile`].
fn bevel_profile(v: &Value) -> Option<BevelProfile> {
let list = v.as_array().filter(|a| a.len() <= BevelProfile::MAX_POINTS)?;
let pts: Option<Vec<(f64, f64)>> = list
.iter()
.map(|pt| match pt.as_array().map(Vec::as_slice) {
Some([x, y]) => Some((x.as_f64()?, y.as_f64()?)),
_ => None,
})
.collect();
BevelProfile::new(&pts?)
}
/// The bevel shape of parameters `p`: `bevel` `"none"` (none), a built-in [`BevelShape`] id, or
/// `"custom"` with its points in [`BEVEL_PROFILE`] (none when they do not make a profile).
pub(crate) fn bevel_shape(p: &Value) -> Option<BevelShape> {
match text(p, "bevel", "none") {
"custom" => p.get(BEVEL_PROFILE).and_then(bevel_profile).map(BevelShape::Custom),
id => BevelShape::parse(id),
}
}
/// Check the custom bevel parameters of `p`: `bevel` `"custom"` needs [`BEVEL_PROFILE`], whose
/// points, when given, must make a profile, and [`BEVEL_NAME`] is a string.
fn validate_bevel(p: &Value) -> Result<(), String> {
let most = BevelProfile::MAX_POINTS;
if let Some(v) = p.get(BEVEL_PROFILE)
&& !v.is_null()
&& bevel_profile(v).is_none()
{
return Err(format!(
"{BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall)"
));
}
if text(p, "bevel", "none") == "custom" && p.get(BEVEL_PROFILE).is_none_or(Value::is_null) {
return Err(format!("bevel custom needs {BEVEL_PROFILE}, the bevel's points"));
}
if p.get(BEVEL_NAME).is_some_and(|v| !v.is_string() && !v.is_null()) {
return Err(format!("{BEVEL_NAME} must be a string"));
}
Ok(())
}
/// Extrude & Bevel's parameters. `bevel` is `"none"`, a [`BevelShape`] id, or `"custom"` with
/// its points in [`BEVEL_PROFILE`].
pub fn extrude_options(p: &Value) -> Extrude {
Extrude {
depth: num(p, "depth", 50.0),
twist: num(p, "twist", 0.0),
taper: num(p, "taper", 100.0) / 100.0,
cap: flag(p, "cap", true),
bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel {
bevel: bevel_shape(p).map(|shape| Bevel {
shape,
width: num(p, "bevelWidth", 4.0),
height: num(p, "bevelHeight", 4.0),
@@ -351,12 +412,12 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
graphics::validate(id, p)?;
wireframe::validate_render(id, p)?;
if let Some(v) = p.get("bevel")
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
&& !v.as_str().is_some_and(|s| s == "none" || s == "custom" || BevelShape::parse(s).is_some())
{
let names: Vec<_> = BevelShape::ALL.iter().map(|b| b.id()).collect();
return Err(format!("bevel must be none or one of {}", names.join(", ")));
return Err(format!("bevel must be none or one of {}, or custom with {BEVEL_PROFILE}", names.join(", ")));
}
Ok(())
validate_bevel(p)
}
/// The name an error gives 3D effect `id`.
+10 -10
View File
@@ -7,7 +7,7 @@ use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node};
use vectorcraft_geom::Rect;
use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light};
use vectorcraft_three_d::{Bevel, ClassicShading, ClassicSurface, Extrude, Facet, Light};
use super::graphics::map_art::{self, MapArt, MapBudget, SolidLayout};
use crate::util::{flag, num, text};
@@ -44,13 +44,7 @@ pub fn classic_extrude_options(p: &Value) -> Extrude {
Extrude {
depth: num(p, "depth", 50.0),
cap: flag(p, "cap", true),
bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel {
shape,
width: height,
height,
inside: flag(p, "bevelInside", false),
..Bevel::default()
}),
bevel: super::bevel_shape(p).map(|shape| Bevel { shape, width: height, height, inside: flag(p, "bevelInside", false), ..Bevel::default() }),
hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe,
// The numbered surfaces are laid out only for an effect that maps art onto them.
map_surfaces: !map_art::surface_maps(p).is_empty(),
@@ -119,9 +113,15 @@ const FLAGS: [&str; 7] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"
/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of
/// its parameters, numbers are in range, flags are true or false, `surface`, `shadingColor` and
/// `shadingCustom` name a surface, a shading color and a #rrggbb color, and `mapArt` holds valid
/// maps.
/// maps. A custom bevel's name and points ([`super::BEVEL_NAME`], [`super::BEVEL_PROFILE`]) are
/// parameters too, checked with Extrude & Bevel's.
pub fn validate(p: &Value) -> Result<(), String> {
validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)?;
let mut rest = p.clone();
if let Some(m) = rest.as_object_mut() {
m.remove(super::BEVEL_NAME);
m.remove(super::BEVEL_PROFILE);
}
validate_classic(CLASSIC_EXTRUDE, &rest, &RANGES, &FLAGS)?;
map_art::validate(CLASSIC_EXTRUDE, p)
}
+52
View File
@@ -1594,6 +1594,58 @@ fn parameters_are_validated_and_lengths_scale_with_the_object() {
assert!(extrude_options(&json!({})).bevel.is_none());
}
/// `bevel` custom draws the points of `bevelProfile` in both Extrude & Bevels, with the other bevel
/// settings; bad points, a custom bevel without points and a name that is not a string are refused.
#[test]
fn custom_bevels_draw_their_points_and_bad_points_are_refused() {
let n = square_node();
let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]);
let custom = json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch, "bevelWidth": 10, "bevelRepeat": 2, "bevelBothSides": true});
let b = extrude_options(&custom).bevel.unwrap();
assert!(matches!(b.shape, BevelShape::Custom(_)));
assert_eq!((b.width, b.repeat, b.both_sides), (10.0, 2, true));
let points: Vec<(f64, f64)> = match b.shape {
BevelShape::Custom(p) => p.points().collect(),
_ => vec![],
};
assert_eq!(points.len(), 4);
assert!((points[2].0 - 0.7).abs() < 1e-4 && (points[2].1 - 0.4).abs() < 1e-4, "{points:?}");
assert!(matches!(classic_extrude_options(&custom).bevel.map(|b| b.shape), Some(BevelShape::Custom(_))));
for id in [EXTRUDE, CLASSIC_EXTRUDE] {
let classic_params = json!({"bevel": "classic", "bevelHeight": 10});
let custom_params = json!({"bevel": "custom", "bevelProfile": notch, "bevelHeight": 10, "bevelName": "Notch"});
assert!(validate_solid(&n, id, &custom_params).is_ok(), "{id}");
let art = |p: &Value| {
let mut n = square_node();
n.appearance.effects.push(fx(id, p.clone()));
solid_art(&n).unwrap()
};
assert_ne!(art(&classic_params), art(&custom_params), "{id}");
for (bad, err) in [
(json!({"bevel": "custom"}), "bevel custom needs bevelProfile"),
(json!({"bevel": "custom", "bevelProfile": [[0, 0]]}), "bevelProfile must be 2 to 64"),
(json!({"bevel": "custom", "bevelProfile": [[0.1, 0], [1, 1]]}), "bevelProfile must be 2 to 64"),
(json!({"bevel": "custom", "bevelProfile": [[0, 0], [2, 0.5], [1, 1]]}), "bevelProfile must be 2 to 64"),
(json!({"bevel": "custom", "bevelProfile": [[0, 0], ["a", 0.5], [1, 1]]}), "bevelProfile must be 2 to 64"),
(json!({"bevel": "custom", "bevelProfile": "0,0 1,1"}), "bevelProfile must be 2 to 64"),
(json!({"bevel": "custom", "bevelProfile": notch, "bevelName": 3}), "bevelName must be a string"),
] {
let e = validate_solid(&n, id, &bad).unwrap_err();
assert!(e.contains(err), "{id} {bad}: {e}");
}
}
// A loaded file whose points do not make a profile draws no bevel.
assert!(extrude_options(&json!({"bevel": "custom", "bevelProfile": [[0, 0]]})).bevel.is_none());
// Changing the type keeps the custom bevel where the new effect takes a bevel, and drops it
// where it does not.
let classic = three_d_params_as(EXTRUDE, &custom, CLASSIC_EXTRUDE);
assert_eq!((&classic["bevel"], &classic[BEVEL_NAME], &classic[BEVEL_PROFILE]), (&json!("custom"), &json!("Notch"), &notch));
assert!(validate_solid(&n, CLASSIC_EXTRUDE, &classic).is_ok());
assert_eq!(three_d_params_as(CLASSIC_EXTRUDE, &classic, EXTRUDE)[BEVEL_PROFILE], notch);
let inflate = three_d_params_as(EXTRUDE, &custom, INFLATE);
assert!(inflate.get(BEVEL_PROFILE).is_none() && inflate.get(BEVEL_NAME).is_none());
}
#[test]
fn inflate_reads_twist_taper_and_cap() {
let o = inflate_options(&json!({"twist": 90, "taper": 40, "cap": false}));
+2
View File
@@ -8,6 +8,7 @@ pub mod arrowheads;
mod artboardalign;
mod assets;
mod attributes;
pub mod bevels;
pub mod brushlib;
mod brushsym;
mod buildcmds;
@@ -321,6 +322,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(draw2::specs());
v.extend(xform::specs());
v.extend(effectcmd::specs());
v.extend(bevels::specs());
v.extend(wireframe::specs());
v.extend(pathops::specs());
v.extend(compoundshape::specs());
+6 -5
View File
@@ -378,13 +378,14 @@ impl Session {
}
}
fn same_file(a: &str, b: &str) -> bool {
pub(super) fn same_file(a: &str, b: &str) -> bool {
let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p));
std::path::Path::new(a) == std::path::Path::new(b) || canon(a) == canon(b)
}
/// The document in the arrowheads file at `path`; `None` when there is no file.
fn read(path: &str) -> std::result::Result<Option<Document>, String> {
/// The document in the arrowheads file at `path` (or another such file of the user's, as the
/// bevels file); `None` when there is no file.
pub(super) fn read(path: &str) -> std::result::Result<Option<Document>, String> {
let size = match std::fs::metadata(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(format!("{path}: {e}")),
@@ -412,13 +413,13 @@ fn skipped(s: &Session) -> Vec<Value> {
/// The arrowheads file at `path` checked for reading against the automation roots in force: an agent
/// confined to read roots reaches the file only inside them. The error names the file by its file
/// name outside them.
fn may_reach(path: &str) -> Result<()> {
pub(super) fn may_reach(path: &str) -> Result<()> {
crate::file_access::check_read(path).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), path))
}
/// `msg`, an error about the arrowheads file at `path`, as the request being served may see it: the
/// file named whole inside the read roots, else by its file name.
fn shown_error(msg: &str, path: Option<&str>) -> String {
pub(super) fn shown_error(msg: &str, path: Option<&str>) -> String {
let Some(path) = path else { return msg.to_string() };
match super::fileio::naming_in_error(EngineError::Other(msg.to_string()), path) {
EngineError::Other(m) => m,
+378
View File
@@ -0,0 +1,378 @@
//! Custom bevels for Extrude & Bevel and Extrude & Bevel (Classic). The bevels file is a native
//! document kept next to the preferences ([`Session::attach_bevels_file`]). Each of its symbols
//! whose art is one open path is one bevel, listed by the symbol's name after the built-in shapes
//! in the Bevel Shape menus. The path runs from its first anchor, at the cap's edge, to its last,
//! at the side wall: across the page is across the bevel's width and down the page is along its
//! height, whichever way the path is drawn, and points past its ends are held to them. Curves are
//! cut into straight lines, at most [`BevelProfile::MAX_POINTS`] points in all. Saving the file
//! reloads the bevels. An effect that uses a custom bevel carries a copy of its points
//! (`bevelProfile`), so its document draws it anywhere.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol};
use vectorcraft_geom::{Affine, PathData, PathEl, Point, SubPath};
use vectorcraft_render::effects::{BEVEL_NAME, BEVEL_PROFILE, BevelProfile};
use super::arrowheads::{may_reach, read, same_file, shown_error};
use super::{CommandSpec, Result, Session, always, bad, cmd};
/// The bevels file's name, in the folder of the preferences.
pub const FILE_NAME: &str = "Bevels.vectorcraft";
/// The most bevels read from the file; symbols past it are skipped.
pub const MAX_BEVELS: usize = 256;
/// The most anchors a bevel's path may have; a symbol past it is skipped.
pub const MAX_ANCHORS: usize = 4096;
/// The most points a bevel's path is cut into before it is simplified; a symbol past it is skipped.
pub const MAX_LINE_POINTS: usize = 8192;
/// The most point-to-line distances simplifying the bevels of one file may measure; a symbol that
/// needs more than is left is skipped as too detailed.
pub const MAX_SIMPLIFY_WORK: u64 = 40_000_000;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "threeD.bevels.list",
"Bevels",
[],
None,
"{} → {bevels: [{name (effect.apply and effect.setParams take Extrude & Bevel's and Extrude & Bevel (Classic)'s `bevel` as {custom: name}), points: [[x, y]…] (shares of the bevel's width and height from the cap's edge [0, 0] to the side wall [1, 1])}], file: the bevels file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not bevels, error: why the file could not be read, or null} the custom bevels, listed after the built-in shapes in the Bevel Shape menus",
always,
list
),
cmd!(
"threeD.bevels.edit",
"Edit Bevels",
[],
None,
"{} open the bevels file (a native document next to the preferences; created first with one example bevel when it is missing). Each symbol in it whose art is one open path is one custom bevel named after the symbol: the path runs from its first anchor at the cap's edge to its last at the side wall, across the page across the bevel's width and down the page along its height. Saving the file reloads the bevels → {path, created: whether the file was made now}",
has_file,
edit
),
cmd!(
"threeD.bevels.reload",
"Reload Bevels",
[],
None,
"{} read the bevels file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}",
has_file,
reload
),
]
}
/// A custom bevel: its name and its points, (share of the width, share of the height).
#[derive(Clone, Debug, PartialEq)]
pub struct CustomBevel {
pub name: String,
pub points: Vec<(f64, f64)>,
}
impl CustomBevel {
/// The points as `bevelProfile` holds them.
pub fn profile_json(&self) -> Value {
json!(self.points.iter().map(|&(x, y)| [x, y]).collect::<Vec<_>>())
}
}
/// The custom bevels read from the bevels file.
#[derive(Default)]
pub struct Bevels {
path: Option<String>,
bevels: Vec<Arc<CustomBevel>>,
skipped: Vec<(String, String)>,
error: Option<String>,
}
impl Bevels {
/// The bevels file's path; `None` without one (the web, runs without preferences).
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
/// The bevels, in the order of the file's symbols.
pub fn bevels(&self) -> &[Arc<CustomBevel>] {
&self.bevels
}
/// Bevel `name`.
pub fn get(&self, name: &str) -> Option<Arc<CustomBevel>> {
self.bevels.iter().find(|b| b.name == name).cloned()
}
fn set(&mut self, read: Read) {
(self.bevels, self.skipped) = (read.bevels.into_iter().map(Arc::new).collect(), read.skipped);
self.error = None;
}
}
/// The bevels a document holds, and the symbols that are not bevels with the reason.
#[derive(Debug, Default)]
pub struct Read {
pub bevels: Vec<CustomBevel>,
pub skipped: Vec<(String, String)>,
}
/// The bevels of document `doc`: one per symbol, up to [`MAX_BEVELS`] (see the module docs).
pub fn bevels_of(doc: &Document) -> Read {
bevels_within(doc, MAX_SIMPLIFY_WORK)
}
/// [`bevels_of`] with `work` point-to-line distances to simplify the paths with.
pub fn bevels_within(doc: &Document, mut work: u64) -> Read {
let mut out = Read::default();
for (i, sym) in doc.symbols.iter().enumerate() {
if i >= MAX_BEVELS {
out.skipped.push((sym.name.clone(), format!("only the first {MAX_BEVELS} symbols are read")));
continue;
}
if out.bevels.iter().any(|b| b.name == sym.name) {
out.skipped.push((sym.name.clone(), "another symbol has this name".into()));
continue;
}
match points_of(&sym.art, &mut work) {
Ok(points) => out.bevels.push(CustomBevel { name: sym.name.clone(), points }),
Err(why) => out.skipped.push((sym.name.clone(), why.into())),
}
}
out
}
/// The one open path of art `n`: `n` itself, or the one member of groups that hold one member each.
fn open_path(n: &Node) -> Option<&PathData> {
match &n.kind {
NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1 && !path.subpaths[0].closed => Some(path),
NodeKind::Group { children, clip: false } if children.len() == 1 => open_path(&children[0]),
_ => None,
}
}
/// The profile points of a bevel symbol's art `n` (see the module docs), simplified within `work`
/// point-to-line distances, which it uses up.
fn points_of(n: &Node, work: &mut u64) -> std::result::Result<Vec<(f64, f64)>, &'static str> {
let path = open_path(n).ok_or("its art is not one open path")?;
if path.anchor_count() > MAX_ANCHORS {
return Err("its path has too many anchors for a bevel");
}
let mut line: Vec<Point> = vec![];
let tolerance = path.bounds().map_or(1.0, |b| b.width().hypot(b.height()) / 2000.0).max(1e-9);
// One segment at a time, so a path past the limit stops being cut at the segment that passes it.
let mut at: Option<Point> = None;
for &el in path.to_bezpath().elements() {
if line.len() > MAX_LINE_POINTS {
return Err("its path is too detailed for a bevel");
}
match (el, at) {
(PathEl::MoveTo(p), _) => line.push(p),
(_, Some(start)) => vectorcraft_geom::flatten([PathEl::MoveTo(start), el], tolerance, |e| {
if let PathEl::LineTo(p) = e {
line.push(p);
}
}),
(_, None) => {}
}
at = el.end_point().or(at);
}
if line.len() > MAX_LINE_POINTS {
return Err("its path is too detailed for a bevel");
}
let (Some(&first), Some(&last)) = (line.first(), line.last()) else { return Err("its path has no length") };
let (dx, dy) = (last.x - first.x, last.y - first.y);
let size = path.bounds().map_or(0.0, |b| b.width().hypot(b.height()));
if !(dx.abs() > size * 1e-6 && dy.abs() > size * 1e-6 && size.is_finite()) {
return Err("its ends are not apart both across and down");
}
let mut pts: Vec<(f64, f64)> = line.iter().map(|p| (((p.x - first.x) / dx).clamp(0.0, 1.0), ((p.y - first.y) / dy).clamp(0.0, 1.0))).collect();
pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9);
if pts.len() < 2 {
return Err("its ends are not apart both across and down");
}
// The ends map to the corners exactly.
let last = pts.len() - 1;
(pts[0], pts[last]) = ((0.0, 0.0), (1.0, 1.0));
let pts = simplified(&pts, work).ok_or("its path is too detailed for a bevel")?;
BevelProfile::new(&pts).ok_or("its path is too detailed for a bevel")?;
Ok(pts)
}
/// `pts` with the fewest points the Ramer-Douglas-Peucker rule keeps at a tolerance (from a
/// thousandth of the bevel, doubled until they fit) that leaves at most
/// [`BevelProfile::MAX_POINTS`]. The first and last points are always kept. `None` when that
/// measures more point-to-line distances than `work` has left.
fn simplified(pts: &[(f64, f64)], work: &mut u64) -> Option<Vec<(f64, f64)>> {
let mut eps = 1e-3;
loop {
let out = rdp(pts, eps, work)?;
if out.len() <= BevelProfile::MAX_POINTS || eps > 2.0 {
return Some(out);
}
eps *= 2.0;
}
}
/// The points of `pts` Ramer-Douglas-Peucker keeps at tolerance `eps`; `None` when that measures
/// more point-to-line distances than `work` has left.
fn rdp(pts: &[(f64, f64)], eps: f64, work: &mut u64) -> Option<Vec<(f64, f64)>> {
if pts.len() < 3 {
return Some(pts.to_vec());
}
let mut keep = vec![false; pts.len()];
keep[0] = true;
keep[pts.len() - 1] = true;
let mut stack = vec![(0, pts.len() - 1)];
while let Some((a, b)) = stack.pop() {
*work = work.checked_sub((b - a).saturating_sub(1) as u64)?;
let (p, q) = (pts[a], pts[b]);
let (vx, vy) = (q.0 - p.0, q.1 - p.1);
let len = vx.hypot(vy);
let far = (a + 1..b)
.map(|i| {
let (wx, wy) = (pts[i].0 - p.0, pts[i].1 - p.1);
let d = if len > 0.0 { (vx * wy - vy * wx).abs() / len } else { wx.hypot(wy) };
(i, d)
})
.fold(None, |best: Option<(usize, f64)>, (i, d)| if best.is_none_or(|(_, bd)| d > bd) { Some((i, d)) } else { best });
if let Some((i, d)) = far
&& d > eps
{
keep[i] = true;
stack.push((a, i));
stack.push((i, b));
}
}
Some(pts.iter().zip(keep).filter_map(|(p, k)| k.then_some(*p)).collect())
}
/// The document a missing bevels file starts as: one example bevel, a chamfer with a notch.
pub fn starter() -> Document {
let mut doc = Document::new(612.0, 792.0);
doc.title = "Bevels".into();
let name = "Example Bevel";
let pts = [Point::new(0.0, 0.0), Point::new(10.0, 40.0), Point::new(55.0, 30.0), Point::new(100.0, 100.0)];
let art =
Node::path(NodeId(0), PathData::single(SubPath::polyline(&pts, false)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
let art = doc.reid(&art);
doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false });
let id = doc.alloc_id();
let instance = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate((256.0, 346.0)) });
let layer = doc.layers.first().map(|l| l.id);
let _ = doc.insert(layer, 0, instance);
doc
}
impl Session {
/// Keep the custom bevels in the file at `path` and read the bevels it holds (none while it is
/// missing; an unreadable file is reported by `threeD.bevels.list`).
pub fn attach_bevels_file(&mut self, path: String) {
self.bevels.path = Some(path);
self.reload_bevels();
}
/// Read the bevels file again.
fn reload_bevels(&mut self) {
let Some(path) = self.bevels.path.clone() else { return };
match read(&path) {
Ok(Some(doc)) => self.bevels.set(bevels_of(&doc)),
Ok(None) => self.bevels.set(Read::default()),
Err(e) => {
self.bevels.set(Read::default());
self.bevels.error = Some(e);
}
}
}
/// A document was saved to `path`: when that is the bevels file, its bevels are read back from
/// what was written.
pub(crate) fn bevels_saved(&mut self, path: &str) {
if self.bevels.path.as_deref().is_some_and(|b| same_file(b, path)) {
self.reload_bevels();
}
}
}
/// The command parameter that holds the points a custom bevel given by name had when the command
/// ran. The journal records it, so a replay draws the same bevel after the bevels file changes or
/// loses that name.
pub const SAVED_BEVEL: &str = "savedBevel";
/// `params` of an effect with `bevel` given as `{custom: name}`: the bevel of the bevels file named
/// so, stored as `bevel` `"custom"` with its `bevelName` and `bevelProfile`. The command's
/// [`SAVED_BEVEL`] points (`p`), when given, are used in place of the file's, and the points used
/// join the journal entry as [`SAVED_BEVEL`]. Other values are left for the effect to check.
pub(crate) fn resolve_custom(s: &mut Session, p: &Value, params: &mut Value, cmd: &str) -> Result<()> {
let Some(Value::Object(o)) = params.get("bevel") else { return Ok(()) };
let name = match (o.len(), o.get("custom")) {
(1, Some(Value::String(name))) => name.clone(),
_ => return Err(bad(cmd, "bevel: give a shape id, or {custom: name} for a bevel of the bevels file (threeD.bevels.list)")),
};
let points = match p.get(SAVED_BEVEL).filter(|v| !v.is_null()) {
Some(saved) => saved.clone(),
None => s.bevels.get(&name).ok_or_else(|| bad(cmd, format!("no custom bevel {name} (see threeD.bevels.list)")))?.profile_json(),
};
s.note_journal(SAVED_BEVEL, points.clone());
params["bevel"] = json!("custom");
params[BEVEL_NAME] = json!(name);
params[BEVEL_PROFILE] = points;
Ok(())
}
fn has_file(s: &Session) -> std::result::Result<(), String> {
if s.bevels.path.is_some() { Ok(()) } else { Err("no bevels file here".into()) }
}
fn skipped(s: &Session) -> Vec<Value> {
s.bevels.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect()
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let bevels: Vec<Value> = s.bevels.bevels.iter().map(|b| json!({"name": b.name, "points": b.profile_json()})).collect();
// Under automation read roots, a file outside them is not shown and its error names it by its file name.
let path = s.bevels.path.as_deref();
let file = path.filter(|p| crate::file_access::check_read(p).is_ok());
let error = s.bevels.error.as_deref().map(|e| shown_error(e, path));
Ok(json!({"bevels": bevels, "file": file, "skipped": skipped(s), "error": error}))
}
fn reload(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "threeD.bevels.reload";
if let Some(path) = &s.bevels.path {
may_reach(path)?;
}
s.reload_bevels();
if let Some(e) = &s.bevels.error {
return Err(bad(C, e.clone()));
}
Ok(json!({"count": s.bevels.bevels.len(), "skipped": skipped(s)}))
}
fn edit(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "threeD.bevels.edit";
let path = s.bevels.path.clone().ok_or_else(|| bad(C, "no bevels file here"))?;
// Checked before anything is made, brought to the front or opened.
may_reach(&path)?;
if let Some(dir) = std::path::Path::new(&path).parent() {
let dir = dir.to_string_lossy();
std::fs::create_dir_all(&*dir).map_err(|e| super::fileio::naming_in_error(bad(C, format!("{dir}: {e}")), &dir))?;
}
// Made only when no file is there, also when another run makes one at the same moment.
let bytes = vectorcraft_format::save_file(&starter());
let created = match crate::file_access::unconfined(|| super::fileio::write_new_file(&path, &bytes)) {
Ok(()) => true,
Err(_) if std::path::Path::new(&path).exists() => false,
Err(e) => return Err(bad(C, e.to_string())),
};
if created {
s.reload_bevels();
}
// Already open: that document comes to the front.
let open = s.documents().iter().position(|st| st.path.as_deref().is_some_and(|p| same_file(p, &path)));
match open {
Some(i) => {
s.set_active(i);
}
None => {
// Opened in the request's own scope, so the document keeps the roots it was opened under.
s.execute("document.open", &json!({ "path": path }))?;
}
}
Ok(json!({"path": path, "created": created}))
}
+42
View File
@@ -177,6 +177,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
@@ -690,6 +691,47 @@ fn pattern_borders() -> BrushLibrary {
built("Pattern Borders", Document::new(100.0, 100.0), brushes)
}
/// Decorative: repeating plant, flower and hanging ornaments drawn as original vector tiles.
/// Every tile joins the next at x = 0 and 48 so open and closed paths stay continuous.
fn decorative() -> BrushLibrary {
let stem = || black(shapes::rectangle(Rect::new(0.0, -0.65, 48.0, 0.65)));
let vine = group(vec![
stem(),
black(polygon(&[(8.0, -0.2), (12.0, -5.0), (24.0, -8.0), (20.0, -1.0)])),
black(polygon(&[(28.0, 0.2), (32.0, 5.0), (44.0, 8.0), (40.0, 1.0)])),
]);
let mut blossoms = vec![stem()];
for x in [12.0, 36.0] {
for (dx, dy) in [(0.0, -4.0), (4.0, 0.0), (0.0, 4.0), (-4.0, 0.0)] {
blossoms.push(black(shapes::ellipse(Rect::new(x + dx - 2.5, dy - 2.5, x + dx + 2.5, dy + 2.5))));
}
blossoms.push(black(shapes::ellipse(Rect::new(x - 1.3, -1.3, x + 1.3, 1.3))));
}
let flowers = group(blossoms);
let pennants = group(vec![
black(shapes::rectangle(Rect::new(0.0, -5.2, 48.0, -4.2))),
black(polygon(&[(4.0, -4.2), (20.0, -4.2), (12.0, 10.0)])),
black(polygon(&[(28.0, -4.2), (44.0, -4.2), (36.0, 10.0)])),
]);
let lanterns = group(vec![
black(shapes::rectangle(Rect::new(0.0, -5.0, 48.0, -4.0))),
black(shapes::rectangle(Rect::new(11.4, -4.0, 12.6, -1.0))),
black(shapes::ellipse(Rect::new(7.0, -1.0, 17.0, 9.0))),
black(shapes::rectangle(Rect::new(35.4, -4.0, 36.6, -1.0))),
black(shapes::ellipse(Rect::new(31.0, -1.0, 41.0, 9.0))),
]);
built(
"Decorative",
Document::new(100.0, 100.0),
vec![
border("Leaf Vine", vine, None, PatternFit::Stretch),
border("Blossom Chain", flowers, None, PatternFit::Stretch),
border("Pennant Garland", pennants, None, PatternFit::Stretch),
border("Lantern String", lanterns, None, PatternFit::Stretch),
],
)
}
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
}
+15 -2
View File
@@ -52,7 +52,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Apply Effect",
[],
None,
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (with params bevel {custom: name}: the custom bevel's points, used in place of the bevels file's; the journal records them so a replay draws the same bevel after the file changes)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
has_doc,
apply
),
@@ -79,7 +79,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Effect Options",
[],
None,
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} → {ids}",
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}",
has_doc,
set_params
),
@@ -496,6 +496,10 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
if texture_load_effect(id) {
load_texture(&mut params, C)?;
}
// A custom bevel by name takes a copy of its points from the bevels file.
if bevel_effect(id) {
super::bevels::resolve_custom(s, p, &mut params, C)?;
}
// An SVG filter needs its <filter> element, and is named by its id.
if id == effects::SVG_FILTER {
let xml = params.get("xml").and_then(Value::as_str).ok_or_else(|| bad(C, "give `xml`, one SVG <filter> element"))?;
@@ -818,6 +822,9 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
if edited.iter().any(|e| texture_load_effect(e)) {
load_texture(&mut params, C)?;
}
if edited.iter().any(|e| bevel_effect(e)) || kind == Some(effects::EXTRUDE) {
super::bevels::resolve_custom(s, p, &mut params, C)?;
}
let targets = effect_targets(s, p, item, index, C)?;
// The type each 3D effect already has, with nothing else to change, is no edit (and is not
// checked again).
@@ -910,6 +917,12 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids_json(&ids) }))
}
/// Does effect `id` take a `bevel` (Extrude & Bevel, Extrude & Bevel (Classic)), which may be a
/// custom bevel given by name?
fn bevel_effect(id: &str) -> bool {
id == effects::EXTRUDE || id == effects::CLASSIC_EXTRUDE
}
/// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder
/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale
+3 -1
View File
@@ -1193,7 +1193,8 @@ impl SaveJob {
}
// The other open documents that place this one show the new version.
let written = self.plan.path.clone().filter(|_| matches!(self.plan.format.id, "vectorcraft" | "template"));
// A save of the arrowheads file lists its heads in the arrowhead menus.
// A save of the arrowheads file lists its heads in the arrowhead menus, and one of the
// bevels file its bevels in the Bevel Shape menus.
let native = self.plan.format.id == "vectorcraft";
if let Some(st) = s.document_mut(uid) {
self.finish(st);
@@ -1204,6 +1205,7 @@ impl SaveJob {
if let Some(path) = written {
if native {
s.arrowheads_saved(&path);
s.bevels_saved(&path);
}
crate::cmd::links::refresh_placed(s, uid, &path);
}
+1 -1
View File
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+20 -6
View File
@@ -124,7 +124,7 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live
}
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii"], "object.setLiveShape")?;
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
let items = match p.get("items").filter(|v| !v.is_null()) {
@@ -235,6 +235,13 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// When every value given is the current one, the document and its undo history stay as they
// are.
let st = s.doc()?;
// `rectanglesOnly`: the live rectangles among the targets; the other objects stay as they are.
let ids: Vec<NodeId> = if p.get("rectanglesOnly").and_then(Value::as_bool) == Some(true) {
let rectangle = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Path { live: Some(l), .. }) if matches!(**l, LiveShape::Rectangle { .. }));
ids.into_iter().filter(rectangle).collect()
} else {
ids
};
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
// past the document's coordinate limit is an error before anything changes.
let mut lines = std::collections::BTreeMap::new();
@@ -278,16 +285,23 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
}
let Some(c) = LiveCorners::new(path, live.as_deref()) else { return true };
let picked = corners_of(*id).unwrap_or_else(|| c.picked(st.selection.anchors.get(id)));
// Setting corners folds a scale left in a rectangle's transform into its size, which
// changes it.
live.as_deref().is_none_or(|l| l.folded() == *l)
// Setting a radius folds a scale left in a rectangle's transform into its size, which
// changes it. A kind the corners already have leaves the rectangle as it is.
(radius.is_none() || live.as_deref().is_none_or(|l| l.folded() == *l))
&& picked.iter().all(|k| {
*k < c.base.anchor_count()
&& radius.is_none_or(|r| (c.drawn_radius(*k) - r.max(0.0)).abs() < 1e-9)
// A radius stored in document units can be larger than it draws; a relative
// one is a fraction, so it is compared as drawn.
&& radius.is_none_or(|r| {
let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) };
(now - r.max(0.0)).abs() < 1e-9
})
&& kind.is_none_or(|kd| c.kind(*k) == kd)
})
};
if ids.iter().all(has_values) {
// The objects every value given already matches stay as they are, beside others that change.
let ids: Vec<NodeId> = ids.into_iter().filter(|id| !has_values(id)).collect();
if ids.is_empty() {
return ok();
}
s.edit("Live Shape", |d, sel| {
+3 -2
View File
@@ -582,8 +582,9 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> {
/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number
/// and a Gaussian Blur's `linear` is true or false. A Pathfinder effect's `precision` is a number and
/// its `removeRedundantPoints` and `removeUnpainted` are true or false. A Glass, Texturizer or Rough
/// Pastels `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of
/// Crop Marks have checks of their own; they aren't listed.
/// Pastels `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version`, the `style` of Crop
/// Marks and an Extrude & Bevel's custom `bevelName` and `bevelProfile` have checks of their own;
/// they aren't listed.
pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
use vectorcraft_render::effects;
let number = || Some(Value::from(0.0));
@@ -746,5 +746,7 @@ pub(super) const DENIED: &[&str] = &[
"stroke.arrowheads.edit",
"stroke.arrowheads.list",
"text.similarFonts",
"threeD.bevels.edit",
"threeD.bevels.list",
"type.compositeFonts.set",
];
+740 -37
View File
@@ -10,9 +10,11 @@
//! path, inside groups too) is compared with the glyphs of the candidate fonts
//! ([`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. Shapes that match no font stay as
//! they are and are reported. Near matches (another version of the font, simplified outlines,
//! merged glyphs) and images are phase 2.
//! 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`]), 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. Near matches (another version of the
//! font, simplified outlines, merged glyphs) and images are phase 2.
use std::f64::consts::{PI, TAU};
use std::sync::Arc;
@@ -39,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…]} 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 (exact matches only); 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 splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); 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}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
"{fonts?: [family…]} 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 (exact matches only); 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 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); 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)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
has_selected_path,
retype
)]
@@ -163,8 +165,11 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vecto
}
/// One line of retyped glyphs.
#[derive(Clone)]
struct Line {
pieces: Vec<NodeId>,
/// Tracking in 1/1000 em, added after each character, spaces included.
tracking: f64,
/// What each piece matched, as `pieces`.
matches: Vec<GlyphMatch>,
/// Every glyph the first piece fits, while the line holds only it: the next glyph may tell
@@ -204,16 +209,53 @@ impl Line {
// Wrapped: type turned 180° has angles near +π and −π.
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
&& across < size * 0.05
&& (m.origin - self.end).dot(dir) > -size * 0.25
// After the line's end, or, for type tracked tighter than that, still ahead of the
// last glyph's start (by more than rounding); the layout check decides whether it fits.
&& ((m.origin - self.end).dot(dir) > -size * 0.25
|| self.matches.last().is_some_and(|last| (m.origin - last.origin).dot(dir) > size * 1e-3))
}
fn size(&self) -> f64 {
self.scale * self.face.units_per_em()
}
/// The shapes of the one-contour glyphs that stand alone on this line: neither the glyph before
/// nor the one after continues it by starting after the end of the glyph before it. A glyph
/// that joined the line only through the tight-tracking test counts as alone. A line of three
/// glyphs or more is type (its tracking can be read), so none of its glyphs is alone.
fn lone_one_contour(&self) -> Vec<NodeId> {
if self.matches.len() >= 3 {
return vec![];
}
let dir = self.dir();
let size = self.size();
// Does glyph `k` start after the end of the glyph before it, less a quarter em?
let after_previous = |k: usize| match (k.checked_sub(1).and_then(|j| self.matches.get(j)), self.matches.get(k)) {
(Some(a), Some(b)) => (b.origin - (a.origin + dir * (a.face.advance(a.gid) * a.scale))).dot(dir) > -size * 0.25,
_ => false,
};
let n = self.matches.len();
(0..n)
.filter(|&k| !after_previous(k) && !after_previous(k + 1))
.filter_map(|k| self.matches.get(k).filter(|m| m.contours == 1).and_then(|_| self.pieces.get(k).copied()))
.collect()
}
/// The line's tracking in points.
fn tracking_pt(&self) -> f64 {
self.tracking * self.size() / 1000.0
}
fn push(&mut self, id: NodeId, m: &GlyphMatch) {
// A gap wider than half a space before the glyph is spaces the outlines left no shape for.
// A gap, past the tracking, wider than half a space before the glyph is spaces the
// outlines left no shape for. Each space takes the tracking too.
let dir = self.dir();
let gap = (m.origin - self.end).dot(dir);
let space = space_advance(&self.face) * self.scale;
if space > 0.0 && gap > space * 0.5 {
let n = ((gap / space).round() as usize).clamp(1, 64);
let gap = (m.origin - self.end).dot(dir) - self.tracking_pt();
// Tracking tighter than a space's width gives each space a negative advance.
let space = space_advance(&self.face) * self.scale + self.tracking_pt();
let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 };
if spaces.is_finite() && spaces > 0.5 {
let n = (spaces.round() as usize).clamp(1, 64);
self.text.extend(std::iter::repeat_n(' ', n));
}
self.text.push(m.ch);
@@ -222,13 +264,49 @@ impl Line {
self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale);
}
/// The line of this one's glyphs `from..to`, with its group, paint and transparency.
/// The line of this one's glyphs `from..to`, with its group, paint, transparency, tracking and
/// the spaces between those glyphs.
fn part(&self, from: usize, to: usize) -> Option<Line> {
let mut text = String::new();
let mut glyph = 0usize;
for c in self.text.chars() {
// The text after glyph `to - 1` is not read.
if glyph >= to {
break;
}
if c == ' ' {
// Spaces before glyph `glyph`, after glyph `glyph - 1`.
if glyph > from {
text.push(c);
}
continue;
}
if glyph >= from {
text.push(c);
}
glyph += 1;
}
if glyph != to || to > self.matches.len() {
return self.respaced(from, to, self.tracking);
}
let mut l = self.respaced(from, to.min(from.saturating_add(1)), self.tracking)?;
l.pieces = self.pieces.get(from..to)?.to_vec();
l.matches = self.matches.get(from..to)?.to_vec();
let last = l.matches.last()?;
l.end = last.origin + l.dir() * (last.face.advance(last.gid) * last.scale);
l.text = text;
Some(l)
}
/// The line of this one's glyphs `from..to` at `tracking`, with its group, paint and
/// transparency, its spaces read again from the gaps at that tracking.
fn respaced(&self, from: usize, to: usize, tracking: f64) -> Option<Line> {
let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?);
let (first, m) = (ids.first()?, ms.first()?);
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
let mut l = Line {
pieces: vec![*first],
tracking,
matches: vec![m.clone()],
first_cands: vec![],
text: m.ch.to_string(),
@@ -248,8 +326,8 @@ impl Line {
Some(l)
}
/// The point type that sets this line.
fn text_object(&self, system_layout: bool) -> TextObject {
/// The point type that sets this line, not yet laid out (for a layout check).
fn probe(&self, system_layout: bool) -> TextObject {
let style = CharStyle {
font_family: self.face.family.clone(),
font_style: self.face.style.clone(),
@@ -258,6 +336,7 @@ impl Line {
// Each outlined glyph was drawn on its own; a ligature would draw another shape.
features: vec!["-liga".into()],
size: self.scale * self.face.units_per_em(),
tracking: self.tracking,
fill: self.appearance.fill_paint(),
stroke: self.appearance.stroke_paint(),
stroke_width: self.appearance.stroke_width(),
@@ -277,6 +356,12 @@ impl Line {
}
t.para = super::create::new_type_para();
t.system_layout = system_layout;
t
}
/// The point type that sets this line, laid out and measured.
fn text_object(&self, system_layout: bool) -> TextObject {
let mut t = self.probe(system_layout);
super::typecmd::refresh_bounds(&mut t);
t
}
@@ -285,27 +370,262 @@ 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<usize> {
let lay = vectorcraft_text::layout(FontDb::global(), t);
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01);
for (k, m) in self.matches.iter().enumerate() {
let Some(g) = drawn.next() else { return Some(k) };
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);
first_mismatch(t, &self.matches, self.size())
}
/// 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.
/// The glyphs are laid out untracked and without spaces, so each gap's extra is how much
/// further apart the outlines are than the font's advances and pair kerning set them; a gap
/// read as word spaces is measured from the glyph's own advance instead, as no pair kerning
/// crosses a space. The extra most gaps share (the lower median, so that the word spaces of a
/// few gaps do not count) places the word spaces; the tracking is then the lower median, over
/// the gaps, of each gap's extra less its spaces, per character. The upper median of the
/// extras is tried next, for a line whose word spaces are its tighter gaps, and last the lower
/// median less one space, halved, for a line most of whose gaps hold a word space. A tracking within
/// 0.05 of a whole number is tried rounded to it first, then as measured. A tracked line is
/// kept when its type draws the whole line in place, or more of it from its start than
/// untracked type does. When untracked type with the spaces also draws the whole line, the line stays
/// untracked if the tracking is under one unit or the tracked reading drops a gap untracked
/// type reads as one space. The line also stays as it is when its tracking is 0 or outside
/// -1000..10000, and when its tracking is negative and the line does not paint the same as one
/// object ([`paints_as_one`]: its glyphs may overlap). Each of the nine layouts at most takes
/// its characters, spaces included, from `budget` before it runs; without enough left, the
/// line stays as it is, or becomes the best tracked reading laid out before the budget ran out.
fn tracked(self, system_layout: bool, budget: &mut usize) -> Line {
let size = self.size();
let n = self.pieces.len();
if n < 3 || size <= 0.0 {
return self;
}
// Each layout takes its characters, spaces included, from `budget` before it runs.
let mut take = |text: &str| match budget.checked_sub(text.chars().count()) {
Some(left) => {
*budget = left;
true
}
None => false,
};
if !take(&self.text) {
return self;
}
let plain_miss = self.first_mismatch(&self.probe(system_layout));
let dir = self.dir();
// Where untracked type draws the glyphs of `text` (each layout dropped once read).
let mut bare = self.clone();
bare.tracking = 0.0;
let mut origins = |text: String| -> Vec<Point> {
bare.text = text;
let t = bare.probe(system_layout);
let lay = vectorcraft_text::layout(FontDb::global(), &t);
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect()
};
// With no spaces.
let joined: String = self.matches.iter().map(|m| m.ch).collect();
if !take(&joined) {
return self;
}
let drawn = origins(joined);
if drawn.len() != n {
return self;
}
// And with one space between each two glyphs (kerning against the space included).
let spaced = self.matches.iter().map(|m| m.ch.to_string()).collect::<Vec<_>>().join(" ");
if !take(&spaced) {
return self;
}
let drawn_spaced = origins(spaced);
// A font whose space has ink draws more glyphs: then the glyph's own advance stands in.
let spaced_ok = drawn_spaced.len() == n;
let space = space_advance(&self.face) * self.scale;
// Each gap's extra over the joined pair, and over the pair with one space between them
// plus a space (so the extra counts the spaces as the joined pair's extra counts none).
let gaps: Vec<(f64, f64)> = self
.matches
.windows(2)
.enumerate()
.zip(drawn.windows(2))
.filter_map(|((i, m), p)| match (m, p) {
([a, b], [pa, pb]) => {
let d = (b.origin - a.origin).dot(dir);
let apart = match (spaced_ok, drawn_spaced.get(i), drawn_spaced.get(i + 1)) {
(true, Some(qa), Some(qb)) => d - (*qb - *qa).dot(dir) + space,
_ => d - a.face.advance(a.gid) * a.scale,
};
Some((d - (*pb - *pa).dot(dir), apart))
}
_ => None,
})
.collect();
let extra: Vec<f64> = gaps.iter().map(|g| g.0).collect();
// The spaces in each gap at a tracking of `tr` points: each space takes the tracking too,
// and tracking tighter than a space's width gives it a negative advance. A gap reads as
// spaces when they fit it better than the joined pair does.
let spaces = |tr: f64| -> Vec<usize> {
gaps.iter()
.map(|(joined, apart)| {
let step = space + tr;
// Spaces with no advance: one space, which still breaks the pair's kerning.
let s = if step.abs() > 1e-9 { (apart - tr) / step } else { 1.0 };
if !s.is_finite() {
return 0;
}
// At least one space: the space's own kerning can make it fit a narrower gap.
let k = (s.round().max(1.0) as usize).clamp(1, 64);
// Spaces only where they fit better by more than rounding (1/100,000 em).
if (apart - tr - k as f64 * step).abs() + size * 1e-5 < (joined - tr).abs() { k } else { 0 }
})
.collect()
};
// The tracking the gaps give when the word spaces are placed by `seed`.
let measure = |seed: f64| -> Option<f64> {
let per: Vec<f64> = gaps
.iter()
.zip(spaces(seed))
.map(|((joined, apart), s)| if s == 0 { *joined } else { (apart - s as f64 * space) / (s + 1) as f64 })
.collect();
median(per, false).map(|g| g / size * 1000.0)
};
// The lower median of the extras places the word spaces first; the upper one second, for a
// line whose word spaces are its tighter gaps (tracking tighter than a space).
let lower = median(extra.clone(), false);
// A line whose word gaps are most of its gaps has a space and two trackings in each extra
// (tracking is added after the glyph and after the space): the seed then places the spaces
// from the extra less one space, shared by the two. It goes last, so a reading that fits
// without it is kept (an untracked "a b c" has no such tracking).
// Where untracked type already draws the whole line, a space and a tracking of half its
// advance less draw it too: that reading is not tried.
let spaced_seed = lower.filter(|_| plain_miss.is_some()).map(|e| (e - space) / 2.0);
let mut tries = vec![];
for seed in [lower, median(extra, true), spaced_seed].into_iter().flatten() {
let Some(measured) = measure(seed) else { continue };
for t in [round_tracking(measured), measured] {
if !tries.contains(&t) {
tries.push(t);
}
}
}
// Ink the outlines did not have: the last glyph is where it went wrong.
drawn.next().map(|_| self.matches.len().saturating_sub(1))
// The spaces in each gap of the line as it is (the reading `plain_miss` checked).
let mut plain_gaps = vec![];
let mut run = 0usize;
for (i, c) in self.text.chars().enumerate() {
if c == ' ' {
run += 1;
} else {
if i > 0 {
plain_gaps.push(run);
}
run = 0;
}
}
let mut best: Option<(usize, Line)> = None;
for t in tries {
if t == 0.0 || !TRACKING.contains(&t) {
continue;
}
if t < 0.0 && !paints_as_one(&self) {
return self;
}
let mut tracked = self.clone();
tracked.tracking = t;
tracked.text = String::new();
let gaps = spaces(t * size / 1000.0);
for (k, (m, s)) in self.matches.iter().zip(std::iter::once(0).chain(gaps.iter().copied())).enumerate() {
if k > 0 {
tracked.text.extend(std::iter::repeat_n(' ', s));
}
tracked.text.push(m.ch);
}
// A reading the budget cannot lay out is skipped; the next may be shorter.
if !take(&tracked.text) {
continue;
}
// When both draw the whole line (gaps as wide as whole spaces), the tracked reading is
// kept unless it drops a gap that untracked type reads as one space: such a gap is a
// word space ("a b c"), and the line keeps its spaces.
let drops_a_word_space = plain_gaps.iter().zip(&gaps).any(|(plain, tracked)| *plain == 1 && *tracked == 0);
match (tracked.first_mismatch(&tracked.probe(system_layout)), plain_miss) {
// Under a unit of tracking, or a word space the tracked reading drops, where
// untracked type draws the line: no tracking.
(None, None) if t.abs() < 1.0 || drops_a_word_space => return self,
(None, _) => return tracked,
(Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)),
_ => {}
}
}
best.map_or(self, |(_, l)| l)
}
}
/// Does line `l` paint the same as one object as glyph by glyph where its glyphs overlap: opaque,
/// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and
/// blend once, spans a gradient over all of it, and strokes after filling every glyph.
fn paints_as_one(l: &Line) -> bool {
l.opacity == 1.0
&& l.blend == vectorcraft_color::BlendMode::Normal
&& matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
&& matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None)
}
/// The tracking Retype sets, in 1/1000 em.
const TRACKING: std::ops::RangeInclusive<f64> = -1000.0..=10000.0;
/// The lower median of the finite values of `v`, or the upper one when `upper`; None for fewer
/// than two.
fn median(mut v: Vec<f64>, upper: bool) -> Option<f64> {
v.retain(|x| x.is_finite());
if v.len() < 2 {
return None;
}
v.sort_by(f64::total_cmp);
v.get(if upper { v.len() / 2 } else { (v.len() - 1) / 2 }).copied()
}
/// Tracking `t` rounded to a whole number when it is within 0.05 of one.
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) -> Option<usize> {
let lay = vectorcraft_text::layout(FontDb::global(), t);
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
let tol = (size * 0.01).max(0.01);
for (k, m) in matches.iter().enumerate() {
let Some(g) = drawn.next() else { return Some(k) };
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.
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
// Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot
// leave glyphs unchecked; past it they keep no tracking. Each measure takes the glyphs to
// rebuild the rest and the characters it lays out (see [`Line::tracked`]); the budget covers
// one measure of each whole line, as `retype` gives the first, and the glyph checks' budget.
// The glyphs measured again after splits are limited apart from it, at six times each rest's
// glyphs from half as much again as the glyph checks' budget.
let mut remeasured = budget.saturating_add(budget / 2);
let mut track_budget =
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(394))).fold(budget, usize::saturating_add);
let mut todo: std::collections::VecDeque<Line> = lines.into();
let mut out = vec![];
while let Some(l) = todo.pop_front() {
@@ -323,28 +643,58 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
break;
};
budget = left;
match part.first_mismatch(&part.text_object(system_layout)) {
match part.first_mismatch(&part.probe(system_layout)) {
// The whole line is drawn as it was: one object.
None if e == n => {
out.push(part);
break;
}
None => w = w.saturating_mul(2),
// The first glyph on its own may still be drawn as it was (a contextual form
// changed it in the line); else it stays an outline. Checked again either way.
Some(0) if n > 1 => {
todo.extend_front_parts(&l, [(0, 1), (1, n)]);
// Tracking that type does not set as the outlines are spaced: the line is
// checked again without it.
Some(k) if l.tracking != 0.0 && k < 2 => {
match l.respaced(0, n, 0.0) {
Some(p) => todo.push_front(p),
None => unmatched.extend(l.pieces.iter().copied()),
}
break;
}
Some(0) => {
// A single glyph its type cannot draw as it was stays an outline.
Some(0) if n == 1 => {
unmatched.extend(l.pieces.first().copied());
break;
}
// The glyphs before the mismatch, then the rest, each checked as a line of its
// own: the type before the mismatch may draw otherwise without what follows it (a
// font can place a glyph by the glyph after it).
// font can place a glyph by the glyph after it), and the first glyph on its own
// may still be drawn as it was (a contextual form changed it in the line). The
// rest takes the tracking its own glyphs are spaced by, while the budget for
// measuring it lasts and when type draws its first glyph as it was, followed by the
// next two (else that glyph splits off first, and the tracking is measured from the
// next one); past it, an untracked line's rest keeps its text as it is.
Some(k) => {
todo.extend_front_parts(&l, [(0, k), (k, n)]);
let k = k.max(1);
// A measure takes at least six times the rest's glyphs from each budget.
let measurable = n - k >= 3 && remeasured >= (n - k).saturating_mul(6) && track_budget >= (n - k).saturating_mul(6);
let first_drawn = measurable && {
budget = budget.saturating_sub(3);
l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0))
};
let rest = if first_drawn {
// Rebuilding the rest for the measure takes its glyphs from the budget.
remeasured = remeasured.saturating_sub((n - k).saturating_mul(6));
track_budget = track_budget.saturating_sub(n - k);
l.respaced(k, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget))
} else if l.tracking == 0.0 {
l.part(k, n)
} else {
l.respaced(k, n, 0.0)
};
match rest {
Some(r) => todo.push_front(r),
None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()),
}
todo.extend_front_parts(&l, [(0, k)]);
break;
}
}
@@ -353,6 +703,290 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
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<usize> = 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<TextObject>,
/// The glyphs the type must draw, in order.
matches: Vec<GlyphMatch>,
pieces: Vec<NodeId>,
text: String,
face: Arc<vectorcraft_text::FontFace>,
size: f64,
tracking: f64,
/// The leading set on the type: None for Auto or a single line.
leading: Option<f64>,
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(),
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<Line>,
/// 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<f64>,
}
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<Line> {
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<Made> {
let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::<Vec<_>>();
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::<Vec<_>>().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<GlyphMatch> = 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) {
// 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).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,
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<Line>, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec<Made> {
let mut out = vec![];
let mut block: Option<Block> = 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<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]);
@@ -407,6 +1041,7 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Line {
pieces: vec![id],
tracking: 0.0,
matches: vec![m.clone()],
first_cands: l.first_cands.clone(),
text: m.ch.to_string(),
@@ -428,6 +1063,7 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Some(Line {
pieces: vec![pc.id],
tracking: 0.0,
matches: vec![m.clone()],
first_cands: cands.to_vec(),
text: m.ch.to_string(),
@@ -531,8 +1167,15 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
// art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is
// what was asked for. Lone means alone on its baseline as the outlines lie, before the
// layout check splits lines (tracking and manual kerning split them glyph by glyph).
let lone_pieces: std::collections::HashSet<NodeId> =
lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect();
let lone_pieces: std::collections::HashSet<NodeId> = lines.iter().flat_map(Line::lone_one_contour).collect();
// Each line's tracking is measured with nine layouts at most: the line as read (its
// characters), its glyphs without and with one space between them (three times its
// glyphs) and six tracked readings of at most 64 spaces in each gap (390 times its
// 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 mut lines: Vec<Line> = 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 {
lines.retain(|l| {
@@ -543,20 +1186,29 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
!lone
});
}
(lines, unmatched, truncated)
let at: std::collections::HashMap<NodeId, usize> = 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![];
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;
@@ -603,15 +1255,66 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
// 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).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<NodeId> = 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::<Vec<_>>(),
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
"fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::<Vec<_>>(),
"fonts": lines
.iter()
.zip(&made)
.map(|(l, id)| json!({
"family": l.face.family,
"style": l.face.style,
"size": l.size,
"tracking": l.tracking,
"leading": l.leading,
"area": area(id),
}))
.collect::<Vec<_>>(),
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
"truncated": truncated,
}))
+705 -6
View File
@@ -477,10 +477,10 @@ fn tracked_one_contour_letters_still_become_type() {
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();
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}");
assert!(texts.len() > 1, "the tracking splits the line: {r}");
assert_eq!(r["texts"], json!([text]), "evenly tracked, the line is one object: {r}");
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
assert_eq!(text_of(&s, r["ids"][0].as_u64().unwrap()).first_style().tracking, 50.0);
}
}
@@ -521,8 +521,8 @@ fn timing_with_hundreds_of_cjk_outlines() {
#[test]
fn a_long_tracked_line_is_checked_in_time() {
// Tracking splits the line at every glyph: the layout check must not lay out the rest of the
// line again after each split.
// Even tracking is kept on the line; the layout check of a long line must not lay out the rest
// of the line again after each window.
let text = "abe".repeat(150);
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap();
@@ -533,7 +533,706 @@ fn a_long_tracked_line_is_checked_in_time() {
let t0 = std::time::Instant::now();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.concat(), text);
assert_eq!(texts, vec![text], "the whole line is one object: {r}");
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
assert_eq!(r["unmatched"], json!([]));
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
}
#[test]
fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
// Two M outlines start 0.3 em apart, closer than the first one's advance: a tight-tracking
// line of two, which the layout check splits again. Each is still a lone one-contour glyph.
let mut s = session();
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "M", "size": 30}));
let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30}));
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap();
// Nothing is left to retype: both stay outlines, as the lone bar beside art does.
let e = s.execute("type.retype", &json!({})).unwrap_err();
assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}");
}
/// Where type `t` draws each glyph that has ink, in document space.
fn glyph_places(t: &TextObject) -> Vec<kurbo::Point> {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * kurbo::Point::ORIGIN)).collect()
}
/// Type made with `p` (and `setup` run on its id), outlined and retyped: the original type, and
/// Retype's result.
fn retyped(s: &mut Session, p: serde_json::Value, setup: &[serde_json::Value]) -> (TextObject, serde_json::Value) {
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
for q in setup {
let mut q = q.clone();
q["id"] = json!(id);
s.execute("text.setRangeStyle", &q).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();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
(before, s.execute("type.retype", &json!({})).unwrap())
}
fn assert_same_places(a: &TextObject, b: &TextObject) {
let (pa, pb) = (glyph_places(a), glyph_places(b));
assert_eq!(pa.len(), pb.len());
for (x, y) in pa.iter().zip(&pb) {
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
}
}
#[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<String> = 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<kurbo::Point> = 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();
// Less than half a space more after e: no gap can be read as a word space.
let text = "abcdefgh";
let (before, r) = retyped(
&mut s,
json!({"x": 40, "y": 100, "text": text, "size": 30}),
&[json!({"start": 0, "end": 4, "tracking": 50}), json!({"start": 4, "end": 8, "tracking": 120})],
);
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.concat(), text, "{r}");
assert!(texts.len() > 1, "{r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
// Each object's glyphs are where the outlines were.
let places: Vec<kurbo::Point> = 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 second half keeps its own tracking.
assert_eq!(r["fonts"].as_array().unwrap().last().unwrap()["tracking"], json!(120.0), "{r}");
}
#[test]
fn a_tracked_line_keeps_its_tracking_and_spaces() {
let mut s = session();
let text = "SPACED OUT";
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_long_line_tracked_two_spaces_wide_keeps_its_tracking() {
// Read as it is, the line holds two spaces in each gap, which the tracking measure lays out too.
let mut s = session();
let text = "M".repeat(400);
let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 400})]);
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]);
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{}", r["fonts"]);
}
#[test]
fn a_long_tightly_tracked_line_keeps_its_word_spaces() {
// Read as it is, the line holds no spaces; the tracked reading holds eight in each word gap.
let mut s = session();
let text = vec!["MMM"; 100].join(" ");
let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": -180})]);
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]);
assert_eq!(r["fonts"][0]["tracking"], json!(-180.0), "{}", r["fonts"]);
}
#[test]
fn spaced_letters_keep_their_spaces_when_type_draws_them() {
// Most gaps are word spaces: untracked type with the spaces draws every glyph in place.
// Every gap one word space: tracking a space wide would draw them too, without the spaces.
// L T J: without its spaces the pairs kern, which a measure of the gaps would read as more space.
for text in ["a a a aa", "1 2 3", "a b c d", "x = y + 1", "L T J"] {
let mut s = session();
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
}
#[test]
fn slight_tracking_without_spaces_is_kept() {
// Tracking 3 moves the last glyph less than the layout check notices: both readings draw it.
// A word space both readings keep does not cost the tracking either.
for text in ["MMM", "M MM"] {
let mut s = session();
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": 3})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(3.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
}
/// The lines Retype reads from the outlines in group `g` (all in the face of its first glyph's
/// first match), before their tracking is measured and their layout checked.
fn lines_in(s: &Session, g: u64) -> Vec<super::Line> {
let d = &s.doc().unwrap().doc;
let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]);
super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces);
let db = vectorcraft_text::FontDb::global();
let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted);
let face = index.matches(&pieces[0].path)[0].face.id();
let mut lines: Vec<super::Line> = vec![];
for pc in &pieces {
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
lines.extend(super::new_line(pc, &cands));
}
}
lines
}
#[test]
fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() {
// Glyph `bad` of a tracked line read as another glyph of its font, as when the line's type
// would draw another form there: the glyphs after it are still one tracked object.
for bad in [0usize, 1] {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let lines = lines_in(&s, g);
assert_eq!(lines.len(), 1);
let mut budget = 1000;
let mut l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!(l.tracking, 300.0);
let other = l.matches[bad].gid + 1;
l.matches[bad].gid = other;
let bad_id = l.pieces[bad];
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
assert_eq!(unmatched, vec![bad_id], "{bad}");
let last = out.last().unwrap();
assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
assert_eq!(last.tracking, 300.0, "{bad}");
}
}
#[test]
fn the_tracking_measure_counts_the_spaces_it_lays_out() {
// Three glyphs ten spaces apart: a budget of six times the glyphs, short of the first
// layout's 23 characters, lays nothing out.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "a b c", "size": 30}));
let lines = lines_in(&s, g);
assert_eq!(lines.len(), 1);
assert!(lines[0].text.chars().filter(|c| *c == ' ').count() >= 20, "{}", lines[0].text);
let mut budget = 3 * 6;
let l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!((budget, l.tracking), (3 * 6, 0.0));
}
#[test]
fn the_tracking_measure_needs_only_the_layouts_it_runs() {
// The line as read, without spaces, with one space per gap, then the tracked reading: a
// budget of exactly those characters recovers the tracking.
let mut s = session();
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let lines = lines_in(&s, g);
assert_eq!(lines.len(), 1);
let mut budget = lines[0].text.chars().count() + 6 + 11 + 6;
let l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!((budget, l.tracking), (0, 300.0));
}
#[test]
fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() {
// Tracking 40 spaces wide: read untracked, the rest after the split holds 40 spaces per gap,
// and its measure still has the budget to lay them out.
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(100), "size": 2})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 8000})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mut budget = 100_000;
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!(l.tracking, 8000.0);
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
assert_eq!(unmatched.len(), 1);
let last = out.last().unwrap();
assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
}
#[test]
fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() {
// A long tracked line whose first five glyphs are read as other glyphs: the rest is still one
// tracked object.
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mut budget = 1000;
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
assert_eq!(l.tracking, 300.0);
for m in l.matches.iter_mut().take(5) {
m.gid += 1;
}
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
assert_eq!(unmatched.len(), 5);
let last = out.last().unwrap();
assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
}
#[test]
fn tightly_tracked_type_keeps_its_tracking() {
// Tracking tighter than a space: the space moves the next glyph back.
// M MM: of its two gaps, the word space is the tighter, and the lower median.
// M M MM: most gaps hold a word space, so the tightest extras alone seed a tracking that
// splits the last glyph.
for text in ["MMMM", "MMMM MM", "M MM", "MM M", "M M MM"] {
let mut s = session();
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -300})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(-300.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
}
#[test]
fn kerned_pairs_in_tight_tracking_are_not_read_as_spaces() {
// Tracking -250 gives a space a negative advance; the pair kerning of T and a is no space.
let mut s = session();
let text = "MMMTaMMM";
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn a_word_space_between_kerned_letters_is_read_as_a_space() {
// T and a kern when they touch; with a space between them they do not.
let mut s = session();
let text = "MMMT aMMM";
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
// Tracking that cancels the space's advance: the space still stops the pair kerning.
let mut s = session();
let text = "MMMT aMMM";
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -200})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(-200.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
// Tracking that nearly cancels it: the space still moves the glyphs after it a little.
let mut s = session();
let text = "MMMM MM";
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -199.5})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), -199.5, 1e-3), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
// A word space a little narrower than its tracking makes it (the word after it moved left by
// less than the layout check notices): one space still fits better than the kerned pair.
for (tracking, dx) in [(-190, -0.18), (-193, -0.24)] {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMc aMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).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);
assert_eq!(kids.len(), 8);
s.execute("select.set", &json!({"ids": kids[4..]})).unwrap();
s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["MMMc aMMM"]), "{tracking}: {r}");
}
// A space that kerns with the letter after it.
let mut s = session();
let text = "MMMd TMMM";
let p = json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Serif 4", "style": "Regular"});
let (before, r) = retyped(&mut s, p, &[json!({"tracking": -217})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(-217.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn an_untracked_word_is_not_read_as_spaced_letters_in_tight_tracking() {
// Letters, each followed by a space, at tracking of minus half a space, sit where the word's
// letters do.
let mut s = session();
let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "Third", "size": 24}), &[]);
assert_eq!(r["texts"], json!(["Third"]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}");
}
#[test]
fn glyphs_barely_ahead_of_each_other_stay_one_line() {
let mut s = session();
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "MMMM", "size": 30}), &[json!({"tracking": -700})]);
assert_eq!(r["texts"], json!(["MMMM"]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(-700.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn tracking_near_a_whole_number_is_kept_as_measured_when_rounding_moves_glyphs() {
let mut s = session();
let text = "i".repeat(400);
let (before, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 50.04})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), 50.04, 1e-3), "{}", r["fonts"]);
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": -300})).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.edit("test", |d, _| {
for k in &kids {
d.node_mut(NodeId(*k)).unwrap().opacity = 0.5;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// Each glyph composites on its own over the one it overlaps, as the outlines did.
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);
}
+28 -22
View File
@@ -634,34 +634,40 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
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) {
+2
View File
@@ -164,6 +164,8 @@ pub struct Session {
pub brush_libraries: cmd::brushlib::Libraries,
/// The custom arrowheads of the arrowheads file (`stroke.arrowheads.*`); none without one.
pub arrowheads: cmd::arrowheads::Arrowheads,
/// The custom bevels of the bevels file (`threeD.bevels.*`); none without one.
pub bevels: cmd::bevels::Bevels,
/// The id each loaded library outside a request's read roots has been shown under, by its own id
/// ([`cmd::swatchlib::concealed_library_ids`]), kept for the session.
shown_library_ids: std::sync::Mutex<std::collections::BTreeMap<String, String>>,
+1
View File
@@ -90,6 +90,7 @@ impl Session {
symbol_libraries: Default::default(),
brush_libraries: Default::default(),
arrowheads: Default::default(),
bevels: Default::default(),
shown_library_ids: Default::default(),
libraries: Default::default(),
pdf_preset_dir: None,
+1
View File
@@ -15,6 +15,7 @@ mod assets;
mod assets_3d;
mod attributes;
mod bboxrotate;
mod bevels;
mod blendfidelity;
mod blendopts;
mod blendspine;
+394
View File
@@ -0,0 +1,394 @@
//! Custom bevels (`cmd/bevels.rs`): bevels read from the bevels file's symbols, listed, set on
//! Extrude & Bevel and Extrude & Bevel (Classic) by name, reloaded when the file is saved, and kept
//! with the documents that use them.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, Symbol};
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
use vectorcraft_render::effects;
use crate::cmd::bevels::{self, bevels_of};
use crate::*;
fn line(pts: &[(f64, f64)], closed: bool) -> Node {
let pts: Vec<Point> = pts.iter().map(|&(x, y)| Point::new(x, y)).collect();
Node::path(NodeId(0), PathData::single(SubPath::polyline(&pts, closed)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))
}
fn add_symbol(d: &mut Document, name: &str, art: Node) {
let art = d.reid(&art);
d.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false });
}
/// A folder of its own for test `name`, emptied.
fn folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vectorcraft-bevels-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn close(a: (f64, f64), b: (f64, f64)) -> bool {
(a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9
}
#[test]
fn each_open_path_symbol_is_a_bevel_from_its_first_anchor_to_its_last() {
let mut d = Document::new(100.0, 100.0);
add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (20.0, 60.0), (70.0, 40.0), (100.0, 100.0)], false));
// The same path mirrored across the page and drawn from the other side gives the same points.
add_symbol(&mut d, "Mirrored", line(&[(300.0, 50.0), (280.0, 110.0), (230.0, 90.0), (200.0, 150.0)], false));
// In a group of one, at another size.
let small = line(&[(0.0, 0.0), (2.0, 6.0), (7.0, 4.0), (10.0, 10.0)], false);
add_symbol(&mut d, "Grouped", Node::group(NodeId(0), vec![Arc::new(small)]));
// Points past the ends are held to them.
add_symbol(&mut d, "Overshoot", line(&[(0.0, 0.0), (-20.0, 50.0), (100.0, 120.0), (100.0, 100.0)], false));
add_symbol(&mut d, "Closed", line(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], true));
let two = Node::group(NodeId(0), vec![Arc::new(line(&[(0.0, 0.0), (1.0, 1.0)], false)), Arc::new(line(&[(0.0, 0.0), (1.0, 1.0)], false))]);
add_symbol(&mut d, "Two paths", two);
add_symbol(&mut d, "Upright", line(&[(0.0, 0.0), (5.0, 50.0), (0.0, 100.0)], false));
let dense: Vec<(f64, f64)> = (0..=bevels::MAX_ANCHORS).map(|i| (i as f64, i as f64)).collect();
add_symbol(&mut d, "Dense", line(&dense, false));
add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (1.0, 1.0)], false));
let read = bevels_of(&d);
let names: Vec<&str> = read.bevels.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["Notch", "Mirrored", "Grouped", "Overshoot"]);
let notch = [(0.0, 0.0), (0.2, 0.6), (0.7, 0.4), (1.0, 1.0)];
for b in &read.bevels[..3] {
assert_eq!(b.points.len(), 4, "{}", b.name);
assert!(b.points.iter().zip(notch).all(|(&a, b)| close(a, b)), "{}: {:?}", b.name, b.points);
}
assert!(close(read.bevels[3].points[1], (0.0, 0.5)) && close(read.bevels[3].points[2], (1.0, 1.0)), "{:?}", read.bevels[3].points);
let skipped: Vec<(&str, &str)> = read.skipped.iter().map(|(n, r)| (n.as_str(), r.as_str())).collect();
assert_eq!(
skipped,
[
("Closed", "its art is not one open path"),
("Two paths", "its art is not one open path"),
("Upright", "its ends are not apart both across and down"),
("Dense", "its path has too many anchors for a bevel"),
("Notch", "another symbol has this name"),
]
);
}
/// A curve is cut into straight lines, and a path of many points keeps the ones that matter, at
/// most 64 in all, ends included.
#[test]
fn curves_and_long_paths_fit_in_the_points_a_bevel_holds() {
let mut d = Document::new(100.0, 100.0);
// A quarter circle from (0, 0) to (100, 100), bulging up and right.
let k = 0.5523 * 100.0;
let mut a = Anchor::corner(Point::new(0.0, 0.0));
a.h_out = Point::new(k, 0.0);
let mut b = Anchor::corner(Point::new(100.0, 100.0));
b.h_in = Point::new(100.0, 100.0 - k);
let arc = Node::path(NodeId(0), PathData::single(SubPath::new(vec![a, b], false)), Appearance::default());
add_symbol(&mut d, "Arc", arc);
let wavy: Vec<(f64, f64)> = (0..=3000).map(|i| (i as f64 / 30.0, i as f64 / 30.0 + 5.0 * (i as f64 / 50.0).sin())).collect();
add_symbol(&mut d, "Wavy", line(&wavy, false));
let read = bevels_of(&d);
assert!(read.skipped.is_empty(), "{:?}", read.skipped);
for b in &read.bevels {
assert!((3..=effects::BevelProfile::MAX_POINTS).contains(&b.points.len()), "{}: {}", b.name, b.points.len());
assert!(close(b.points[0], (0.0, 0.0)) && close(*b.points.last().unwrap(), (1.0, 1.0)), "{}", b.name);
assert!(effects::BevelProfile::new(&b.points).is_some(), "{}", b.name);
}
// The arc's points lie on the circle: across first, then down.
let arc = &read.bevels[0];
assert!(arc.points.iter().all(|&(x, y)| (((x - 0.0).powi(2) + (y - 1.0).powi(2)).sqrt() - 1.0).abs() < 0.01), "{:?}", arc.points);
}
/// A path of many tall curves, cut into more straight lines than a bevel's path may take, is
/// skipped as too detailed.
#[test]
fn a_path_cut_into_too_many_lines_is_skipped() {
let mut d = Document::new(100.0, 100.0);
let anchors: Vec<Anchor> = (0..4000)
.map(|i| {
let p = Point::new(f64::from(i), f64::from(i) / 4.0);
let swing = if i % 2 == 0 { 1000.0 } else { -1000.0 };
let mut a = Anchor::corner(p);
a.h_in = Point::new(p.x - 0.5, p.y - swing);
a.h_out = Point::new(p.x + 0.5, p.y + swing);
a
})
.collect();
let wild = Node::path(NodeId(0), PathData::single(SubPath::new(anchors, false)), Appearance::default());
add_symbol(&mut d, "Wild", wild);
let read = bevels_of(&d);
assert!(read.bevels.is_empty());
assert_eq!(read.skipped, [("Wild".to_string(), "its path is too detailed for a bevel".to_string())]);
}
/// Simplifying the paths of one file measures at most a fixed number of point-to-line distances:
/// a path that needs more than are left is skipped as too detailed, and a short one still reads.
#[test]
fn simplifying_the_bevels_of_a_file_has_a_work_limit() {
let mut d = Document::new(100.0, 100.0);
let wavy: Vec<(f64, f64)> = (0..=3000).map(|i| (i as f64 / 30.0, i as f64 / 30.0 + 5.0 * (i as f64 / 50.0).sin())).collect();
add_symbol(&mut d, "Wavy", line(&wavy, false));
add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (20.0, 60.0), (70.0, 40.0), (100.0, 100.0)], false));
let read = bevels::bevels_within(&d, 5_000);
let names: Vec<&str> = read.bevels.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["Notch"]);
assert_eq!(read.skipped, [("Wavy".to_string(), "its path is too detailed for a bevel".to_string())]);
assert_eq!(bevels_of(&d).bevels.len(), 2);
}
fn rect(s: &mut Session, x: u32) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap())
}
fn params(s: &Session, id: NodeId) -> Value {
s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone()
}
#[test]
fn the_bevels_file_is_made_opened_and_reloaded_when_saved() {
let dir = folder("edit");
let file = dir.join(bevels::FILE_NAME).to_string_lossy().to_string();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = rect(&mut s, 20);
s.attach_bevels_file(file.clone());
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
assert_eq!((list["bevels"].as_array().unwrap().len(), list["file"].as_str()), (0, Some(file.as_str())));
let apply = json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Example Bevel"}}});
assert!(s.execute("effect.apply", &apply).unwrap_err().to_string().contains("no custom bevel Example Bevel"));
let r = s.execute("threeD.bevels.edit", &json!({})).unwrap();
assert_eq!(r["created"], true);
assert_eq!(s.doc().unwrap().path.as_deref(), Some(file.as_str()), "the file is the active document");
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
assert_eq!(list["bevels"][0]["name"], "Example Bevel");
assert_eq!(list["bevels"][0]["points"].as_array().unwrap().len(), 4);
// A second bevel drawn in the file is listed once the file is saved.
let st = s.doc_mut().unwrap();
add_symbol(Arc::make_mut(&mut st.doc), "Steps", line(&[(0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 100.0), (100.0, 100.0)], false));
assert_eq!(s.execute("threeD.bevels.list", &json!({})).unwrap()["bevels"].as_array().unwrap().len(), 1);
s.execute("document.save", &json!({})).unwrap();
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
let names: Vec<&str> = list["bevels"].as_array().unwrap().iter().filter_map(|b| b["name"].as_str()).collect();
assert_eq!(names, ["Example Bevel", "Steps"]);
assert_eq!(s.execute("threeD.bevels.reload", &json!({})).unwrap()["count"], 2);
// Editing again brings the open file to the front, without making it anew.
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(s.execute("threeD.bevels.edit", &json!({})).unwrap()["created"], false);
assert_eq!(s.documents().len(), 2);
// The rectangle takes the bevel with a copy of its points, in both Extrude & Bevels.
s.execute("document.activate", &json!({"index": 0})).unwrap();
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Steps"}}})).unwrap();
let p = params(&s, id);
assert_eq!((p["bevel"].as_str(), p[effects::BEVEL_NAME].as_str()), (Some("custom"), Some("Steps")));
assert_eq!(p[effects::BEVEL_PROFILE], json!([[0.0, 0.0], [0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [1.0, 1.0]]));
let set = |bevel: Value| json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": bevel}});
s.execute("effect.setParams", &set(json!({"custom": "Example Bevel"}))).unwrap();
assert_eq!(params(&s, id)[effects::BEVEL_NAME], "Example Bevel");
for bad in [json!({"custom": 3}), json!({"custom": "Nope"}), json!({"name": "Steps"})] {
let undo = s.doc().unwrap().history.undo.len();
assert!(s.execute("effect.setParams", &set(bad.clone())).is_err(), "{bad}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{bad}: no undo step");
}
let classic = rect(&mut s, 200);
s.execute(
"effect.apply",
&json!({"effect": effects::CLASSIC_EXTRUDE, "ids": [classic.0], "item": null, "params": {"bevel": {"custom": "Steps"}}}),
)
.unwrap();
assert_eq!(params(&s, classic)[effects::BEVEL_NAME], "Steps");
// A built-in shape again draws that shape.
s.execute("effect.setParams", &set(json!("rounded"))).unwrap();
assert!(matches!(effects::extrude_options(&params(&s, id)).bevel.map(|b| b.shape.id()), Some("rounded")));
let _ = std::fs::remove_dir_all(&dir);
}
/// `effect.apply` and `effect.setParams` given a custom bevel by name record its points as
/// `savedBevel`, so a replay draws that bevel after the bevels file no longer has it.
#[test]
fn a_replay_draws_the_custom_bevel_the_command_recorded() {
let dir = folder("replay");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = rect(&mut s, 20);
s.attach_bevels_file(dir.join(bevels::FILE_NAME).to_string_lossy().to_string());
s.execute("threeD.bevels.edit", &json!({})).unwrap();
s.execute("document.activate", &json!({"index": 0})).unwrap();
let apply = json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Example Bevel"}}});
s.execute("effect.apply", &apply).unwrap();
let applied = params(&s, id);
let (cmd, recorded) = s.journal.last().unwrap().clone();
assert_eq!(cmd, "effect.apply");
assert_eq!(recorded[bevels::SAVED_BEVEL], applied[effects::BEVEL_PROFILE]);
let set = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": {"custom": "Example Bevel"}, "bevelWidth": 9}});
s.execute("effect.setParams", &set).unwrap();
let edited = params(&s, id);
let (_, set_recorded) = s.journal.last().unwrap().clone();
assert_eq!(set_recorded[bevels::SAVED_BEVEL], applied[effects::BEVEL_PROFILE]);
// The bevels file no longer has the bevel: by name it is refused, and the replays draw it.
s.attach_bevels_file(dir.join("Other.vectorcraft").to_string_lossy().to_string());
assert!(s.execute("effect.apply", &apply).is_err());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(id).unwrap().appearance.effects.is_empty());
s.replay("effect.apply", &recorded).unwrap();
assert_eq!(params(&s, id), applied);
s.replay("effect.setParams", &set_recorded).unwrap();
assert_eq!(params(&s, id), edited);
// Points given with the name are used in place of the file's.
let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]);
let mut given = set.clone();
given["savedBevel"] = notch.clone();
s.execute("effect.setParams", &given).unwrap();
assert_eq!((&params(&s, id)[effects::BEVEL_PROFILE], &params(&s, id)[effects::BEVEL_NAME]), (&notch, &json!("Example Bevel")));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_document_keeps_its_custom_bevels_without_the_bevels_file() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let id = rect(&mut s, 100);
let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]);
let custom = json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch, "bevelWidth": 12, "bevelHeight": 12});
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": custom})).unwrap();
let ink = |s: &Session| {
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default())
};
let with_bevel = ink(&s);
// Saved and opened in a session that has no bevels file: the bevel is drawn the same.
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone();
let mut o = Session::new();
o.execute("document.open", &json!({"name": "a.vectorcraft", "dataBase64": saved})).unwrap();
assert_eq!(params(&o, id)[effects::BEVEL_PROFILE], params(&s, id)[effects::BEVEL_PROFILE]);
assert_eq!(ink(&o).pixels, with_bevel.pixels);
// The classic chamfer draws differently.
let set = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": "classic"}});
o.execute("effect.setParams", &set).unwrap();
assert_ne!(ink(&o).pixels, with_bevel.pixels);
o.execute("edit.undo", &json!({})).unwrap();
assert_eq!(ink(&o).pixels, with_bevel.pixels);
// Points that do not make a bevel are refused before the document changes.
let bad = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevelProfile": [[0, 0], [0.5, 2], [1, 1]]}});
assert!(o.execute("effect.setParams", &bad).unwrap_err().to_string().contains("bevelProfile must be"));
}
#[test]
fn both_extrudes_take_a_custom_bevels_points_and_refuse_a_name_that_is_not_a_string() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]);
for effect in [effects::EXTRUDE, effects::CLASSIC_EXTRUDE] {
let id = rect(&mut s, 100);
let apply = |name: Value| json!({"effect": effect, "ids": [id.0], "item": null, "params": {"bevel": "custom", "bevelName": name, "bevelProfile": notch}});
let before = s.doc().unwrap().doc.clone();
let e = s.execute("effect.apply", &apply(json!(3))).unwrap_err().to_string();
assert!(e.contains("bevelName must be a string"), "{effect}: {e}");
assert_eq!(s.doc().unwrap().doc, before, "{effect}");
s.execute("effect.apply", &apply(json!("Notch"))).unwrap();
assert_eq!((&params(&s, id)[effects::BEVEL_PROFILE], &params(&s, id)[effects::BEVEL_NAME]), (&notch, &json!("Notch")), "{effect}");
}
}
#[test]
fn without_a_bevels_file_editing_is_refused_and_none_are_listed() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
assert_eq!((list["bevels"].as_array().unwrap().len(), &list["file"]), (0, &Value::Null));
assert!(s.execute("threeD.bevels.edit", &json!({})).is_err());
assert!(s.execute("threeD.bevels.reload", &json!({})).is_err());
// A file that is not a document lists no bevels and says why.
let dir = folder("unreadable");
let file = dir.join(bevels::FILE_NAME);
std::fs::write(&file, b"not a document").unwrap();
s.attach_bevels_file(file.to_string_lossy().to_string());
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
assert!(list["error"].is_string(), "{list}");
assert!(s.execute("threeD.bevels.reload", &json!({})).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
/// Automation roots that grant reading `read` alone.
fn read_roots(read: &[&std::path::Path]) -> Arc<crate::file_access::AutomationRoots> {
crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap()
}
#[test]
fn an_agent_outside_the_bevels_files_folder_sees_its_file_name_alone_and_cannot_reload_it() {
let dir = folder("roots-list");
let (prefs, other) = (dir.join("prefs"), dir.join("other"));
std::fs::create_dir_all(&prefs).unwrap();
std::fs::create_dir_all(&other).unwrap();
let file = prefs.join(bevels::FILE_NAME);
std::fs::write(&file, b"not a drawing").unwrap();
let (file, prefs_text) = (file.to_string_lossy().to_string(), prefs.to_string_lossy().to_string());
let mut s = Session::new();
s.attach_bevels_file(file.clone());
let (outside, inside) = (read_roots(&[&other]), read_roots(&[&prefs]));
let list = crate::file_access::confine(Some(&outside), || s.execute("threeD.bevels.list", &json!({}))).unwrap();
assert_eq!(list["file"], Value::Null, "{list}");
let error = list["error"].as_str().unwrap();
assert!(error.starts_with(bevels::FILE_NAME) && !error.contains(&prefs_text), "{error}");
let list = crate::file_access::confine(Some(&inside), || s.execute("threeD.bevels.list", &json!({}))).unwrap();
assert_eq!(list["file"].as_str(), Some(file.as_str()));
assert!(list["error"].as_str().unwrap().starts_with(&file), "{list}");
// A good file now: an agent outside the folder cannot have it read.
std::fs::write(&file, vectorcraft_format::save_file(&bevels::starter())).unwrap();
let e = crate::file_access::confine(Some(&outside), || s.execute("threeD.bevels.reload", &json!({}))).unwrap_err().to_string();
assert!(e.contains("outside the read root") && e.ends_with(bevels::FILE_NAME) && !e.contains(&prefs_text), "{e}");
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
assert!(list["bevels"].as_array().unwrap().is_empty() && list["error"].is_string(), "not read again: {list}");
let r = crate::file_access::confine(Some(&inside), || s.execute("threeD.bevels.reload", &json!({}))).unwrap();
assert_eq!(r["count"], 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_agent_edits_the_bevels_file_only_inside_its_read_roots() {
let dir = folder("roots-edit");
let (prefs, other) = (dir.join("prefs"), dir.join("other"));
std::fs::create_dir_all(&other).unwrap();
let file = prefs.join(bevels::FILE_NAME).to_string_lossy().to_string();
let prefs_text = prefs.to_string_lossy().to_string();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.attach_bevels_file(file.clone());
let first_doc = s.doc().unwrap().uid;
let outside = read_roots(&[&other]);
let edit = |s: &mut Session, roots: &Arc<crate::file_access::AutomationRoots>| {
crate::file_access::confine(Some(roots), || s.execute("threeD.bevels.edit", &json!({})))
};
// Refused before the folder or the file is made, or anything is opened.
let e = edit(&mut s, &outside).unwrap_err().to_string();
assert!(e.ends_with(bevels::FILE_NAME) && !e.contains(&prefs_text), "{e}");
assert!(!prefs.exists(), "no folder made");
assert_eq!((s.documents().len(), s.doc().unwrap().uid), (1, first_doc));
// From the 3D and Materials panel (no roots), the file is made and opened.
assert_eq!(s.execute("threeD.bevels.edit", &json!({})).unwrap()["created"], true);
assert_eq!(s.documents().len(), 2);
// Open already: still not brought to the front for an agent outside the folder.
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert!(edit(&mut s, &outside).is_err());
assert_eq!((s.documents().len(), s.doc().unwrap().uid), (2, first_doc));
// Inside the read roots: opened under them, with its path.
let inside = read_roots(&[&prefs]);
let mut agent = Session::new();
agent.attach_bevels_file(file.clone());
let r = edit(&mut agent, &inside).unwrap();
assert_eq!((r["path"].as_str(), &r["created"]), (Some(file.as_str()), &json!(false)));
let st = agent.doc().unwrap();
assert_eq!(st.path.as_deref(), Some(file.as_str()));
assert!(st.opened_by.as_ref().is_some_and(|r| Arc::ptr_eq(r, &inside)), "opened under the agent's roots");
// A missing file inside the roots is still made first.
let fresh = dir.join("fresh").join(bevels::FILE_NAME).to_string_lossy().to_string();
let mut agent = Session::new();
agent.attach_bevels_file(fresh.clone());
let r = edit(&mut agent, &read_roots(&[&dir])).unwrap();
assert_eq!(r["created"], true);
assert!(std::path::Path::new(&fresh).is_file());
assert_eq!(agent.doc().unwrap().path.as_deref(), Some(fresh.as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
+62 -7
View File
@@ -114,6 +114,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"bristle-brushes",
"paint",
"pattern-borders",
"decorative",
"scatter-shapes",
"stipple",
"game-trails",
@@ -127,6 +128,20 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
// None of them is a default brush.
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
for id in ids {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
}
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
}
#[test]
fn the_builtin_libraries_list_their_brush_names_and_counts() {
let mut s = Session::new();
let list = run(&mut s, "brush.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
// Looked up by id, so a library added to the list does not shift these checks.
let entry = |id: &str| libs.iter().find(|l| l["id"] == id).unwrap();
let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"}));
@@ -135,6 +150,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"]
);
assert_eq!(entry("art-ribbons")["count"].as_u64(), Some(5));
assert_eq!((entry("decorative")["name"].as_str(), entry("decorative")["count"].as_u64()), (Some("Decorative"), Some(4)));
let trails = run(&mut s, "brush.library", json!({"library": "game-trails"}));
assert_eq!(
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
@@ -164,6 +180,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
assert_eq!(strs(&added["added"]), ["Laser Bolt"]);
}
#[test]
fn every_builtin_library_brush_has_its_kind_and_draws() {
let s = Session::new();
// One kind of brush per library (Ink and Wash: art brushes and a calligraphic one), every
// brush drawing something.
for (id, kind) in [
@@ -174,6 +195,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("bristle-brushes", "bristle"),
("paint", "art"),
("pattern-borders", "pattern"),
("decorative", "pattern"),
("scatter-shapes", "scatter"),
("stipple", "scatter"),
("game-trails", "art"),
@@ -195,6 +217,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &stroke).is_empty(), "{} draws nothing", b.name);
}
}
}
#[test]
fn builtin_library_brushes_bring_the_resources_their_art_uses() {
let s = Session::new();
// The resources their art uses come with them: Striped Ribbon's pattern, Sparkles' symbol.
let (_, ribbons) = cmd::brushlib::library(&s, "art-ribbons").unwrap();
assert_eq!(art_patterns(ribbons.brush("Striped Ribbon").unwrap()), ["Pinstripes"]);
@@ -203,13 +230,6 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
let BrushKind::Scatter(sparkles) = &shapes.brush("Sparkles").unwrap().kind else { panic!("not a scatter brush") };
assert!(matches!(&sparkles.art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Sparkle"));
assert!(shapes.doc.symbols.iter().any(|x| x.name == "Sparkle"));
// None of them is a default brush.
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
for id in ids {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
}
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
}
#[test]
@@ -562,6 +582,41 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Decorative").unwrap();
let names = ["Leaf Vine", "Blossom Chain", "Pennant Garland", "Lantern String"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
let mut signatures = std::collections::HashSet::new();
for b in &lib.brushes {
let BrushKind::Pattern(pattern) = &b.kind else { panic!("{} is not a pattern brush", b.name) };
assert_eq!(pattern.colorization, vectorcraft_brush::Colorization::Tints);
let points = |len: f64| anchors(&vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(len), &black_stroke()).iter().collect::<Vec<_>>());
let (one, four) = (points(48.0), points(192.0));
assert!(!one.is_empty() && four.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
// A path four tiles long places the motif four times, each copy one tile further along.
assert_eq!(four.len(), 4 * one.len(), "{} repeats its motif", b.name);
for (i, p) in four.iter().enumerate() {
let q = one[i % one.len()];
let shift = 48.0 * (i / one.len()) as f64;
assert!((p.x - q.x - shift).abs() < 1e-3 && (p.y - q.y).abs() < 1e-3, "{} copy {} at {p:?}, not {q:?}", b.name, i / one.len());
}
signatures.insert(one.iter().map(|p| ((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64)).collect::<Vec<_>>());
let before = undo_len(&s);
let applied = run(&mut s, "brush.addFromLibrary", json!({"library": "decorative", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!((strs(&applied["added"]), &applied["applied"]), (vec![b.name.as_str()], &json!([path])));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
}
assert_eq!(signatures.len(), names.len(), "each design produces a different repeating shape");
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 pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
let mut s = session();
+3
View File
@@ -579,6 +579,9 @@ fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut
/// natural size or anything else a symbol is measured with checks them all.
#[test]
fn refreshing_only_changed_trees_matches_the_full_pass() {
// Both sessions lay out type, and the test rescans the fonts: a font another test adds between
// the full pass and the fast one would change how the type resolves in only one of them.
let _fonts = crate::adding_fonts();
let setup = |s: &mut Session| {
circle_symbol(s, "Tap", 10.0);
circle_symbol(s, "Dot", 6.0);
+101
View File
@@ -59,6 +59,107 @@ fn a_whole_rectangle_rounds_all_corners_and_given_corners_alone() {
assert_eq!(corners(&s, id).1[3], CornerKind::Chamfer);
}
/// The Corner menus of Rectangle Properties: a kind for all four corners or one, set on corners
/// with no radius too and leaving the radii as they are, in one undo step; the kind the corners
/// already have adds no step.
#[test]
fn rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo() {
let (mut s, id) = session();
run(&mut s, json!({"corners": [1], "radius": 12}));
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = steps(&s);
run(&mut s, json!({"corners": [0, 1, 2, 3], "kind": "invertedRound"}));
assert_eq!(corners(&s, id).0, [0.0, 12.0, 0.0, 0.0]);
assert_eq!(corners(&s, id).1, [CornerKind::InvertedRound; 4]);
assert_eq!(steps(&s), undo + 1);
run(&mut s, json!({"corners": [0, 1, 2, 3], "kind": "invertedRound"}));
run(&mut s, json!({"corners": [2], "kind": "invertedRound"}));
assert_eq!(steps(&s), undo + 1, "no step when nothing changes");
run(&mut s, json!({"corners": [2], "kind": "chamfer"}));
assert_eq!(corners(&s, id).1, [CornerKind::InvertedRound, CornerKind::InvertedRound, CornerKind::Chamfer, CornerKind::InvertedRound]);
assert_eq!(corners(&s, id).0, [0.0, 12.0, 0.0, 0.0]);
assert_eq!(steps(&s), undo + 2);
}
/// A kind the corners already have leaves a rectangle saved stretched by an older version as it
/// is, alone or beside a rectangle the kind changes: its scale stays in its transform.
#[test]
fn a_kind_the_corners_have_leaves_a_stretched_rectangle() {
let (mut s, id) = session();
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
let stretched = LiveShape::Rectangle {
w: 50.0,
h: 60.0,
radii: [10.0; 4],
kinds: [CornerKind::Chamfer; 4],
radii_relative: false,
xf: Affine::translate((10.0, 10.0)) * Affine::scale_non_uniform(2.0, 1.0),
};
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, live: Some(live), .. } = &mut d.node_mut(id).unwrap().kind else { panic!("not live") };
**live = stretched.clone();
*path = live.to_path();
}
let live = |s: &Session| node_path(s, id).1;
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = steps(&s);
run(&mut s, json!({"ids": [id.0], "kind": "chamfer"}));
assert_eq!(live(&s), Some(stretched.clone()));
assert_eq!(steps(&s), undo, "no step when nothing changes");
run(&mut s, json!({"ids": [id.0, other.0], "kind": "chamfer"}));
assert_eq!(live(&s), Some(stretched));
assert_eq!(corners(&s, other).1, [CornerKind::Chamfer; 4]);
assert_eq!(steps(&s), undo + 1);
}
/// A radius is stored on a corner that stores a larger radius drawn at the new value, alone or
/// beside another rectangle; the radius every target already stores adds no undo step.
#[test]
fn a_radius_reaches_a_rectangle_that_already_draws_it() {
let (mut s, id) = session();
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
// 80 pt on every corner draws at 30 pt, half the 60 pt side.
run(&mut s, json!({"ids": [id.0], "radius": 80}));
assert_eq!(corners(&s, id).0, [80.0; 4]);
let (path, live) = node_path(&s, id);
let drawn = LiveCorners::new(&path, live.as_ref()).unwrap().drawn_radius(0);
assert!((drawn - 30.0).abs() < 1e-9, "draws at {drawn}");
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = steps(&s);
run(&mut s, json!({"ids": [id.0], "corners": [1], "radius": 30}));
assert_eq!(corners(&s, id).0, [80.0, 30.0, 80.0, 80.0]);
assert_eq!(steps(&s), undo + 1);
run(&mut s, json!({"ids": [id.0, other.0], "corners": [0], "radius": 30}));
assert_eq!(corners(&s, id).0[0], 30.0);
assert_eq!(corners(&s, other).0[0], 30.0);
// The radius both already store adds no step.
run(&mut s, json!({"ids": [id.0, other.0], "corners": [0], "radius": 30}));
assert_eq!(steps(&s), undo + 2);
}
/// `rectanglesOnly` sets the live rectangles among the selection and leaves a polygon as it is; an
/// action that records it holds no ids, so playing it sets the rectangles selected then.
#[test]
fn rectangles_only_sets_the_selected_rectangles_when_an_action_plays() {
let (mut s, id) = session();
let polygon = NodeId(s.execute("shape.polygon", &json!({"cx": 300, "cy": 300, "radius": 40, "sides": 6})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0, polygon.0]})).unwrap();
let start = s.journal.len();
run(&mut s, json!({"rectanglesOnly": true, "corners": [0], "kind": "chamfer"}));
assert_eq!(corners(&s, id).1[0], CornerKind::Chamfer);
let NodeKind::Path { live: Some(l), .. } = &s.doc().unwrap().doc.node(polygon).unwrap().kind else { panic!("not live") };
let LiveShape::Polygon { kinds, .. } = &**l else { panic!("not a polygon") };
assert!(kinds.iter().all(|k| *k == CornerKind::Round), "the polygon keeps its corners: {kinds:?}");
let action = s.journal_for_action(start);
assert_eq!(action.len(), 1);
assert_eq!(action[0].1.get("ids"), None);
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [other.0, polygon.0]})).unwrap();
s.replay(&action[0].0, &action[0].1).unwrap();
assert_eq!(corners(&s, other).1[0], CornerKind::Chamfer);
}
/// #938: `items` rounds several objects in one step, each its own corners (or all of them).
#[test]
fn items_round_several_objects_each_its_own_corners() {
+2 -1
View File
@@ -707,12 +707,13 @@ fn an_effect_parameter_without_a_default_is_held_to_its_type() {
use crate::cmd::params::undefaulted_type;
use vectorcraft_render::effects::effect_catalog;
// Read by checks of their own: a stored texture or a texture to load, an SVG filter and its axes, a Warp's
// map and the style of Crop Marks.
// map, the style of Crop Marks and a custom bevel's name and points.
let own_check = |effect: &str, key: &str| match key {
"textureImage" | "name" | "xml" => true,
"axes" => effect == "svg.filter",
"version" => effect.starts_with("warp."),
"style" => effect == "cropMarks",
"bevelName" | "bevelProfile" => matches!(effect, "threeD.extrude" | "threeD.classicExtrude"),
_ => false,
};
let mut unlisted = vec![];
+181
View File
@@ -154,3 +154,184 @@ fn scissors_cuts_after_a_command_settles_a_deferred_move() {
assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1);
}
}
/// Real Session composition: the hovered feedback must be the endpoint the actual split creates,
/// while the selected crossing owner, history and Undo/Redo contracts remain intact.
#[test]
fn review_8655_scissors_session_feedback_is_the_committed_cut_endpoint() {
let mut observed = Vec::new();
for pixel_preview in [true, false] {
let mut session = Session::new();
session.execute("file.new", &json!({"width":800,"height":600})).unwrap();
let rectangle =
NodeId(session.execute("shape.rectangle", &json!({"x":100,"y":100,"width":100,"height":100})).unwrap()["id"].as_u64().unwrap());
let crossing = NodeId(session.execute("shape.line", &json!({"x1":145,"y1":90,"x2":165,"y2":130})).unwrap()["id"].as_u64().unwrap());
session.execute("select.set", &json!({"ids":[rectangle.0]})).unwrap();
let view = ViewInfo { pixel_preview, ..ViewInfo::default() };
session.select_tool("scissors", view).unwrap();
let original = path(&session, rectangle);
let other = path(&session, crossing);
let selection_before = session.doc().unwrap().selection.clone();
let undo_before = session.doc().unwrap().history.undo.len();
let raw = Point::new(152.0, 101.5);
session.pointer(&PointerEvent::new(PointerKind::Move, raw.x, raw.y), view).unwrap();
let overlays = session.overlays(view);
let markers: Vec<_> = overlays
.iter()
.filter_map(|o| match o {
Overlay::Anchor { p, color, filled: false, size } if *color == vectorcraft_tools::draw2::FEEDBACK && *size == 7.0 => Some(*p),
_ => None,
})
.collect();
let intersection = overlays.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "intersect"));
assert_eq!(intersection, !pixel_preview, "CONTROL: native view boundary retains Smart Guides policy");
for kind in [PointerKind::Down, PointerKind::Up] {
session.pointer(&PointerEvent::new(kind, raw.x, raw.y), view).unwrap();
}
let opened = path(&session, rectangle);
assert!(!opened.is_closed());
let anchors = &opened.subpaths[0].anchors;
assert_eq!(anchors.len(), 6);
let cut = anchors[0].p;
assert_eq!(anchors.last().unwrap().p, cut);
let expected = Point::new(if pixel_preview { 152.0 } else { 150.0 }, 100.0);
assert!(cut.distance(expected) < 1e-6, "CONTROL: actual cut geometry respects view snapping");
assert!(cut.distance(raw) > 1.0, "CONTROL: feedback is projected to the path, not raw input");
let selection_after = session.doc().unwrap().selection.clone();
assert_eq!(selection_after.objects, [rectangle]);
assert_eq!(selection_after.partial(rectangle).unwrap().iter().copied().collect::<Vec<_>>(), [(0, 0)]);
assert!(selection_after.segments.is_empty());
assert_eq!(path(&session, crossing), other);
assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1);
assert!(
session.overlays(view).iter().all(|o| !matches!(o, Overlay::Anchor { color, filled:false, size, .. }
if *color == vectorcraft_tools::draw2::FEEDBACK && *size == 7.0)),
"CONTROL: Up clears cut feedback"
);
session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&session, rectangle), original);
assert_eq!(path(&session, crossing), other);
assert_eq!(session.doc().unwrap().selection, selection_before);
assert_eq!(session.doc().unwrap().history.undo.len(), undo_before);
session.execute("edit.redo", &json!({})).unwrap();
assert_eq!(path(&session, rectangle), opened);
assert_eq!(path(&session, crossing), other);
assert_eq!(session.doc().unwrap().selection, selection_after);
assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1);
observed.push((pixel_preview, markers, cut));
}
let endpoint_controls = review_8655_session_endpoint_controls();
for (pixel_preview, markers, cut) in observed {
assert_eq!(markers.len(), 1, "REGRESSION: Pixel Preview{pixel_preview} needs one hollow7px FEEDBACK anchor");
assert!(markers[0].distance(cut) < 1e-6, "REGRESSION: preview{markers:?} must mark the actual committed endpoint{cut:?}");
}
for (markers, cut) in endpoint_controls {
assert_eq!(markers.len(), 1, "a successful interior/canonicalized cut has one marker");
assert!(markers[0].distance(cut) < 1e-6, "marker{markers:?} must equal the actual Engine cut{cut:?}");
}
}
fn review_8655_session_markers(overlays: &[Overlay]) -> Vec<Point> {
overlays
.iter()
.filter_map(|o| match o {
Overlay::Anchor { p, color, filled: false, size } if *color == vectorcraft_tools::draw2::FEEDBACK && *size == 7.0 => Some(*p),
_ => None,
})
.collect()
}
fn review_8655_session_endpoint_controls() -> Vec<(Vec<Point>, Point)> {
let mut session = Session::new();
session.execute("file.new", &json!({"width":800,"height":600})).unwrap();
let line = NodeId(session.execute("shape.line", &json!({"x1":100,"y1":300,"x2":200,"y2":300})).unwrap()["id"].as_u64().unwrap());
session.execute("select.set", &json!({"ids":[line.0]})).unwrap();
let view = ViewInfo { smart_guides: false, snap_to_point: false, snap_to_grid: false, snap_to_pixel: false, ..ViewInfo::default() };
session.select_tool("scissors", view).unwrap();
let original = path(&session, line);
let document = json!(session.doc().unwrap().doc.as_ref());
let selection = session.doc().unwrap().selection.clone();
let undo = session.doc().unwrap().history.undo.len();
let redo = session.doc().unwrap().history.redo.len();
assert!(!original.is_closed());
assert_eq!(original.subpaths[0].anchors.len(), 2, "CONTROL: ordinary minimal drawable open line");
for endpoint in [Point::new(100.0, 300.0), Point::new(200.0, 300.0)] {
session.pointer(&PointerEvent::new(PointerKind::Move, endpoint.x, endpoint.y), view).unwrap();
let endpoint_markers = review_8655_session_markers(&session.overlays(view));
let error = session.pointer(&PointerEvent::new(PointerKind::Down, endpoint.x, endpoint.y), view).unwrap_err();
assert!(error.to_string().contains("cannot split an open path at its end point"), "CONTROL: preserve baseline endpoint error: {error}");
assert_eq!(json!(session.doc().unwrap().doc.as_ref()), document, "a failed endpoint cut changes no document data");
assert_eq!(session.doc().unwrap().selection, selection);
assert_eq!(session.doc().unwrap().history.undo.len(), undo);
assert_eq!(session.doc().unwrap().history.redo.len(), redo);
assert!(endpoint_markers.is_empty(), "an endpoint that Engine rejects has no successful-cut feedback");
session.pointer(&PointerEvent::new(PointerKind::Up, endpoint.x, endpoint.y), view).unwrap();
}
let interior = Point::new(150.0, 300.0);
session.pointer(&PointerEvent::new(PointerKind::Move, interior.x, interior.y), view).unwrap();
let interior_markers = review_8655_session_markers(&session.overlays(view));
for kind in [PointerKind::Down, PointerKind::Up] {
session.pointer(&PointerEvent::new(kind, interior.x, interior.y), view).unwrap();
}
let right_id = session.doc().unwrap().selection.objects[0];
assert_ne!(right_id, line);
let right = path(&session, right_id);
let left = path(&session, line);
let actual_interior = right.subpaths[0].anchors[0].p;
assert!(actual_interior.distance(interior) < 1e-6);
assert_eq!(left.subpaths[0].anchors.last().unwrap().p, actual_interior);
assert_eq!(session.doc().unwrap().history.undo.len(), undo + 1);
session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&session, line), original);
assert!(session.doc().unwrap().doc.node(right_id).is_none());
assert_eq!(session.doc().unwrap().selection, selection);
let (canonical_markers, canonical) = review_8655_session_canonical_control(session, view);
vec![(interior_markers, actual_interior), (canonical_markers, canonical)]
}
fn review_8655_session_canonical_control(mut session: Session, view: ViewInfo) -> (Vec<Point>, Point) {
let closed = NodeId(
session
.execute(
"path.create",
&json!({"d":"M99.99995 100 C133.33328333333333 100 166.66661666666666 100 199.99995 100 L199.99995 200 L99.99995 200 Z"}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let mut prefs = session.prefs.clone();
prefs.gridline_every = 10.0;
prefs.grid_subdivisions = 1;
session.apply_prefs(prefs);
assert_eq!(session.doc().unwrap().doc.grid.spacing, 10.0);
assert_eq!(session.doc().unwrap().doc.grid.subdivisions, 1);
session.execute("select.set", &json!({"ids":[closed.0]})).unwrap();
let grid = ViewInfo { snap_to_grid: true, ..view };
let original_closed = path(&session, closed);
assert!(original_closed.is_closed());
let canonical = original_closed.subpaths[0].anchors[0].p;
let (_, segment, t, projected, _) = original_closed.nearest(Point::new(100.0, 100.0)).unwrap();
assert_eq!(segment, 0);
assert!(t > 0.0 && t <= 1e-6, "CONTROL: stored native cubic reaches actual canonicalization threshold: {t}");
assert!(projected.distance(canonical) > 1e-5, "CONTROL: projected point differs from canonical stored anchor");
let raw = Point::new(100.1, 100.2);
session.pointer(&PointerEvent::new(PointerKind::Move, raw.x, raw.y), grid).unwrap();
let canonical_markers = review_8655_session_markers(&session.overlays(grid));
let before = session.doc().unwrap().history.undo.len();
for kind in [PointerKind::Down, PointerKind::Up] {
session.pointer(&PointerEvent::new(kind, raw.x, raw.y), grid).unwrap();
}
let opened = path(&session, closed);
assert!(!opened.is_closed());
let anchors = &opened.subpaths[0].anchors;
assert_eq!(anchors.first().unwrap().p, canonical, "Engine commits the original anchor rather than curve.eval(t)");
assert_eq!(anchors.last().unwrap().p, canonical);
assert_eq!(session.doc().unwrap().history.undo.len(), before + 1);
session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&session, closed), original_closed);
session.execute("edit.redo", &json!({})).unwrap();
assert_eq!(path(&session, closed), opened);
(canonical_markers, canonical)
}
+7 -1
View File
@@ -1012,6 +1012,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
("help.about", "About VectorCraft", "", "{}"),
("help.checkForUpdates", "Check for Updates…", "", "{}"),
("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"),
(
"help.clearRecentCommands",
"Clear Recent Commands",
"",
"{} empty the recent picks of Help › Search Commands (the list an empty search shows and the Recent Commands list), the saved list and the pick counts that rank the results; a pick of it is not kept as a recent pick or counted. Not enabled while no picks or counts are saved",
),
(
"help.discover",
"VectorCraft Help…",
@@ -1573,7 +1579,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision}",
),
(
"ui.savePdfDialog",
+3 -3
View File
@@ -12,9 +12,9 @@ pub mod fold;
mod solid;
mod visibility;
pub use solid::{
Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MapCell, MeshFace, PlanarFace, SolidSurface, SurfaceKind, TOO_COMPLEX_SOLID,
View, extrude, extrude_face_map, extrude_mesh_face, extrude_side_size, extrude_surfaces, inflate, inflate_each, inflate_together, plane,
plane_face_map, plane_mesh_face,
Bevel, BevelProfile, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MapCell, MeshFace, PlanarFace, SolidSurface, SurfaceKind,
TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, extrude_mesh_face, extrude_side_size, extrude_surfaces, inflate, inflate_each,
inflate_together, plane, plane_face_map, plane_mesh_face,
};
pub use visibility::{VisibleFace, visible_faces};
mod shading;
+72
View File
@@ -113,6 +113,8 @@ impl View {
}
/// The shape of a bevel's cross-section, from the cap's edge (0) to the side wall (1).
// A custom profile takes 258 bytes; an extrusion copies its bevel a few times.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BevelShape {
/// A straight 45° chamfer when width and height are equal.
@@ -126,11 +128,73 @@ pub enum BevelShape {
Step,
/// A convex then concave S curve.
Ogee,
/// A cross-section of the user's own, drawn as an open path ([`BevelProfile`]).
Custom(BevelProfile),
}
/// A custom bevel's cross-section: points from the cap's edge, (0, 0), to the side wall, (1, 1),
/// each a (share of the width, share of the height) pair in 0..1, joined by straight lines. The
/// shares are kept to 1/32,768 in a fixed array, so the profile is `Copy` like the built-in shapes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BevelProfile {
points: [(u16, u16); BevelProfile::MAX_POINTS],
len: u8,
}
impl BevelProfile {
/// The most points a profile holds.
pub const MAX_POINTS: usize = 64;
/// A profile of `points`, or `None` unless there are 2 to [`Self::MAX_POINTS`] of them, every
/// share is a number in 0..1, and they start at (0, 0) and end at (1, 1).
pub fn new(points: &[(f64, f64)]) -> Option<Self> {
const END: f64 = 1e-6;
if !(2..=Self::MAX_POINTS).contains(&points.len()) || points.iter().any(|&(x, y)| !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y)) {
return None;
}
let (first, last) = (points[0], points[points.len() - 1]);
if first.0 > END || first.1 > END || last.0 < 1.0 - END || last.1 < 1.0 - END {
return None;
}
let mut out = Self { points: [(0, 0); Self::MAX_POINTS], len: points.len() as u8 };
let share = |v: f64| (v * f64::from(Self::ONE)).round() as u16;
for (slot, &(x, y)) in out.points.iter_mut().zip(points) {
*slot = (share(x), share(y));
}
out.points[0] = (0, 0);
out.points[points.len() - 1] = (Self::ONE, Self::ONE);
Some(out)
}
/// A whole share in the stored points: shares are kept to 1/32,768, so halves and quarters
/// stay exact.
const ONE: u16 = 1 << 15;
/// The points, as (share of the width, share of the height).
pub fn points(&self) -> impl Iterator<Item = (f64, f64)> + '_ {
let share = |v: u16| f64::from(v) / f64::from(Self::ONE);
self.points[..usize::from(self.len)].iter().map(move |&(x, y)| (share(x), share(y)))
}
/// The point at `s` (0..1), the points spread evenly along `s` and joined by straight lines.
fn at(&self, s: f64) -> (f64, f64) {
// A profile holds at least two points (`new`).
let len = usize::from(self.len).max(2);
let share = |v: u16| f64::from(v) / f64::from(Self::ONE);
let k = s * (len - 1) as f64;
let i = (k.floor() as usize).min(len - 2);
let f = k - i as f64;
let (a, b) = (self.points[i], self.points[i + 1]);
let (ax, ay, bx, by) = (share(a.0), share(a.1), share(b.0), share(b.1));
(ax + (bx - ax) * f, ay + (by - ay) * f)
}
}
impl BevelShape {
/// The built-in shapes.
pub const ALL: [BevelShape; 5] = [Self::Classic, Self::Rounded, Self::Cove, Self::Step, Self::Ogee];
/// The shape's parameter value; `custom` for a [`BevelShape::Custom`] one.
pub fn id(self) -> &'static str {
match self {
Self::Classic => "classic",
@@ -138,9 +202,11 @@ impl BevelShape {
Self::Cove => "cove",
Self::Step => "step",
Self::Ogee => "ogee",
Self::Custom(_) => "custom",
}
}
/// The built-in shape named `s`.
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|b| b.id() == s)
}
@@ -150,6 +216,7 @@ impl BevelShape {
let s = s.clamp(0.0, 1.0);
let q = s * std::f64::consts::FRAC_PI_2;
match self {
Self::Custom(profile) => profile.at(s),
Self::Classic => (s, s),
Self::Rounded => (1.0 - q.cos(), q.sin()),
Self::Cove => (q.sin(), 1.0 - q.cos()),
@@ -177,6 +244,11 @@ impl BevelShape {
match self {
Self::Classic => vec![0.0, 1.0],
Self::Step => vec![0.0, 0.25, 0.5, 0.75, 1.0],
// Each of its points, where the straight lines between them turn.
Self::Custom(profile) => {
let last = (usize::from(profile.len) - 1) as f64;
(0..usize::from(profile.len)).map(|i| i as f64 / last).collect()
}
_ => (0..=8).map(|i| f64::from(i) / 8.0).collect(),
}
}
+34
View File
@@ -354,6 +354,40 @@ fn bevel_shapes_repeats_and_both_sides_change_the_surface() {
}
}
/// A custom bevel's points are its cross-section, joined by straight lines: two points make the
/// classic chamfer, and the step shape's points make the step shape's solid. Other points change
/// the surface. A profile must run from (0, 0) to (1, 1) with every share in 0..1.
#[test]
fn custom_bevel_profiles_shape_the_bevel() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
let v = View { rotation_x: -20.0, rotation_y: 30.0, ..front() };
let solid = |shape: BevelShape| {
let bevel = Bevel { shape, width: 12.0, height: 12.0, repeat: 2, space: 0.2, both_sides: true, ..Bevel::default() };
extrude(&p, FillRule::EvenOdd, b, Extrude { bevel: Some(bevel), ..Extrude::default() }, v).unwrap()
};
let custom = |pts: &[(f64, f64)]| BevelShape::Custom(BevelProfile::new(pts).unwrap());
assert_eq!(solid(custom(&[(0.0, 0.0), (1.0, 1.0)])), solid(BevelShape::Classic));
let step = [(0.0, 0.0), (0.0, 0.5), (0.5, 0.5), (0.5, 1.0), (1.0, 1.0)];
assert_eq!(solid(custom(&step)), solid(BevelShape::Step));
let notch = custom(&[(0.0, 0.0), (0.2, 0.6), (0.7, 0.4), (1.0, 1.0)]);
assert_ne!(solid(notch), solid(BevelShape::Classic));
assert_eq!(notch.id(), "custom");
assert_eq!(BevelShape::parse("custom"), None);
assert_eq!(notch.at(0.0), (0.0, 0.0));
assert_eq!(notch.at(1.0), (1.0, 1.0));
// The point a third of the way along is the second point, kept to 1/32,768.
let (x, y) = notch.at(1.0 / 3.0);
assert!(close(x, 0.2, 1e-4) && close(y, 0.6, 1e-4), "{x}, {y}");
// Inside, the bevel carves the shape with the same points.
let inside = Bevel { shape: notch, width: 12.0, height: 12.0, inside: true, ..Bevel::default() };
assert!(extrude(&p, FillRule::EvenOdd, b, Extrude { bevel: Some(inside), ..Extrude::default() }, v).is_ok());
let too_many = vec![(0.5, 0.5); BevelProfile::MAX_POINTS + 1];
for bad in [&[(0.0, 0.0)][..], &[(0.1, 0.0), (1.0, 1.0)], &[(0.0, 0.0), (1.0, 0.9)], &[(0.0, 0.0), (1.2, 0.5), (1.0, 1.0)], &too_many] {
assert_eq!(BevelProfile::new(bad), None, "{bad:?}");
}
assert!(BevelProfile::new(&[(0.0, 0.0), (f64::NAN, 0.5), (1.0, 1.0)]).is_none());
}
#[test]
fn holes_stay_holes_in_the_caps_and_get_walls_of_their_own() {
let mut b = square(0.0, 0.0, 100.0);
+74 -16
View File
@@ -16,9 +16,9 @@
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_geom::Point;
use vectorcraft_geom::{ParamCurve, Point};
use super::{hit_anchor, hit_segment, insert_anchor, remove_anchor};
use super::{FEEDBACK, hit_anchor, hit_segment, insert_anchor, remove_anchor};
use crate::direct::hit_handle;
use crate::guides::{DrawSnap, HandleSnap};
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -95,10 +95,48 @@ enum SpaceResume {
SpineHandle { id: NodeId, ai: usize, out: bool },
}
/// A cut chosen with the same anchor/segment priority for preview and press.
enum ScissorsCut {
Anchor { id: NodeId, si: usize, ai: usize },
Segment { id: NodeId, si: usize, seg: usize, t: f64 },
}
impl ScissorsCut {
fn point(&self, cx: &ToolContext) -> Option<Point> {
let (id, si) = match *self {
Self::Anchor { id, si, .. } | Self::Segment { id, si, .. } => (id, si),
};
let sp = cx.doc.node(id)?.path_data()?.subpaths.get(si)?;
if sp.anchors.len() < 2 {
return None;
}
let ai = match *self {
Self::Anchor { ai, .. } => ai,
Self::Segment { seg, t, .. } => {
if seg >= sp.segment_count() || !(0.0..=1.0).contains(&t) {
return None;
}
// path.split canonicalizes cuts near segment ends to the existing anchor.
if t <= 1e-6 {
seg
} else if t >= 1.0 - 1e-6 {
(seg + 1) % sp.anchors.len()
} else {
return Some(sp.segment(seg).eval(t));
}
}
};
let anchor = sp.anchors.get(ai)?;
// An open path cannot be split at either of its existing end points.
(sp.closed || (ai > 0 && ai + 1 < sp.anchors.len())).then_some(anchor.p)
}
}
/// The cursor reuses the last hover's point, with DrawSnap checking its target inputs. The
/// Scissors-only inputs also bind the resolved point to the current cut eligibility.
struct ScissorsHover {
raw: Point,
shared: Point,
snapped: Point,
zoom: f64,
isolation: Option<NodeId>,
@@ -160,7 +198,7 @@ impl AnchorTool {
/// Keep a shared art snap unless it prevents a cut the raw pointer could make. Outside art
/// still supplies alignment and intersection guides; pixel and grid snapping keep precedence.
fn resolve_scissors_snap(&mut self, cx: &ToolContext, raw: Point, snapped: Point) -> Point {
fn scissors_point(cx: &ToolContext, raw: Point, snapped: Point) -> (Point, bool) {
let eligible = |p| hit_anchor(cx, p, 0.0).is_some() || hit_segment(cx, p, cx.pick_tol()).is_some();
let fallback = (cx.smart_guides || cx.snap_to_point)
&& !cx.snaps_to_pixel(PixelOp::Drawing)
@@ -168,14 +206,16 @@ impl AnchorTool {
&& snapped != raw
&& !eligible(snapped)
&& eligible(raw);
let snapped = if fallback {
(if fallback { raw } else { snapped }, fallback)
}
fn resolve_scissors_snap(&mut self, cx: &ToolContext, raw: Point, shared: Point) -> Point {
let (snapped, fallback) = Self::scissors_point(cx, raw, shared);
if fallback {
self.scissors_snap.clear();
raw
} else {
snapped
};
}
self.scissors_hover =
Some(ScissorsHover { raw, snapped, zoom: cx.zoom, isolation: cx.isolation, selection_tolerance: cx.selection_tolerance });
Some(ScissorsHover { raw, shared, snapped, zoom: cx.zoom, isolation: cx.isolation, selection_tolerance: cx.selection_tolerance });
snapped
}
@@ -198,18 +238,27 @@ impl AnchorTool {
}
let snapped = self.scissors_snap.press(cx, p, &[], None);
let p = self.resolve_scissors_snap(cx, p, snapped);
match Self::scissors_cut(cx, p) {
Some(ScissorsCut::Anchor { id, si, ai }) => {
vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))]
}
Some(ScissorsCut::Segment { id, si, seg, t }) => {
vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t}))]
}
None => vec![],
}
}
fn scissors_cut(cx: &ToolContext, p: Point) -> Option<ScissorsCut> {
let point = cx.point_tol();
// A path snap must not be pulled to a nearby anchor by the larger pick radius.
// Shared anchor targets and the path's anchors use the same stored coordinates.
let snapping = cx.smart_guides || cx.snap_to_point || cx.snaps_to_pixel(PixelOp::Drawing) || cx.snap_to_grid;
let anchor_tol = if snapping { 0.0 } else { point };
if let Some((id, si, ai)) = hit_anchor(cx, p, anchor_tol) {
return vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))];
}
match Self::scissors_segment(cx, p) {
Some((id, si, seg, t)) => vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t}))],
None => vec![],
return Some(ScissorsCut::Anchor { id, si, ai });
}
Self::scissors_segment(cx, p).map(|(id, si, seg, t)| ScissorsCut::Segment { id, si, seg, t })
}
/// The Anchor Point tool as the Pen lends it with Alt held: an Alt-drag on a handle moves only
@@ -694,8 +743,17 @@ impl Tool for AnchorTool {
if matches!(self.state, State::Handle { .. }) {
out.extend(self.guides.iter().cloned());
}
if self.id == "scissors" && self.current_scissors_hover(cx).is_some() {
out.extend_from_slice(self.scissors_snap.guides());
if self.id == "scissors"
&& let Some(h) = self.current_scissors_hover(cx)
{
// Selection priority can change without changing DrawSnap's geometry key.
let (p, _) = Self::scissors_point(cx, h.raw, h.shared);
if p == h.snapped {
out.extend_from_slice(self.scissors_snap.guides());
}
if let Some(p) = Self::scissors_cut(cx, p).and_then(|cut| cut.point(cx)) {
out.push(Overlay::Anchor { p, color: FEEDBACK, filled: false, size: 7.0 });
}
}
if cx.measurement_labels
&& let Some((p, dx, dy)) = self.measure
+236
View File
@@ -1049,3 +1049,239 @@ fn anchor_point_alt_drag_links_a_blend_spine_handle() {
);
assert_eq!(tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 190.0, 350.0).with_mods(alt)), vec![Action::Commit]);
}
fn review_8655_markers(tool: &AnchorTool, context: &ToolContext) -> Vec<Point> {
tool.overlays(context)
.into_iter()
.filter_map(|overlay| match overlay {
Overlay::Anchor { p, color, filled: false, size } if color == crate::draw2::FEEDBACK && size == 7.0 => Some(p),
_ => None,
})
.collect()
}
/// Compare the public overlay to geometry reconstructed from the real path.split action,
/// including points projected off the raw pointer and a rejected outside-art snap.
#[test]
fn review_8655_scissors_marker_matches_the_fresh_split_geometry() {
let paint = paint();
let mut observed = Vec::new();
for scenario in 0..5 {
let (mut d, mut target, mut selected) = if scenario == 1 {
scissors_crossing()
} else {
let (d, id) = doc_with_rect();
(d, id, Selection::default())
};
if scenario == 3 {
let outside = d.alloc_id();
d.insert(
Some(d.layers[0].id),
1,
vectorcraft_doc::Node::path(
outside,
vectorcraft_geom::shapes::line(Point::new(150.0, 103.5), Point::new(350.0, 350.0)),
vectorcraft_doc::Appearance::default_art(),
),
)
.unwrap();
} else if scenario == 4 {
let mut curve = vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false);
curve.anchors[0].h_out = Point::new(120.0, 340.0);
curve.anchors[1].h_in = Point::new(180.0, 340.0);
target = d.alloc_id();
d.insert(
Some(d.layers[0].id),
1,
vectorcraft_doc::Node::path(target, vectorcraft_geom::PathData::single(curve), vectorcraft_doc::Appearance::default_art()),
)
.unwrap();
}
selected.set([target]);
let (at, expected) = match scenario {
0 => (Point::new(152.0, 101.5), Point::new(152.0, 100.0)),
1 => (Point::new(152.0, 101.5), Point::new(150.0, 100.0)),
2 => (Point::new(200.0, 104.25), Point::new(200.0, 100.0)),
3 => (Point::new(150.0, 100.0), Point::new(150.0, 100.0)),
_ => (Point::new(150.0, 331.5), Point::new(150.0, 330.0)),
};
let snapping = scenario == 1 || scenario == 3;
let context = ToolContext {
smart_guides: snapping,
snap_to_point: snapping,
snap_to_pixel: false,
snap_to_grid: false,
isolation: (scenario == 3).then_some(target),
..cx(&d, &selected, &paint)
};
let mut tool = AnchorTool::new("scissors");
assert!(tool.pointer(&context, &PointerEvent::new(PointerKind::Move, at.x, at.y)).is_empty());
let markers = review_8655_markers(&tool, &context);
let labels = scissors_labels(&tool, &context);
if scenario == 1 {
assert_eq!(labels, [("intersect".to_string(), expected)], "CONTROL: existing intersection guides remain");
} else {
assert!(labels.is_empty(), "CONTROL: off/rejected snapping adds no guide: {labels:?}");
}
assert_eq!(tool.cursor(&context, at, Mods::default()), Cursor::Scissors);
let actions = tool.pointer(&context, &PointerEvent::new(PointerKind::Down, at.x, at.y));
let cut = scissors_cut_at(&d, target, &actions);
assert!(cut.distance(expected) < 1e-5, "CONTROL: scenario{scenario} actual split {cut:?}, expected{expected:?}");
if scenario == 2 {
assert!(matches!(&actions[..], [Action::Exec(_, args)] if args["anchor"] == 1), "CONTROL: the actual stored anchor wins");
}
if scenario == 0 || scenario == 4 {
assert!(cut.distance(at) > 1.0, "CONTROL: preview must show the path projection, not the raw point");
}
observed.push((scenario, markers, cut));
}
observed.extend(review_8655_endpoint_action_controls());
// Every split/guide control above executes before the missing-feedback oracle on old code.
for (scenario, markers, cut) in observed {
assert_eq!(markers.len(), 1, "REGRESSION: scenario{scenario} needs exactly one hollow7px FEEDBACK anchor: {markers:?}");
assert!(markers[0].distance(cut) < 1e-6, "REGRESSION: marker and actual fresh split disagree: {markers:?} versus{cut:?}");
}
}
#[test]
fn review_8655_scissors_selection_change_cannot_reuse_the_wrong_marker() {
let (mut d, rectangle) = doc_with_rect();
let line = d.alloc_id();
d.insert(
Some(d.layers[0].id),
1,
vectorcraft_doc::Node::path(
line,
vectorcraft_geom::shapes::line(Point::new(120.0, 102.0), Point::new(240.0, 102.0)),
vectorcraft_doc::Appearance::default_art(),
),
)
.unwrap();
let mut rectangle_selected = Selection::default();
rectangle_selected.set([rectangle]);
let mut line_selected = Selection::default();
line_selected.set([line]);
let paint = paint();
// Only the selection changes: these contexts have the same document and DrawSnap key inputs.
let before = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &rectangle_selected, &paint) };
let after = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &line_selected, &paint) };
assert_eq!(before.revision, after.revision);
assert!(std::ptr::eq(before.doc, after.doc));
let at = Point::new(150.0, 101.6);
let mut tool = AnchorTool::new("scissors");
tool.pointer(&before, &PointerEvent::new(PointerKind::Move, at.x, at.y));
let old_markers = review_8655_markers(&tool, &before);
let mut fresh = AnchorTool::new("scissors");
let old_cut = scissors_cut_at(&d, rectangle, &fresh.pointer(&before, &PointerEvent::new(PointerKind::Down, at.x, at.y)));
let new_cut = scissors_cut_at(&d, line, &fresh.pointer(&after, &PointerEvent::new(PointerKind::Down, at.x, at.y)));
assert!(old_cut.distance(Point::new(150.0, 100.0)) < 1e-6, "CONTROL: selected rectangle beats nearer unselected line");
assert!(new_cut.distance(Point::new(150.0, 102.0)) < 1e-6, "CONTROL: fresh selection changes the actual split owner");
assert!(old_cut.distance(new_cut) > 1.0);
let stale = review_8655_markers(&tool, &after);
assert!(stale.iter().all(|p| p.distance(new_cut) < 1e-6), "no unchanged-key selection switch may show the old cut point: {stale:?}");
tool.pointer(&after, &PointerEvent::new(PointerKind::Move, at.x, at.y));
let new_markers = review_8655_markers(&tool, &after);
let actions = tool.pointer(&after, &PointerEvent::new(PointerKind::Down, at.x, at.y));
assert!(scissors_cut_at(&d, line, &actions).distance(new_cut) < 1e-6);
assert_eq!(old_markers.len(), 1, "REGRESSION: valid first selection has feedback");
assert!(old_markers[0].distance(old_cut) < 1e-6);
assert_eq!(new_markers.len(), 1, "REGRESSION: a fresh hover uses the fresh selected owner");
assert!(new_markers[0].distance(new_cut) < 1e-6);
}
#[test]
fn review_8655_scissors_feedback_clears_on_miss_alt_stale_and_leave() {
let (d, _) = doc_with_rect();
let selected = Selection::default();
let paint = paint();
let context = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &selected, &paint) };
let at = Point::new(170.0, 201.0);
let mut tool = AnchorTool::new("scissors");
tool.pointer(&context, &PointerEvent::new(PointerKind::Move, at.x, at.y));
let valid = review_8655_markers(&tool, &context);
// A context change must not keep a geometrically obsolete point visible before rehover.
let stale = ToolContext { zoom: 2.0, smart_guides: false, snap_to_point: false, ..cx(&d, &selected, &paint) };
assert!(tool.overlays(&stale).is_empty(), "CONTROL: stale zoom shows neither guides nor marker");
tool.pointer(&context, &PointerEvent::new(PointerKind::Move, 20.0, 20.0));
assert!(tool.pointer(&context, &PointerEvent::new(PointerKind::Down, 20.0, 20.0)).is_empty());
assert!(tool.overlays(&context).is_empty(), "CONTROL: a true miss has no cut feedback");
tool.pointer(&context, &PointerEvent::new(PointerKind::Move, at.x, at.y));
let alt = Mods { alt: true, ..Mods::default() };
let event = PointerEvent::new(PointerKind::Down, at.x, at.y);
let mut add = AnchorTool::new("addAnchor");
assert_eq!(tool.pointer(&context, &event.with_mods(alt)), add.pointer(&context, &event), "CONTROL: Alt remains Add Anchor Point");
assert!(tool.overlays(&context).is_empty(), "CONTROL: Alt has no Scissors marker");
tool.pointer(&context, &PointerEvent::new(PointerKind::Move, at.x, at.y));
tool.hover_ended(&context);
assert!(tool.overlays(&context).is_empty(), "CONTROL: leaving clears the marker and guides");
assert_eq!(valid.len(), 1, "REGRESSION: the initial valid cut needs visible feedback");
assert!(valid[0].distance(Point::new(170.0, 200.0)) < 1e-6);
}
/// The successful point is owned by path.split's consumer, including endpoint rejection and
/// its canonical anchor threshold. Keep the emitted Down action itself unchanged.
fn review_8655_endpoint_action_controls() -> Vec<(usize, Vec<Point>, Point)> {
let paint = paint();
let (open_doc, rectangle, selected) = scissors_crossing();
let open_cx = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&open_doc, &selected, &paint) };
let mut tool = AnchorTool::new("scissors");
for (anchor, endpoint) in [(0, Point::new(145.0, 90.0)), (1, Point::new(165.0, 130.0))] {
tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Move, endpoint.x, endpoint.y));
let endpoint_markers = review_8655_markers(&tool, &open_cx);
let actions = tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Down, endpoint.x, endpoint.y));
let [Action::Exec(command, args)] = &actions[..] else { panic!("CONTROL: preserve the original endpoint Down action: {actions:?}") };
assert_eq!(command, "path.split");
assert_eq!(args["anchor"], anchor);
let owner = NodeId(args["id"].as_u64().unwrap());
assert_ne!(owner, rectangle);
assert!(!open_doc.node(owner).unwrap().path_data().unwrap().subpaths[0].closed);
assert_eq!(scissors_cut_at(&open_doc, owner, &actions), endpoint);
assert!(endpoint_markers.is_empty(), "an open path's end point has no successful-cut marker");
tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Up, endpoint.x, endpoint.y));
}
let interior = Point::new(155.0, 110.0);
tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Move, interior.x, interior.y));
let interior_markers = review_8655_markers(&tool, &open_cx);
let actions = tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Down, interior.x, interior.y));
let [Action::Exec(_, args)] = &actions[..] else { panic!("CONTROL: interior open path emits split: {actions:?}") };
assert!(args.get("segment").is_some());
let owner = NodeId(args["id"].as_u64().unwrap());
assert!(scissors_cut_at(&open_doc, owner, &actions).distance(interior) < 1e-6);
let (mut d, other_rectangle) = doc_with_rect();
// Keep the unrelated fixture rectangle away: its exact(100,100) anchor must not steal
// the grid contact from the selected near-endpoint cubic.
d.node_mut(other_rectangle).unwrap().transform(vectorcraft_geom::Affine::translate((0.0, 250.0)), true);
d.grid = vectorcraft_doc::GridPrefs { spacing: 10.0, subdivisions: 1 };
let start = Point::new(99.99995, 100.0);
// Explicit collinear cubic handles make t linear; a handle-free rectangle's cubic t
// would be about0.000408 here and would not exercise the consumer's1e-6 threshold.
let path = vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::BezPath::from_vec(vec![
vectorcraft_geom::PathEl::MoveTo(start),
vectorcraft_geom::PathEl::CurveTo(Point::new(133.33328333333333, 100.0), Point::new(166.66661666666666, 100.0), Point::new(199.99995, 100.0)),
vectorcraft_geom::PathEl::LineTo(Point::new(199.99995, 200.0)),
vectorcraft_geom::PathEl::LineTo(Point::new(99.99995, 200.0)),
vectorcraft_geom::PathEl::ClosePath,
]));
let id = d.alloc_id();
d.insert(Some(d.layers[0].id), 1, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap();
let mut selected = Selection::default();
selected.set([id]);
let context = ToolContext { snap_to_grid: true, smart_guides: false, snap_to_point: false, ..cx(&d, &selected, &paint) };
let raw = Point::new(100.1, 100.2);
let mut tool = AnchorTool::new("scissors");
tool.pointer(&context, &PointerEvent::new(PointerKind::Move, raw.x, raw.y));
let markers = review_8655_markers(&tool, &context);
let actions = tool.pointer(&context, &PointerEvent::new(PointerKind::Down, raw.x, raw.y));
let [Action::Exec(command, args)] = &actions[..] else { panic!("CONTROL: near-end grid contact emits split: {actions:?}") };
assert_eq!(command, "path.split");
assert_eq!(args["id"], id.0);
assert_eq!(args["segment"], 0);
let t = args["t"].as_f64().unwrap();
assert!(t > 0.0 && t <= 1e-6, "CONTROL: actual emitted t reaches the consumer's anchor canonicalization: {t}");
let projected = scissors_cut_at(&d, id, &actions);
assert!(projected.distance(Point::new(100.0, 100.0)) < 1e-6);
assert!(projected.distance(start) > 1e-5, "CONTROL: raw curve evaluation differs from the committed canonical anchor");
assert!(scissors_labels(&tool, &context).is_empty(), "grid contact adds no Smart Guide label");
vec![(5, interior_markers, interior), (6, markers, start)]
}
+1 -2
View File
@@ -157,8 +157,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
})
.inner;
if clicked && enabled {
app.ui.palette_open = !app.ui.palette_open;
app.ui.palette_query.clear();
crate::palette::toggle(app);
}
if learn {
let shown = crate::panels::learn::visible(&app.ui);
+105 -7
View File
@@ -6,7 +6,7 @@
use egui::{Align2, FontId, Id, Pos2, Sense, Stroke, vec2};
use serde_json::{Value, json};
use vectorcraft_doc::Unit;
use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, REVOLVE, ROTATION_PRESETS};
use vectorcraft_effects::{BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, REVOLVE, ROTATION_PRESETS};
use crate::state::Dialog;
use crate::theme::Tokens;
@@ -233,11 +233,11 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &
} else if object && d.str("__tab") != "rotation" {
let unit = app.session.general_unit();
if id == CLASSIC_EXTRUDE {
super::three_d_classic::object_controls(ui, d, unit);
super::three_d_classic::object_controls(app, ui, d, unit);
} else if id == CLASSIC_REVOLVE {
super::three_d_classic::revolve_controls(ui, d, unit);
} else if id == EXTRUDE {
extrude_controls(ui, d, unit);
extrude_controls(app, ui, d, unit);
} else {
heading(ui, tl!("Object"));
number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit));
@@ -252,8 +252,108 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &
}
}
/// A Bevel Shape menu entry: (shown label, value, the custom bevel's name and points).
pub(crate) type BevelChoice = (String, Value, Option<(String, Value)>);
/// The entries of [`bevel_choice`]'s menu for form `fields`, and how many are built in. The
/// built-in labels are translated; custom bevels show their names as they are. The effect's own
/// custom bevel, the panel's [`OWN_BEVEL`] else the form's, is listed unless the file lists it by
/// name with the same points; while another entry has its label, " (document)" is added to it.
pub(crate) fn bevel_options(app: &VectorcraftApp, fields: &serde_json::Map<String, Value>, effect: &str) -> (Vec<BevelChoice>, usize) {
let mut options: Vec<BevelChoice> = super::effect::own_choices(effect, "bevel", false)
.unwrap_or_default()
.into_iter()
.map(|(label, value)| (tl!(label).to_string(), json!(value), None))
.collect();
let builtin = options.len();
for b in app.session.bevels.bevels() {
options.push((b.name.clone(), json!("custom"), Some((b.name.clone(), b.profile_json()))));
}
let custom = fields.get("bevel").and_then(Value::as_str) == Some("custom");
let own = match fields.get(OWN_BEVEL).and_then(Value::as_array).map(Vec::as_slice) {
Some([n, p]) => Some((n.as_str().unwrap_or_default().to_string(), p.clone())),
_ => fields
.get(BEVEL_PROFILE)
.filter(|p| custom && !p.is_null())
.map(|p| (fields.get(BEVEL_NAME).and_then(Value::as_str).unwrap_or_default().to_string(), p.clone())),
};
if let Some((n, p)) = own
&& !options[builtin..].iter().any(|(_, _, c)| c.as_ref().is_some_and(|(cn, cp)| *cn == n && *cp == p))
{
let mut shown = if n.is_empty() { tl!("Custom").to_string() } else { n.clone() };
// Each pass makes the label longer, so this ends once no entry has it.
while options.iter().any(|(l, _, _)| *l == shown) {
shown = crate::i18n::fmt(tl!("{name} (document)"), &[("name", &shown)]);
}
options.push((shown, json!("custom"), Some((n, p))));
}
(options, builtin)
}
/// The form field where the 3D and Materials panel puts the first selected effect's custom bevel,
/// `[name, points]`, so Bevel Shape lists it while a mixed selection unsets the shown bevel.
pub(crate) const OWN_BEVEL: &str = "__ownBevel";
/// The Bevel Shape menu of Extrude & Bevel and Extrude & Bevel (Classic) (`effect`): None and the
/// built-in shapes, then the custom bevels of the bevels file, and the effect's own custom bevel
/// when the file does not list it (a document from elsewhere carries its points). Picking a
/// custom bevel stores its name and a copy of its points. In the 3D and Materials panel, Edit
/// Bevels… opens the bevels file (`__editBevels`, which the panel runs).
pub(super) fn bevel_choice(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, effect: &str) {
const KEY: &str = "bevel";
let (options, builtin) = bevel_options(app, &d.fields, effect);
let name = d.fields.get(BEVEL_NAME).and_then(Value::as_str).unwrap_or_default().to_string();
let points = d.fields.get(BEVEL_PROFILE).filter(|v| !v.is_null()).cloned();
let custom = d.fields.get(KEY).and_then(Value::as_str) == Some("custom");
let is = |c: &Option<(String, Value)>| c.as_ref().is_some_and(|(n, p)| *n == name && Some(p) == points.as_ref());
let default = vectorcraft_effects::default_params(effect).and_then(|p| p.get(KEY).cloned()).unwrap_or(Value::Null);
let mixed = d.fields.get(KEY).is_some_and(Value::is_null);
let value = d.fields.get(KEY).filter(|v| !v.is_null()).cloned().unwrap_or_else(|| default.clone());
let current = if custom {
options[builtin..].iter().position(|(_, _, c)| is(c)).map(|i| i + builtin)
} else {
options[..builtin].iter().position(|(_, v, _)| *v == value)
};
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
label(ui, tl!("Bevel Shape"));
let labels: Vec<&str> = options.iter().map(|(l, _, _)| l.as_str()).collect();
let shown = current.and_then(|i| labels.get(i)).copied().unwrap_or("");
let width = VALUE_W + rail_width(ui) + 6.0;
// Marked by index, not label: a custom bevel's name can match another entry's label.
let picked = widgets::combo(ui, ("three-d-choice", KEY), shown, width, |ui| {
let mut chosen = None;
for (i, l) in labels.iter().enumerate() {
if ui.add(egui::Button::selectable(current == Some(i), *l)).clicked() {
chosen = Some(i);
}
}
chosen
});
if let Some(k) = picked
&& let Some((_, v, c)) = options.get(k)
{
d.fields.insert(KEY.into(), v.clone());
if let Some((n, p)) = c {
d.fields.insert(BEVEL_NAME.into(), json!(n));
d.fields.insert(BEVEL_PROFILE.into(), p.clone());
}
}
let default_label = options.iter().find(|(_, v, _)| *v == default).map_or("", |(l, _, _)| l.as_str());
if reset_dot(ui, KEY, mixed || value != default, default_label) {
d.fields.insert(KEY.into(), default.clone());
}
});
if d.bool("__panel") {
let enabled = app.session.bevels.path().is_some();
if ui.add_enabled(enabled, egui::Button::new(tl!("Edit Bevels…"))).clicked() {
d.fields.insert("__editBevels".into(), json!(true));
}
}
}
/// Extrude & Bevel's depth, twist, taper, cap and bevel.
fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
fn extrude_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
heading(ui, tl!("Object"));
number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit));
number(ui, d, "twist", tl!("Twist"), (0.0, 360.0), "°", 1, None);
@@ -261,9 +361,7 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]);
ui.add_space(10.0);
bevel_heading(ui, d);
let shapes: Vec<(Value, &str)> =
super::effect::own_choices(EXTRUDE, "bevel", false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect();
choice(ui, d, "bevel", tl!("Bevel Shape"), &shapes);
bevel_choice(app, ui, d, EXTRUDE);
ui.add_enabled_ui(d.str("bevel") != "none", |ui| {
number(ui, d, "bevelWidth", tl!("Width"), (0.0, 1000.0), "", 1, Some(unit));
number(ui, d, "bevelHeight", tl!("Height"), (0.0, 1000.0), "", 1, Some(unit));
@@ -13,15 +13,15 @@ use super::revolve::{c3, choice, heading, label, light_list, light_record, numbe
use crate::state::Dialog;
use crate::theme::Tokens;
/// Depth and cap, then the bevel: its shape, its height and whether it is added around the shape
/// or carved into it.
pub(super) fn object_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
/// Depth and cap, then the bevel: its shape (a custom one included), its height and whether it is
/// added around the shape or carved into it.
pub(super) fn object_controls(app: &crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
heading(ui, tl!("Object"));
number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit));
choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]);
ui.add_space(10.0);
heading(ui, c3("Bevel"));
choice(ui, d, "bevel", tl!("Bevel Shape"), &options("bevel"));
super::revolve::bevel_choice(app, ui, d, CLASSIC_EXTRUDE);
ui.add_enabled_ui(d.str("bevel") != "none", |ui| {
number(ui, d, "bevelHeight", tl!("Height"), (1.0, 100.0), "", 1, Some(unit));
toggle(ui, d, "bevelInside", tl!("Bevel Inside"), false);
@@ -438,11 +438,6 @@ pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) {
}
}
/// The values of Extrude & Bevel (Classic)'s `key` as the dropdowns list them, (value, label).
fn options(key: &str) -> Vec<(Value, &'static str)> {
options_of(CLASSIC_EXTRUDE, key)
}
/// The values of classic 3D effect `effect`'s `key` as the dropdowns list them, (value, label).
fn options_of(effect: &str, key: &str) -> Vec<(Value, &'static str)> {
super::effect::own_choices(effect, key, false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect()
+11
View File
@@ -587,6 +587,7 @@ font-technology Variable Променливи
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Изглед „Колело“
Box View Изглед „Квадрат“
Show Out-of-Gamut Colors Показване на цветовете извън цветовата гама
Box Channel Канал на квадрата
Color box Цветови квадрат
Color Wheel Options Опции на цветното колело
@@ -3142,6 +3143,11 @@ digits Malayalam Малаялам
Edit Arrowheads Редактиране на върхове на стрелки
Edit Arrowheads… Редактиране на върхове на стрелки…
Reload Arrowheads Презареждане на върхове на стрелки
Bevels Фаски
Edit Bevels Редактиране на фаски
Edit Bevels… Редактиране на фаски…
{name} (document) {name} (документ)
Reload Bevels Презареждане на фаски
Reset Rotate View Нулиране на изгледа на завъртане
Rotate View to Selection Завъртане на изгледа спрямо селекцията
Reset the rows to the artwork's colors Нулиране на редовете към цветовете на илюстрацията
@@ -3572,6 +3578,7 @@ digits Malayalam Малаялам
Recent Commands Последни команди
No recent commands Няма последни команди
Type to search commands, tools, panels and effects Въведете текст, за да търсите команди, инструменти, панели и ефекти
Clear Recent Commands Изчистване на последните команди
Search commands Търсене на команди
Search Commands… Търсене на команди…
Secondary Вторичен
@@ -7905,6 +7912,10 @@ 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"
Leaf Vine Листна лоза
Blossom Chain Цветна верига
Pennant Garland Гирлянд от знаменца
Lantern String Низ от фенери
Orbit Lines Орбитални линии
Petal Garland Гирлянд от венчелистчета
Lattice Braid Решетъчна плетка
Can't render this file because it is too large.
+11
View File
@@ -819,6 +819,7 @@
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Prikaz kotača
Box View Prikaz kvadrata
Show Out-of-Gamut Colors Prikaži boje izvan gamuta
Box Channel Kanal kvadrata
Color box Kvadrat boje
Color Wheel Options Opcije kotača boja
@@ -4323,6 +4324,11 @@ theme Appearance Izgled
Edit Arrowheads Uredi vrhove strelica
Edit Arrowheads… Uredi vrhove strelica…
Reload Arrowheads Ponovo učitaj vrhove strelica
Bevels Zakošenja
Edit Bevels Uredi zakošenja
Edit Bevels… Uredi zakošenja…
{name} (document) {name} (dokument)
Reload Bevels Ponovo učitaj zakošenja
Stroke Options Opcije poteza
Width Profiles Profili širine
Apply Graphic Style Primijeni grafički stil
@@ -4649,6 +4655,7 @@ font-technology Variable Varijabilni
Recent Commands Nedavne naredbe
No recent commands Nema nedavnih naredbi
Type to search commands, tools, panels and effects Upišite za pretragu naredbi, alata, panela i efekata
Clear Recent Commands Očisti nedavne naredbe
Dashed Line Isprekidana linija
Panel menu Meni panela
Unembed… Poništi ugrađivanje…
@@ -7960,6 +7967,10 @@ 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"
Leaf Vine Lisnata loza
Blossom Chain Cvjetni lanac
Pennant Garland Girlanda zastavica
Lantern String Niz lampiona
Orbit Lines Orbitalne linije
Petal Garland Vijenac od latica
Lattice Braid Rešetkasti preplet
Can't render this file because it contains an unexpected character in line 2 and column 73.
+15 -1
View File
@@ -888,6 +888,7 @@ arrowhead Target Diana
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Visualització de roda
Box View Visualització de quadre
Show Out-of-Gamut Colors Mostra els colors fora de gama
Box Channel Canal del quadre
Color box Quadre de color
Color Wheel Options Opcions de la roda de colors
@@ -3985,6 +3986,11 @@ digits Malayalam Malaiàlam
Edit Arrowheads Edita les puntes de fletxa
Edit Arrowheads… Edita les puntes de fletxa…
Reload Arrowheads Torna a carregar les puntes de fletxa
Bevels Bisells
Edit Bevels Edita els bisells
Edit Bevels… Edita els bisells…
{name} (document) {name} (document)
Reload Bevels Torna a carregar els bisells
Reset Rotate View Restableix la rotació de la vista
Reset Ruler Origin Restableix l’origen de les regles
Reset the rows to the artwork's colors Restableix les files als colors de l’obra
@@ -4787,6 +4793,7 @@ digits Malayalam Malaiàlam
Recent Commands Ordres recents
No recent commands No hi ha ordres recents
Type to search commands, tools, panels and effects Escriviu per cercar ordres, eines, panells i efectes
Clear Recent Commands Esborra les ordres recents
Search commands Cerca ordres
Search Commands… Cerca ordres…
Search Fonts Folder Cerca a la carpeta de tipus de lletra
@@ -7267,7 +7274,10 @@ liquify-list-end {0}, {1} {0} i {1}
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objecte no té cap efecte 3D (Extrudeix i bisella, Revoluciona, Infla o Gira)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` ha de ser un objecte que només contingui `mode`, amb el valor shaded o wireframe
@msg its 3D effect builds no solid el seu efecte 3D no construeix cap sòlid
@msg bevel must be none or one of {_1} bevel ha de ser none o un de {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel ha de ser none, un de {_1}, o custom amb {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom necessita {BEVEL_PROFILE}, els punts del bisell
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} ha de ser una cadena
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} ha de tenir de 2 a {most} punts [x, y], cada proporció entre 0 i 1, des de [0, 0] (la vora de la tapa) fins a [1, 1] (la paret lateral)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} no pot construir sòlids a partir d’aquesta il·lustració: les seves instàncies de símbol, fusions i grups de retall contenen massa objectes
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} no pot construir un sòlid a partir de la instància del símbol «{symbol}»: la il·lustració del símbol no està disponible
@msg {_1}: the clipping path is too complex to cut the art with {_1}: el traçat de retall és massa complex per retallar-hi la il·lustració
@@ -8949,6 +8959,10 @@ 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"
Leaf Vine Enfiladissa de fulles
Blossom Chain Cadena de flors
Pennant Garland Garlanda de banderins
Lantern String Filera de fanalets
Orbit Lines Línies orbitals
Petal Garland Garlanda de pètals
Lattice Braid Trena reticular
Can't render this file because it is too large.
+15 -1
View File
@@ -831,6 +831,7 @@
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Zobrazení kola
Box View Zobrazení čtverce
Show Out-of-Gamut Colors Zobrazit barvy mimo gamut
Box Channel Kanál čtverce
Color box Barevný čtverec
Color Wheel Options Možnosti barevného kola
@@ -4432,6 +4433,11 @@ theme Appearance Motiv
Edit Arrowheads Upravit šipky
Edit Arrowheads… Upravit šipky…
Reload Arrowheads Znovu načíst šipky
Bevels Zkosení
Edit Bevels Upravit zkosení
Edit Bevels… Upravit zkosení…
{name} (document) {name} (dokument)
Reload Bevels Znovu načíst zkosení
Stroke Options Možnosti tahu
Width Profiles Profily šířky
Apply Graphic Style Použít grafický styl
@@ -4758,6 +4764,7 @@ font-technology Variable Variabilní
Recent Commands Nedávné příkazy
No recent commands Žádné nedávné příkazy
Type to search commands, tools, panels and effects Pište pro hledání příkazů, nástrojů, panelů a efektů
Clear Recent Commands Vymazat seznam nedávných příkazů
Dashed Line Čárkovaná čára
Panel menu Nabídka panelu
Unembed… Zrušit vložení…
@@ -6857,7 +6864,10 @@ mark-style Japanese Japonské
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objekt nemá žádný 3D efekt (Vysunutí a zkosení, Rotační těleso, Nafouknutí ani Otočit)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` musí být objekt obsahující pouze `mode` s hodnotou shaded nebo wireframe
@msg its 3D effect builds no solid jeho 3D efekt nevytváří žádné těleso
@msg bevel must be none or one of {_1} bevel musí být none nebo jedno z {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel musí být none, jedno z {_1} nebo custom s {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom vyžaduje {BEVEL_PROFILE}, body zkosení
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} musí být řetězec
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} musí mít 2 až {most} bodů [x, y], každý podíl mezi 0 a 1, od [0, 0] (hrana čelní plochy) do [1, 1] (boční stěna)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} nemůže z této kresby vytvořit tělesa: její instance symbolů, prolnutí a ořezové skupiny obsahují příliš mnoho objektů
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} nemůže vytvořit těleso z instance symbolu „{symbol}“: kresba symbolu není k dispozici
@msg {_1}: the clipping path is too complex to cut the art with {_1}: ořezová cesta je příliš složitá na oříznutí kresby
@@ -10773,6 +10783,10 @@ 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}
Leaf Vine Listová liána
Blossom Chain Květinový řetěz
Pennant Garland Girlanda praporků
Lantern String Řetěz luceren
Orbit Lines Orbitální čáry
Petal Garland Okvětní girlanda
Lattice Braid Mřížkový cop
Can't render this file because it is too large.
+15 -1
View File
@@ -433,7 +433,10 @@ liquify-list-end {0}, {1} {0} og {1}
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Ekstrudér og facet, Omdrej, Pust op eller Rotér)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` skal være et objekt, der kun indeholder `mode` med værdien shaded eller wireframe
@msg its 3D effect builds no solid dens 3D-effekt danner intet legeme
@msg bevel must be none or one of {_1} bevel skal være none eller en af {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel skal være none, en af {_1} eller custom med {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom kræver {BEVEL_PROFILE}, facettens punkter
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} skal være en streng
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} skal være 2 til {most} punkter [x, y], hver andel mellem 0 og 1, fra [0, 0] (dækfladens kant) til [1, 1] (sidevæggen)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kan ikke danne legemer af denne grafik: dens symbolforekomster, blandinger og beskæringsgrupper indeholder for mange objekter
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kan ikke danne et legeme af forekomsten af symbolet "{symbol}": symbolets grafik er ikke tilgængelig
@msg {_1}: the clipping path is too complex to cut the art with {_1}: beskæringskurven er for kompleks til at skære grafikken med
@@ -3529,6 +3532,7 @@ liquify-list-end {0}, {1} {0} og {1}
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Hjulvisning
Box View Kvadratvisning
Show Out-of-Gamut Colors Vis farver uden for gamut
Box Channel Kvadratets kanal
Color box Farvekvadrat
Color Wheel Options Indstillinger for farvehjul
@@ -6887,6 +6891,11 @@ theme Appearance Udseende
Edit Arrowheads Redigér pilespidser
Edit Arrowheads… Redigér pilespidser…
Reload Arrowheads Genindlæs pilespidser
Bevels Facetter
Edit Bevels Redigér facetter
Edit Bevels… Redigér facetter…
{name} (document) {name} (dokument)
Reload Bevels Genindlæs facetter
Stroke Options Konturindstillinger
Width Profiles Breddeprofiler
Apply Graphic Style Anvend grafikstil
@@ -7202,6 +7211,7 @@ font-technology Variable Variable
Recent Commands Seneste kommandoer
No recent commands Ingen seneste kommandoer
Type to search commands, tools, panels and effects Skriv for at søge i kommandoer, værktøjer, paneler og effekter
Clear Recent Commands Ryd seneste kommandoer
Dashed Line Stiplet linje
Panel menu Panelmenu
Unembed… Ophæv integrering…
@@ -10835,6 +10845,10 @@ 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"
Leaf Vine Bladranke
Blossom Chain Blomsterkæde
Pennant Garland Vimpelguirlande
Lantern String Lygtekæde
Orbit Lines Banekurver
Petal Garland Kronbladsguirlande
Lattice Braid Gitterfletning
Can't render this file because it is too large.
+15 -1
View File
@@ -591,6 +591,7 @@ font-technology Variable Variabel
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Kreisansicht
Box View Quadratansicht
Show Out-of-Gamut Colors Farben außerhalb des Farbumfangs einblenden
Box Channel Kanal des Quadrats
Color box Farbquadrat
Color Wheel Options Optionen für den Farbkreis
@@ -3210,6 +3211,11 @@ digits Malayalam Malayalam
Edit Arrowheads Pfeilspitzen bearbeiten
Edit Arrowheads… Pfeilspitzen bearbeiten…
Reload Arrowheads Pfeilspitzen neu laden
Bevels Abgeflachte Kanten
Edit Bevels Abgeflachte Kanten bearbeiten
Edit Bevels… Abgeflachte Kanten bearbeiten…
{name} (document) {name} (Dokument)
Reload Bevels Abgeflachte Kanten neu laden
Rotate View Ansicht drehen
Reset Rotate View Ansichtsdrehung zurücksetzen
Rotate View to Selection Ansicht nach Auswahl drehen
@@ -3657,6 +3663,7 @@ digits Malayalam Malayalam
Recent Commands Zuletzt verwendete Befehle
No recent commands Keine zuletzt verwendeten Befehle
Type to search commands, tools, panels and effects Tippen, um Befehle, Werkzeuge, Bedienfelder und Effekte zu suchen
Clear Recent Commands Liste der zuletzt verwendeten Befehle leeren
Search commands Befehle suchen
Search Commands… Befehle suchen…
Secondary Sekundär
@@ -6423,7 +6430,10 @@ lighting Light Licht
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) das Objekt hat keinen 3D-Effekt (Extrudieren und abgeflachte Kante, Kreiseln, Aufblasen oder Drehen)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` muss ein Objekt sein, das nur `mode` mit dem Wert shaded oder wireframe enthält
@msg its 3D effect builds no solid sein 3D-Effekt erzeugt keinen Körper
@msg bevel must be none or one of {_1} bevel muss none oder einer der folgenden Werte sein: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel muss none, einer der Werte {_1} oder custom mit {BEVEL_PROFILE} sein
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom benötigt {BEVEL_PROFILE}, die Punkte der abgeflachten Kante
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} muss eine Zeichenfolge sein
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} muss 2 bis {most} Punkte [x, y] enthalten, jeder Anteil zwischen 0 und 1, von [0, 0] (Kante der Deckfläche) bis [1, 1] (Seitenwand)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kann aus diesem Bildmaterial keine Körper erstellen: Seine Symbolinstanzen, Angleichungen und Schnittgruppen enthalten zu viele Objekte
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kann keinen Körper aus der Instanz des Symbols „{symbol}“ erstellen: Das Bildmaterial des Symbols ist nicht verfügbar
@msg {_1}: the clipping path is too complex to cut the art with {_1}: Der Schnittpfad ist zu komplex, um das Bildmaterial damit zu beschneiden
@@ -10414,6 +10424,10 @@ 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}
Leaf Vine Blätterranke
Blossom Chain Blütenkette
Pennant Garland Wimpelgirlande
Lantern String Laternenkette
Orbit Lines Orbitlinien
Petal Garland Blütengirlande
Lattice Braid Gittergeflecht
Can't render this file because it is too large.
+15 -1
View File
@@ -566,6 +566,7 @@ font-technology Variable Μεταβλητές
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Προβολή τροχού
Box View Προβολή τετραγώνου
Show Out-of-Gamut Colors Εμφάνιση χρωμάτων εκτός χρωματικής γκάμας
Box Channel Κανάλι τετραγώνου
Color box Τετράγωνο χρώματος
Color Wheel Options Επιλογές χρωματικού τροχού
@@ -4069,6 +4070,11 @@ digits Malayalam Μαλαγιάλαμ
Edit Arrowheads Επεξεργασία αιχμών βελών
Edit Arrowheads… Επεξεργασία αιχμών βελών…
Reload Arrowheads Επαναφόρτωση αιχμών βελών
Bevels Λοξοτμήσεις
Edit Bevels Επεξεργασία λοξοτμήσεων
Edit Bevels… Επεξεργασία λοξοτμήσεων…
{name} (document) {name} (έγγραφο)
Reload Bevels Επαναφόρτωση λοξοτμήσεων
Reset Rotate View Επαναφορά περιστροφής προβολής
Rotate View to Selection Περιστροφή προβολής ως προς την επιλογή
Reset the rows to the artwork's colors Επαναφορά γραμμών στα χρώματα του σχεδίου
@@ -4394,6 +4400,7 @@ digits Malayalam Μαλαγιάλαμ
Recent Commands Πρόσφατες εντολές
No recent commands Δεν υπάρχουν πρόσφατες εντολές
Type to search commands, tools, panels and effects Πληκτρολογήστε για αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ
Clear Recent Commands Εκκαθάριση πρόσφατων εντολών
Search commands Αναζήτηση εντολών
Search Commands… Αναζήτηση εντολών…
Secondary Δευτερεύον
@@ -6240,7 +6247,10 @@ variable-list-end {0}, {1} {0} και {1}
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) το αντικείμενο δεν έχει εφέ 3D (Εξώθηση και λοξότμηση, Περιστροφή γύρω από άξονα, Φούσκωμα ή Περιστροφή)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe το `render` πρέπει να είναι αντικείμενο που περιέχει μόνο `mode`, με τιμή shaded ή wireframe
@msg its 3D effect builds no solid το εφέ 3D του δεν δημιουργεί στερεό
@msg bevel must be none or one of {_1} το bevel πρέπει να είναι none ή ένα από τα {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} το bevel πρέπει να είναι none, ένα από τα {_1} ή custom με {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points το bevel custom χρειάζεται το {BEVEL_PROFILE}, τα σημεία της λοξότμησης
@msg {BEVEL_NAME} must be a string το {BEVEL_NAME} πρέπει να είναι συμβολοσειρά
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) το {BEVEL_PROFILE} πρέπει να έχει 2 έως {most} σημεία [x, y], κάθε αναλογία μεταξύ 0 και 1, από [0, 0] (η ακμή της ακραίας όψης) έως [1, 1] (το πλευρικό τοίχωμα)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: δεν μπορούν να δημιουργηθούν στερεά από αυτό το σχέδιο· οι παρουσίες συμβόλων, οι αναμείξεις και οι ομάδες αποκοπής του περιέχουν πάρα πολλά αντικείμενα
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: δεν μπορεί να δημιουργηθεί στερεό από την παρουσία του συμβόλου «{symbol}»· το σχέδιο του συμβόλου δεν είναι διαθέσιμο
@msg {_1}: the clipping path is too complex to cut the art with {_1}: η διαδρομή αποκοπής είναι πολύ σύνθετη για να κόψει το σχέδιο
@@ -8922,6 +8932,10 @@ 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"
Leaf Vine Κληματίδα φύλλων
Blossom Chain Αλυσίδα λουλουδιών
Pennant Garland Γιρλάντα σημαιών
Lantern String Σειρά φαναριών
Orbit Lines Τροχιακές γραμμές
Petal Garland Γιρλάντα πετάλων
Lattice Braid Πλεξούδα πλέγματος
Can't render this file because it is too large.
+15 -1
View File
@@ -611,6 +611,7 @@ font-technology Variable Variables
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Vista de rueda
Box View Vista de cuadro
Show Out-of-Gamut Colors Mostrar colores fuera de gama
Box Channel Canal del cuadro
Color box Cuadro de color
Color Wheel Options Opciones de la rueda de color
@@ -3248,6 +3249,11 @@ digits Malayalam Malayálam
Edit Arrowheads Editar puntas de flecha
Edit Arrowheads… Editar puntas de flecha…
Reload Arrowheads Volver a cargar puntas de flecha
Bevels Biseles
Edit Bevels Editar biseles
Edit Bevels… Editar biseles…
{name} (document) {name} (documento)
Reload Bevels Volver a cargar biseles
Reset Rotate View Restablecer rotación de vista
Rotate View to Selection Rotar vista según la selección
Reset the rows to the artwork's colors Restablecer las filas a los colores de la ilustración
@@ -3690,6 +3696,7 @@ digits Malayalam Malayálam
Recent Commands Comandos recientes
No recent commands No hay comandos recientes
Type to search commands, tools, panels and effects Escriba para buscar comandos, herramientas, paneles y efectos
Clear Recent Commands Borrar comandos recientes
Search commands Buscar comandos
Search Commands… Buscar comandos…
Secondary Secundario
@@ -6830,7 +6837,10 @@ mark-style Japanese Japonesas
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) el objeto no tiene ningún efecto 3D (Extrusión y biselado, Revolución, Inflar o Rotar)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` debe ser un objeto que solo contenga `mode`, con el valor shaded o wireframe
@msg its 3D effect builds no solid su efecto 3D no construye ningún sólido
@msg bevel must be none or one of {_1} bevel debe ser none o uno de estos: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel debe ser none, uno de estos: {_1}, o custom con {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom necesita {BEVEL_PROFILE}, los puntos del bisel
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} debe ser una cadena
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} debe tener de 2 a {most} puntos [x, y], cada proporción entre 0 y 1, desde [0, 0] (el borde de la tapa) hasta [1, 1] (la pared lateral)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} no puede construir sólidos a partir de esta ilustración: sus instancias de símbolo, fusiones y grupos de recorte contienen demasiados objetos
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} no puede construir un sólido a partir de la instancia del símbolo «{symbol}»: la ilustración del símbolo no está disponible
@msg {_1}: the clipping path is too complex to cut the art with {_1}: el trazado de recorte es demasiado complejo para recortar la ilustración
@@ -10666,6 +10676,10 @@ 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"
Leaf Vine Enredadera de hojas
Blossom Chain Cadena de flores
Pennant Garland Guirnalda de banderines
Lantern String Cadena de faroles
Orbit Lines Líneas orbitales
Petal Garland Guirnalda de pétalos
Lattice Braid Trenza reticular
Can't render this file because it is too large.
+15 -1
View File
@@ -817,6 +817,7 @@
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Ympyränäkymä
Box View Ruutunäkymä
Show Out-of-Gamut Colors Näytä väriavaruuden ulkopuoliset värit
Box Channel Ruudun kanava
Color box Väriruutu
Color Wheel Options Väriympyrän asetukset
@@ -4349,6 +4350,11 @@ theme Appearance Ulkoasu
Edit Arrowheads Muokkaa nuolenkärkiä
Edit Arrowheads… Muokkaa nuolenkärkiä…
Reload Arrowheads Lataa nuolenkärjet uudelleen
Bevels Viisteet
Edit Bevels Muokkaa viisteitä
Edit Bevels… Muokkaa viisteitä…
{name} (document) {name} (asiakirja)
Reload Bevels Lataa viisteet uudelleen
Stroke Options Viivan asetukset
Width Profiles Leveysprofiilit
Apply Graphic Style Käytä grafiikkatyyliä
@@ -4668,6 +4674,7 @@ font-technology Variable Muuttuvat
Recent Commands Viimeisimmät komennot
No recent commands Ei viimeisimpiä komentoja
Type to search commands, tools, panels and effects Kirjoita hakeaksesi komentoja, työkaluja, paneeleita ja tehosteita
Clear Recent Commands Tyhjennä viimeisimmät komennot
Dashed Line Katkoviiva
Panel menu Paneelivalikko
Unembed… Poista upotus…
@@ -6758,7 +6765,10 @@ mark-style Japanese Japanilainen
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektilla ei ole 3D-tehostetta (Pursota ja viistä, Pyöräytä, Täytä ilmalla tai Kierrä)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` on oltava objekti, jossa on vain `mode` arvolla shaded tai wireframe
@msg its 3D effect builds no solid sen 3D-tehoste ei muodosta kappaletta
@msg bevel must be none or one of {_1} bevel-arvon on oltava none tai jokin seuraavista: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel-arvon on oltava none, jokin seuraavista: {_1}, tai custom yhdessä arvon {BEVEL_PROFILE} kanssa
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom tarvitsee arvon {BEVEL_PROFILE}, viisteen pisteet
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} on oltava merkkijono
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) arvossa {BEVEL_PROFILE} on oltava vähintään 2 ja enintään {most} pistettä [x, y], kukin osuus väliltä 0 ja 1, pisteestä [0, 0] (päätypinnan reuna) pisteeseen [1, 1] (sivuseinä)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} ei voi muodostaa kappaleita tästä kuvituksesta: sen symbolien esiintymät, sulautukset ja leikkausryhmät sisältävät liikaa objekteja
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} ei voi muodostaa kappaletta symbolin ”{symbol}” esiintymästä: symbolin kuvitus ei ole käytettävissä
@msg {_1}: the clipping path is too complex to cut the art with {_1}: leikkauspolku on liian monimutkainen kuvituksen leikkaamiseen
@@ -9005,6 +9015,10 @@ 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"
Leaf Vine Lehtiköynnös
Blossom Chain Kukkaketju
Pennant Garland Viiririvistö
Lantern String Lyhtyketju
Orbit Lines Kiertoradan viivat
Petal Garland Terälehtiköynnös
Lattice Braid Ristikkopunos
Can't render this file because it is too large.
+15 -1
View File
@@ -612,6 +612,7 @@ font-technology Variable Variables
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Affichage roue
Box View Affichage carré
Show Out-of-Gamut Colors Afficher les couleurs hors gamme
Box Channel Couche du carré
Color box Carré de couleur
Color Wheel Options Options de la roue chromatique
@@ -3236,6 +3237,11 @@ digits Malayalam Malayalam
Edit Arrowheads Modifier les pointes de flèche
Edit Arrowheads… Modifier les pointes de flèche…
Reload Arrowheads Recharger les pointes de flèche
Bevels Biseaux
Edit Bevels Modifier les biseaux
Edit Bevels… Modifier les biseaux…
{name} (document) {name} (document)
Reload Bevels Recharger les biseaux
Reset Rotate View Réinitialiser la rotation de l’affichage
Rotate View to Selection Faire pivoter l’affichage selon la sélection
Reset the rows to the artwork's colors Réinitialiser les lignes avec les couleurs de l’illustration
@@ -3678,6 +3684,7 @@ digits Malayalam Malayalam
Recent Commands Commandes récentes
No recent commands Aucune commande récente
Type to search commands, tools, panels and effects Tapez pour rechercher des commandes, des outils, des panneaux et des effets
Clear Recent Commands Effacer les commandes récentes
Search commands Chercher des commandes
Search Commands… Rechercher des commandes…
Secondary Secondaire
@@ -6422,7 +6429,10 @@ lighting Light Lumière
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objet n’a aucun effet 3D (Extrusion et biseautage, Révolution, Gonfler ou Rotation)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` doit être un objet ne contenant que `mode`, avec la valeur shaded ou wireframe
@msg its 3D effect builds no solid son effet 3D ne construit aucun volume
@msg bevel must be none or one of {_1} bevel doit valoir none ou l’une de ces valeurs : {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel doit valoir none, l’une des valeurs {_1}, ou custom avec {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom nécessite {BEVEL_PROFILE}, les points du biseau
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} doit être une chaîne
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} doit contenir de 2 à {most} points [x, y], chaque proportion entre 0 et 1, de [0, 0] (le bord de la face) à [1, 1] (la paroi latérale)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} ne peut pas construire de volumes à partir de cette illustration : ses occurrences de symbole, dégradés de formes et groupes de découpe contiennent trop d’objets
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} ne peut pas construire de volume à partir de l’occurrence du symbole « {symbol} » : l’illustration du symbole n’est pas disponible
@msg {_1}: the clipping path is too complex to cut the art with {_1} : le tracé de découpe est trop complexe pour découper l’illustration
@@ -10736,6 +10746,10 @@ 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
Leaf Vine Liane feuillue
Blossom Chain Chaîne de fleurs
Pennant Garland Guirlande de fanions
Lantern String Guirlande de lanternes
Orbit Lines Lignes orbitales
Petal Garland Guirlande de pétales
Lattice Braid Tresse en treillis
Can't render this file because it is too large.
+6
View File
@@ -3799,6 +3799,7 @@ arrowhead Feather પીંછું
No recent commands કોઈ તાજેતરના આદેશો નથી
Type to search commands, tools, panels and effects આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધવા માટે લખો
Recent તાજેતરના
Clear Recent Commands તાજેતરના આદેશો સાફ કરો
Search commands આદેશો શોધો
Search images છબીઓ શોધો
Searching… શોધી રહ્યા છીએ…
@@ -4816,6 +4817,7 @@ arrowhead Feather પીંછું
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View વ્હીલ વ્યૂ
Box View બૉક્સ વ્યૂ
Show Out-of-Gamut Colors ગેમટ બહારના રંગો બતાવો
Box Channel બૉક્સ ચેનલ
Color box રંગ બૉક્સ
Color Wheel Options રંગ વ્હીલ વિકલ્પો
@@ -5652,6 +5654,10 @@ swatch [Registration] [રજિસ્ટ્રેશન]
Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર
Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine"
Leaf Vine પાંદડાની વેલ
Blossom Chain ફૂલોની સાંકળ
Pennant Garland ધ્વજપટ્ટીની માળા
Lantern String ફાનસની હાર
Orbit Lines ભ્રમણકક્ષાની રેખાઓ
Petal Garland પાંખડીઓની માળા
Lattice Braid જાળી વેણી
Can't render this file because it contains an unexpected character in line 72 and column 5.
+15 -1
View File
@@ -1274,6 +1274,7 @@ arrowhead Feather पंख
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View व्हील व्यू
Box View बॉक्स व्यू
Show Out-of-Gamut Colors गैमट से बाहर के रंग दिखाएँ
Box Channel बॉक्स चैनल
Color box कलर बॉक्स
Color Wheel Options कलर व्हील ऑप्शन्स
@@ -4611,6 +4612,11 @@ arrowhead Feather पंख
Edit Arrowheads एरोहेड्स संपादित करें
Edit Arrowheads… एरोहेड्स संपादित करें…
Reload Arrowheads एरोहेड्स फिर से लोड करें
Bevels बेवल्स
Edit Bevels बेवल्स संपादित करें
Edit Bevels… बेवल्स संपादित करें…
{name} (document) {name} (दस्तावेज़)
Reload Bevels बेवल्स फिर से लोड करें
Reset Rotate View व्यू घुमाएँ रीसेट करें
Reset Ruler Origin रूलर ओरिजिन रीसेट करें
Reset Symbol Instance सिंबल इंस्टेंस रीसेट करें
@@ -5142,6 +5148,7 @@ arrowhead Feather पंख
Recent Commands हाल के आदेश
No recent commands कोई हाल का आदेश नहीं
Type to search commands, tools, panels and effects आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजने के लिए टाइप करें
Clear Recent Commands हाल के आदेश साफ़ करें
Search commands आदेश खोजें
Search Commands… कमांड खोजें…
Search Fonts Folder खोज फ़ॉन्ट फ़ोल्डर
@@ -9172,7 +9179,10 @@ liquify-list-end {0}, {1} {0} और {1}
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) ऑब्जेक्ट पर कोई 3D इफ़ेक्ट नहीं है (एक्सट्रूडेड और बेवेल, रिवॉल्व, फुलाएँ या घुमाव)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` केवल `mode` वाला ऑब्जेक्ट होना चाहिए, जिसका मान shaded या wireframe हो
@msg its 3D effect builds no solid इसका 3D इफ़ेक्ट कोई ठोस नहीं बनाता
@msg bevel must be none or one of {_1} bevel को none या {_1} में से एक होना चाहिए
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel को none, {_1} में से एक, या {BEVEL_PROFILE} के साथ custom होना चाहिए
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom के लिए {BEVEL_PROFILE} चाहिए, यानी बेवल के बिंदु
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} एक स्ट्रिंग होना चाहिए
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} में 2 से {most} [x, y] बिंदु होने चाहिए, हर हिस्सा 0 और 1 के बीच, [0, 0] (सिरे की सतह का किनारा) से [1, 1] (बगल की दीवार) तक
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} इस आर्ट से ठोस नहीं बना सकता: इसके सिंबल इंस्टेंस, ब्लेंड और क्लिपिंग ग्रुप में बहुत अधिक ऑब्जेक्ट हैं
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} सिंबल "{symbol}" के इंस्टेंस से ठोस नहीं बना सकता: सिंबल का आर्ट उपलब्ध नहीं है
@msg {_1}: the clipping path is too complex to cut the art with {_1}: क्लिपिंग पाथ आर्ट को काटने के लिए बहुत जटिल है
@@ -10379,6 +10389,10 @@ 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}
Leaf Vine पत्तों की बेल
Blossom Chain फूलों की शृंखला
Pennant Garland झंडियों की माला
Lantern String लालटेन की शृंखला
Orbit Lines कक्षीय रेखाएँ
Petal Garland पंखुड़ी माला
Lattice Braid जाली चोटी
Can't render this file because it is too large.
+15 -1
View File
@@ -815,6 +815,7 @@ arrowhead Target Céltábla
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Körnézet
Box View Négyzetnézet
Show Out-of-Gamut Colors Színtartományon kívüli színek megjelenítése
Box Channel Négyzet csatornája
Color box Színnégyzet
Color Wheel Options Színkör beállításai
@@ -3824,6 +3825,11 @@ mark-style Japanese Japán
Edit Arrowheads Nyílhegyek szerkesztése
Edit Arrowheads… Nyílhegyek szerkesztése…
Reload Arrowheads Nyílhegyek újratöltése
Bevels Élletörések
Edit Bevels Élletörések szerkesztése
Edit Bevels… Élletörések szerkesztése…
{name} (document) {name} (dokumentum)
Reload Bevels Élletörések újratöltése
Reset Rotate View Nézetforgatás visszaállítása
Rotate View to Selection Nézet elforgatása a kijelöléshez
Reset the rows to the artwork's colors Sorok visszaállítása a grafika színeire
@@ -4324,6 +4330,7 @@ mark-style Japanese Japán
Recent Commands Legutóbbi parancsok
No recent commands Nincsenek legutóbbi parancsok
Type to search commands, tools, panels and effects Gépeljen parancsok, eszközök, panelek és effektusok kereséséhez
Clear Recent Commands Legutóbbi parancsok listájának törlése
Search commands Parancsok keresése
Search Commands… Parancsok keresése…
Search Fonts Folder Keresés betűtípusmappában
@@ -6842,7 +6849,10 @@ variable-list-end {0}, {1} {0} és {1}
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) az objektumnak nincs 3D effektusa (Kihúzás és élletörés, Forgatás tengely körül, Felfújás vagy Elforgatás)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe a `render` csak `mode` mezőt tartalmazó objektum lehet, shaded vagy wireframe értékkel
@msg its 3D effect builds no solid a 3D effektusa nem hoz létre testet
@msg bevel must be none or one of {_1} a bevel értéke none vagy ezek egyike lehet: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} a bevel értéke none, ezek egyike: {_1}, vagy custom lehet {BEVEL_PROFILE} megadásával
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points a bevel custom értékéhez {BEVEL_PROFILE} kell, az élletörés pontjai
@msg {BEVEL_NAME} must be a string {BEVEL_NAME}: karakterlánc kell
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE}: legalább 2 és legfeljebb {most} [x, y] pont kell, minden arány 0 és 1 között, [0, 0]-tól (a fedőlap éle) [1, 1]-ig (az oldalfal)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: ebből a rajzból nem hozható létre test: a szimbólumpéldányai, összemosásai és vágócsoportjai túl sok objektumot tartalmaznak
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: nem hozható létre test a(z) „{symbol}” szimbólum példányából: a szimbólum rajza nem érhető el
@msg {_1}: the clipping path is too complex to cut the art with {_1}: a vágóútvonal túl összetett a rajz kivágásához
@@ -10762,6 +10772,10 @@ 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}
Leaf Vine Leveles inda
Blossom Chain Virágfüzér
Pennant Garland Zászlófüzér
Lantern String Lámpásfüzér
Orbit Lines Pályavonalak
Petal Garland Sziromfüzér
Lattice Braid Rácsfonat
Can't render this file because it is too large.
+15 -1
View File
@@ -318,7 +318,10 @@
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objek tidak memiliki efek 3D (Ekstrusi & bevel, Revolusi, Gelembungkan, atau Putar)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` harus berupa objek yang hanya berisi `mode`, bernilai shaded atau wireframe
@msg its 3D effect builds no solid efek 3D-nya tidak membangun bentuk padat
@msg bevel must be none or one of {_1} bevel harus none atau salah satu dari {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel harus none, salah satu dari {_1}, atau custom dengan {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom memerlukan {BEVEL_PROFILE}, yaitu titik-titik bevel
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} harus berupa string
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} harus berisi 2 sampai {most} titik [x, y], masing-masing bernilai antara 0 dan 1, dari [0, 0] (tepi tutup) hingga [1, 1] (dinding samping)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} tidak dapat membangun bentuk padat dari karya ini: instans simbol, blend, dan grup klipingnya berisi terlalu banyak objek
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} tidak dapat membangun bentuk padat dari instans simbol "{symbol}": karya simbol tidak tersedia
@msg {_1}: the clipping path is too complex to cut the art with {_1}: jalur kliping terlalu rumit untuk memotong karya
@@ -1409,6 +1412,7 @@
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Tampilan roda
Box View Tampilan kotak
Show Out-of-Gamut Colors Tampilkan warna di luar gamut
Box Channel Saluran kotak
Color box Kotak warna
Color Wheel Options Opsi roda warna
@@ -4756,6 +4760,11 @@ theme Appearance Tampilan
Edit Arrowheads Edit mata panah
Edit Arrowheads… Edit mata panah…
Reload Arrowheads Muat ulang mata panah
Bevels Bentuk bevel
Edit Bevels Edit bentuk bevel
Edit Bevels… Edit bentuk bevel…
{name} (document) {name} (dokumen)
Reload Bevels Muat ulang bentuk bevel
Stroke Options Opsi goresan
Width Profiles Profil lebar
Apply Graphic Style Terapkan gaya grafis
@@ -5071,6 +5080,7 @@ font-technology Variable Variabel
Recent Commands Perintah terbaru
No recent commands Tidak ada perintah terbaru
Type to search commands, tools, panels and effects Ketik untuk mencari perintah, alat, panel, dan efek
Clear Recent Commands Kosongkan perintah terbaru
Dashed Line Garis putus-putus
Panel menu Menu panel
Unembed… Lepaskan sematan…
@@ -8607,6 +8617,10 @@ 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"
Leaf Vine Sulur Daun
Blossom Chain Rangkaian Bunga
Pennant Garland Untaian Panji
Lantern String Rangkaian Lentera
Orbit Lines Garis Orbit
Petal Garland Rangkaian Kelopak
Lattice Braid Anyaman Kisi
Can't render this file because it is too large.
+15 -1
View File
@@ -613,6 +613,7 @@ font-technology Variable Variabili
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Vista ruota
Box View Vista riquadro
Show Out-of-Gamut Colors Mostra colori fuori gamma
Box Channel Canale del riquadro
Color box Riquadro colore
Color Wheel Options Opzioni ruota dei colori
@@ -3295,6 +3296,11 @@ digits Malayalam Malayalam
Edit Arrowheads Modifica punte di freccia
Edit Arrowheads… Modifica punte di freccia…
Reload Arrowheads Ricarica punte di freccia
Bevels Smussi
Edit Bevels Modifica smussi
Edit Bevels… Modifica smussi…
{name} (document) {name} (documento)
Reload Bevels Ricarica smussi
Rotate View Ruota vista
Reset Rotate View Reimposta rotazione vista
Rotate View to Selection Ruota vista in base alla selezione
@@ -3742,6 +3748,7 @@ digits Malayalam Malayalam
Recent Commands Comandi recenti
No recent commands Nessun comando recente
Type to search commands, tools, panels and effects Digita per cercare comandi, strumenti, pannelli ed effetti
Clear Recent Commands Cancella comandi recenti
Search commands Cerca comandi
Search Commands… Cerca comandi…
Secondary Secondario
@@ -6470,7 +6477,10 @@ lighting Light Luce
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l'oggetto non ha alcun effetto 3D (Estrusione e smusso, Rivoluzione, Gonfia o Ruota)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` deve essere un oggetto che contiene solo `mode`, con valore shaded o wireframe
@msg its 3D effect builds no solid il suo effetto 3D non costruisce alcun solido
@msg bevel must be none or one of {_1} bevel deve essere none o uno dei seguenti: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel deve essere none, uno dei seguenti: {_1}, oppure custom con {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom richiede {BEVEL_PROFILE}, i punti dello smusso
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} deve essere una stringa
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} deve contenere da 2 a {most} punti [x, y], ogni proporzione tra 0 e 1, da [0, 0] (il bordo della faccia) a [1, 1] (la parete laterale)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} non può costruire solidi da questo disegno: le sue istanze di simbolo, fusioni e gruppi di ritaglio contengono troppi oggetti
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} non può costruire un solido dall'istanza del simbolo «{symbol}»: il disegno del simbolo non è disponibile
@msg {_1}: the clipping path is too complex to cut the art with {_1}: il tracciato di ritaglio è troppo complesso per ritagliare il disegno
@@ -10448,6 +10458,10 @@ 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}
Leaf Vine Tralcio di foglie
Blossom Chain Catena di fiori
Pennant Garland Ghirlanda di bandierine
Lantern String Fila di lanterne
Orbit Lines Linee orbitali
Petal Garland Ghirlanda di petali
Lattice Braid Intreccio a reticolo
Can't render this file because it is too large.
+15 -1
View File
@@ -868,6 +868,7 @@ digits Malayalam マラヤーラム数字
{name1} {value1}, {name2} {value2} {name1} {value1}、{name2} {value2}
Wheel View ホイール表示
Box View ボックス表示
Show Out-of-Gamut Colors 色域外のカラーを表示
Box Channel ボックスのチャンネル
Color box カラーボックス
Color Wheel Options カラーホイールオプション
@@ -3270,6 +3271,11 @@ mark-style Japanese 日本式
Edit Arrowheads 矢印を編集
Edit Arrowheads… 矢印を編集…
Reload Arrowheads 矢印を再読み込み
Bevels ベベル一覧
Edit Bevels ベベルを編集
Edit Bevels… ベベルを編集…
{name} (document) {name} (ドキュメント)
Reload Bevels ベベルを再読み込み
Reset the rows to the artwork's colors 行をアートワークのカラーにリセット
Color Theme Picker カラーテーマピッカー
Undo Changes 変更を取り消し
@@ -3609,6 +3615,7 @@ mark-style Japanese 日本式
Recent Commands 最近使ったコマンド
No recent commands 最近使ったコマンドはありません
Type to search commands, tools, panels and effects 入力してコマンド、ツール、パネル、効果を検索
Clear Recent Commands 最近使ったコマンドを消去
Search commands コマンドを検索
Secondary セカンダリ
Select All Art on Layer レイヤー上のすべてのアートを選択
@@ -6519,7 +6526,10 @@ lighting Light ライト
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) オブジェクトに 3D 効果 (押し出しとベベル、回転体、膨張、回転) がありません
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` は `mode` だけを持ち、その値が shaded または wireframe のオブジェクトにしてください
@msg its 3D effect builds no solid 3D 効果からソリッドが作成されません
@msg bevel must be none or one of {_1} bevel には none または {_1} のいずれかを指定してください
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel には none、{_1} のいずれか、または {BEVEL_PROFILE} を付けた custom を指定してください
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom にはベベルのポイントを表す {BEVEL_PROFILE} が必要です
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} は文字列にしてください
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} には 2 個から {most} 個の [x, y] ポイントを、各値を 0 から 1 までの割合として、[0, 0] (端面の縁) から [1, 1] (側面の壁) まで指定してください
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} はこのアートからソリッドを作成できません。シンボルインスタンス、ブレンド、クリッピンググループに含まれるオブジェクトが多すぎます
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} はシンボル「{symbol}」のインスタンスからソリッドを作成できません。シンボルのアートを使用できません
@msg {_1}: the clipping path is too complex to cut the art with {_1}: クリッピングパスが複雑すぎるため、アートを切り抜けません
@@ -10511,6 +10521,10 @@ 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}
Leaf Vine 葉のつる
Blossom Chain 花の連なり
Pennant Garland 三角旗のガーランド
Lantern String ランタンの連なり
Orbit Lines 軌道線
Petal Garland 花びらのガーランド
Lattice Braid 格子編み
Can't render this file because it is too large.
+15 -1
View File
@@ -2941,6 +2941,7 @@
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View წრის ხედი
Box View კვადრატის ხედი
Show Out-of-Gamut Colors ფერთა გამის გარეთ მყოფი ფერების ჩვენება
Box Channel კვადრატის არხი
Color box ფერის კვადრატი
Color Wheel Options ფერთა წრის პარამეტრები
@@ -6169,6 +6170,11 @@ theme Appearance იერსახე
Edit Arrowheads ისრის წვერების რედაქტირება
Edit Arrowheads… ისრის წვერების რედაქტირება…
Reload Arrowheads ისრის წვერების ხელახლა ჩატვირთვა
Bevels წაკვეთები
Edit Bevels წაკვეთების რედაქტირება
Edit Bevels… წაკვეთების რედაქტირება…
{name} (document) {name} (დოკუმენტი)
Reload Bevels წაკვეთების ხელახლა ჩატვირთვა
Stroke Options კონტურის პარამეტრები
Width Profiles სიგანის პროფილები
Apply Graphic Style გრაფიკული სტილის გამოყენება
@@ -6459,6 +6465,7 @@ font-technology Variable ცვლადი
Recent Commands ბოლოდროინდელი ბრძანებები
No recent commands ბოლოდროინდელი ბრძანებები არ არის
Type to search commands, tools, panels and effects აკრიფეთ ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების მოსაძებნად
Clear Recent Commands ბოლო ბრძანებების სიის გასუფთავება
Dashed Line ტირეებიანი ხაზი
Panel menu პანელის მენიუ
Unembed… ჩაშენების მოხსნა…
@@ -8179,7 +8186,10 @@ arrowhead Feather ბუმბული
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) ობიექტს არ აქვს 3D ეფექტი (ამოწევა და წაკვეთა, ბრუნვა, გაბერვა ან შემობრუნება)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` უნდა იყოს ობიექტი, რომელიც შეიცავს მხოლოდ `mode`-ს, მნიშვნელობით shaded ან wireframe
@msg its 3D effect builds no solid მისი 3D ეფექტი სხეულს არ ქმნის
@msg bevel must be none or one of {_1} bevel უნდა იყოს none ან ერთ-ერთი: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel უნდა იყოს none, ერთ-ერთი: {_1}, ან custom და {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom მოითხოვს {BEVEL_PROFILE}, წაკვეთის წერტილები
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} უნდა იყოს სტრიქონი
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} უნდა შეიცავდეს 2-დან {most}-მდე [x, y] წერტილს, თითოეული წილი 0-სა და 1-ს შორის, [0, 0]-დან (ბოლო წახნაგის კიდე) [1, 1]-მდე (გვერდითი კედელი)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: ამ ნახატიდან სხეულების შექმნა შეუძლებელია: მისი სიმბოლოს ეგზემპლარები, გადასვლები და მომჭრელი ჯგუფები ზედმეტად ბევრ ობიექტს შეიცავს
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: სიმბოლოს „{symbol}“ ეგზემპლარიდან სხეულის შექმნა შეუძლებელია: სიმბოლოს ნახატი მიუწვდომელია
@msg {_1}: the clipping path is too complex to cut the art with {_1}: მომჭრელი ტრაექტორია ზედმეტად რთულია ნახატის მოსაჭრელად
@@ -11059,6 +11069,10 @@ 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"
Leaf Vine ფოთლების ვაზი
Blossom Chain ყვავილების ჯაჭვი
Pennant Garland ალმების გირლანდა
Lantern String ფარნების ჯაჭვი
Orbit Lines ორბიტული ხაზები
Petal Garland ფურცლების გირლანდა
Lattice Braid ბადის ნაწნავი
Can't render this file because it is too large.
+15 -1
View File
@@ -861,6 +861,7 @@ digits Malayalam 말라얄람어
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View 휠 보기
Box View 상자 보기
Show Out-of-Gamut Colors 색상 범위를 벗어난 색상 표시
Box Channel 상자 채널
Color box 색상 상자
Color Wheel Options 색상환 옵션
@@ -3259,6 +3260,11 @@ mark-style Japanese 일본식
Edit Arrowheads 화살촉 편집
Edit Arrowheads… 화살촉 편집…
Reload Arrowheads 화살촉 다시 불러오기
Bevels 베벨 목록
Edit Bevels 베벨 편집
Edit Bevels… 베벨 편집…
{name} (document) {name}(문서)
Reload Bevels 베벨 다시 불러오기
Reset the rows to the artwork's colors 행을 아트웍 색상으로 재설정
Color Theme Picker 색상 테마 피커
Undo Changes 변경 내용 실행 취소
@@ -3600,6 +3606,7 @@ mark-style Japanese 일본식
Recent Commands 최근 명령
No recent commands 최근 명령 없음
Type to search commands, tools, panels and effects 입력하여 명령, 도구, 패널 및 효과 검색
Clear Recent Commands 최근 명령 목록 지우기
Search commands 명령 검색
Secondary 보조
Select All Art on Layer 레이어의 모든 아트웍 선택
@@ -6440,7 +6447,10 @@ lighting Light 광원
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) 개체에 3D 효과(돌출 및 경사, 회전체, 부풀리기 또는 회전)가 없습니다
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render`는 값이 shaded 또는 wireframe인 `mode`만 있는 객체여야 합니다
@msg its 3D effect builds no solid 3D 효과가 입체를 만들지 않습니다
@msg bevel must be none or one of {_1} bevel은 none 또는 {_1} 중 하나여야 합니다
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel은 none, {_1} 중 하나 또는 {BEVEL_PROFILE}을(를) 함께 지정한 custom이어야 합니다
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom에는 베벨의 포인트인 {BEVEL_PROFILE}이(가) 필요합니다
@msg {BEVEL_NAME} must be a string {BEVEL_NAME}은(는) 문자열이어야 합니다
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE}은(는) 2개에서 {most}개의 [x, y] 포인트여야 하며, 각 값은 0과 1 사이의 비율이고 [0, 0](끝면의 가장자리)에서 [1, 1](옆면 벽)까지여야 합니다
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}은(는) 이 아트로 입체를 만들 수 없습니다. 심볼 인스턴스, 블렌드, 클리핑 그룹에 개체가 너무 많습니다
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}은(는) 심볼 “{symbol}”의 인스턴스로 입체를 만들 수 없습니다. 심볼의 아트를 사용할 수 없습니다
@msg {_1}: the clipping path is too complex to cut the art with {_1}: 클리핑 패스가 너무 복잡하여 아트를 자를 수 없습니다
@@ -10411,6 +10421,10 @@ 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}
Leaf Vine 잎 덩굴
Blossom Chain 꽃사슬
Pennant Garland 깃발 장식
Lantern String 등불 줄
Orbit Lines 궤도 선
Petal Garland 꽃잎 화환
Lattice Braid 격자 땋기
Can't render this file because it is too large.
+15 -1
View File
@@ -1397,6 +1397,7 @@ liquify-list-end {0}, {1} {0} en {1}
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Wielweergave
Box View Vakweergave
Show Out-of-Gamut Colors Kleuren buiten gamut tonen
Box Channel Kanaal van het vak
Color box Kleurvak
Color Wheel Options Opties voor kleurenwiel
@@ -4757,6 +4758,11 @@ theme Appearance Vormgeving
Edit Arrowheads Pijlpunten bewerken
Edit Arrowheads… Pijlpunten bewerken…
Reload Arrowheads Pijlpunten opnieuw laden
Bevels Afschuiningen
Edit Bevels Afschuiningen bewerken
Edit Bevels… Afschuiningen bewerken…
{name} (document) {name} (document)
Reload Bevels Afschuiningen opnieuw laden
Stroke Options Lijnopties
Width Profiles Breedteprofielen
Apply Graphic Style Grafische stijl toepassen
@@ -5072,6 +5078,7 @@ font-technology Variable Variabel
Recent Commands Recente opdrachten
No recent commands Geen recente opdrachten
Type to search commands, tools, panels and effects Typ om opdrachten, gereedschappen, panelen en effecten te zoeken
Clear Recent Commands Recente opdrachten wissen
Dashed Line Streepjeslijn
Panel menu Paneelmenu
Unembed… Insluiten ongedaan maken…
@@ -8604,7 +8611,10 @@ mark-style Japanese Japans
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) het object heeft geen 3D-effect (Extruderen en afschuinen, Draaien, Opblazen of Roteren)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` moet een object zijn met alleen `mode`, ingesteld op shaded of wireframe
@msg its 3D effect builds no solid het 3D-effect ervan maakt geen massief object
@msg bevel must be none or one of {_1} bevel moet none of een van {_1} zijn
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel moet none, een van {_1} of custom met {BEVEL_PROFILE} zijn
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom heeft {BEVEL_PROFILE} nodig, de punten van de afschuining
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} moet een tekenreeks zijn
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} moet 2 tot {most} punten [x, y] bevatten, elk aandeel tussen 0 en 1, van [0, 0] (de rand van de bovenkant) tot [1, 1] (de zijwand)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kan van deze illustratie geen massieve objecten maken: de symboolinstanties, vermengingen en knipgroepen ervan bevatten te veel objecten
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kan geen massief object maken van de instantie van symbool "{symbol}": de illustratie van het symbool is niet beschikbaar
@msg {_1}: the clipping path is too complex to cut the art with {_1}: het knippad is te complex om de illustratie mee uit te knippen
@@ -10812,6 +10822,10 @@ 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}
Leaf Vine Bladrank
Blossom Chain Bloemenketting
Pennant Garland Vlaggetjesslinger
Lantern String Lantaarnslinger
Orbit Lines Baanlijnen
Petal Garland Bloemblaadjesslinger
Lattice Braid Rastervlecht
Can't render this file because it is too large.
+15 -1
View File
@@ -780,6 +780,7 @@
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Widok koła
Box View Widok kwadratu
Show Out-of-Gamut Colors Pokaż kolory poza gamutem
Box Channel Kanał kwadratu
Color box Kwadrat koloru
Color Wheel Options Opcje koła kolorów
@@ -4297,6 +4298,11 @@ theme Appearance Wygląd
Edit Arrowheads Edytuj groty strzałek
Edit Arrowheads… Edytuj groty strzałek…
Reload Arrowheads Wczytaj ponownie groty strzałek
Bevels Fazy
Edit Bevels Edytuj fazy
Edit Bevels… Edytuj fazy…
{name} (document) {name} (dokument)
Reload Bevels Wczytaj ponownie fazy
Stroke Options Opcje obrysu
Width Profiles Profile szerokości
Apply Graphic Style Zastosuj styl graficzny
@@ -4601,6 +4607,7 @@ font-technology Variable Zmienne
Recent Commands Ostatnie polecenia
No recent commands Brak ostatnich poleceń
Type to search commands, tools, panels and effects Pisz, aby szukać poleceń, narzędzi, paneli i efektów
Clear Recent Commands Wyczyść listę ostatnich poleceń
Dashed Line Linia przerywana
Panel menu Menu panelu
Unembed… Wyodrębnij…
@@ -6682,7 +6689,10 @@ mark-style Japanese Japońskie
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) obiekt nie ma efektu 3D (Wyciągnięcie i fazowanie, Obrót, Nadmuchanie ani Obróć)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` musi być obiektem zawierającym tylko `mode` o wartości shaded lub wireframe
@msg its 3D effect builds no solid jego efekt 3D nie tworzy żadnej bryły
@msg bevel must be none or one of {_1} bevel musi mieć wartość none lub jedną z: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel musi mieć wartość none, jedną z: {_1}, albo custom z {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom wymaga {BEVEL_PROFILE}, punktów fazy
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} musi być ciągiem znaków
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} musi zawierać od 2 do {most} punktów [x, y], każdy udział od 0 do 1, od [0, 0] (krawędź ściany czołowej) do [1, 1] (ściana boczna)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} nie może utworzyć brył z tej kompozycji: jej wystąpienia symboli, przejścia i grupy przycinające zawierają zbyt wiele obiektów
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} nie może utworzyć bryły z wystąpienia symbolu „{symbol}”: kompozycja symbolu jest niedostępna
@msg {_1}: the clipping path is too complex to cut the art with {_1}: ścieżka przycinająca jest zbyt złożona, aby przyciąć nią kompozycję
@@ -10637,6 +10647,10 @@ 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}
Leaf Vine Liściasta winorośl
Blossom Chain Łańcuch kwiatów
Pennant Garland Girlanda proporczyków
Lantern String Łańcuch lampionów
Orbit Lines Linie orbitalne
Petal Garland Girlanda płatków
Lattice Braid Plecionka kratowa
Can't render this file because it is too large.
+15 -1
View File
@@ -550,6 +550,7 @@ antiAlias Sharp Nítido
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Exibição em Roda
Box View Exibição em Caixa
Show Out-of-Gamut Colors Mostrar Cores Fora do Gamut
Box Channel Canal da Caixa
Color box Caixa de cor
Color Wheel Options Opções da Roda de Cores
@@ -2708,6 +2709,11 @@ digits Malayalam Malaiala
Edit Arrowheads Editar Pontas de Seta
Edit Arrowheads… Editar Pontas de Seta…
Reload Arrowheads Recarregar Pontas de Seta
Bevels Chanfros
Edit Bevels Editar Chanfros
Edit Bevels… Editar Chanfros…
{name} (document) {name} (documento)
Reload Bevels Recarregar Chanfros
Rotate View Girar Visualização
Reset Rotate View Redefinir Visualização Girada
Rotate View to Selection Girar Visualização para a Seleção
@@ -3116,6 +3122,7 @@ digits Malayalam Malaiala
Recent Commands Comandos recentes
No recent commands Nenhum comando recente
Type to search commands, tools, panels and effects Digite para pesquisar comandos, ferramentas, painéis e efeitos
Clear Recent Commands Limpar Comandos Recentes
Search commands Pesquisar comandos
Secondary Secundária
Section Symbol Símbolo de Seção
@@ -6805,7 +6812,10 @@ mark-style Japanese Japonesas
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) o objeto não tem efeito 3D (Extrusão e Bisel, Revolver, Inflar ou Girar)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` deve ser um objeto que contenha apenas `mode`, com o valor shaded ou wireframe
@msg its 3D effect builds no solid seu efeito 3D não constrói nenhum sólido
@msg bevel must be none or one of {_1} bevel deve ser none ou um de {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel deve ser none, um de {_1}, ou custom com {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom precisa de {BEVEL_PROFILE}, os pontos do chanfro
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} deve ser uma string
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} deve ter de 2 a {most} pontos [x, y], cada proporção entre 0 e 1, de [0, 0] (a borda da tampa) a [1, 1] (a parede lateral)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} não pode construir sólidos a partir desta arte: suas instâncias de símbolo, mesclagens e grupos de recorte contêm objetos demais
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} não pode construir um sólido a partir da instância do símbolo “{symbol}”: a arte do símbolo não está disponível
@msg {_1}: the clipping path is too complex to cut the art with {_1}: o caminho de recorte é complexo demais para recortar a arte
@@ -10845,6 +10855,10 @@ 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}
Leaf Vine Trepadeira de folhas
Blossom Chain Corrente de flores
Pennant Garland Guirlanda de bandeirolas
Lantern String Cordão de lanternas
Orbit Lines Linhas orbitais
Petal Garland Guirlanda de pétalas
Lattice Braid Trança em grade
Can't render this file because it is too large.
+15 -1
View File
@@ -609,6 +609,7 @@ font-technology Variable Вариативные
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Вид «Круг»
Box View Вид «Квадрат»
Show Out-of-Gamut Colors Показать цвета вне цветового охвата
Box Channel Канал квадрата
Color box Цветовой квадрат
Color Wheel Options Параметры цветового круга
@@ -3278,6 +3279,11 @@ digits Malayalam Малаялам
Edit Arrowheads Редактировать стрелки
Edit Arrowheads… Редактировать стрелки…
Reload Arrowheads Перезагрузить стрелки
Bevels Фаски
Edit Bevels Редактировать фаски
Edit Bevels… Редактировать фаски…
{name} (document) {name} (документ)
Reload Bevels Перезагрузить фаски
Rotate View Повернуть вид
Reset Rotate View Сбросить поворот вида
Rotate View to Selection Повернуть вид по выделению
@@ -3723,6 +3729,7 @@ digits Malayalam Малаялам
Recent Commands Недавние команды
No recent commands Нет недавних команд
Type to search commands, tools, panels and effects Начните вводить для поиска команд, инструментов, панелей и эффектов
Clear Recent Commands Очистить список недавних команд
Search commands Поиск команд
Search Commands… Поиск команд…
Secondary Вторичный
@@ -6468,7 +6475,10 @@ lighting Light Свет
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) у объекта нет 3D-эффекта (Выдавливание и фаска, Вращение, Надувание или Повернуть)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` должен быть объектом только с полем `mode` со значением shaded или wireframe
@msg its 3D effect builds no solid его 3D-эффект не строит тела
@msg bevel must be none or one of {_1} bevel должен быть none или одним из: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel должен быть none, одним из: {_1}, или custom с {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points для bevel custom нужен {BEVEL_PROFILE}, точки фаски
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} должно быть строкой
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} должен содержать от 2 до {most} точек [x, y], каждая доля от 0 до 1, от [0, 0] (край торца) до [1, 1] (боковая стенка)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: нельзя построить тела из этой иллюстрации: её экземпляры символов, переходы и обтравочные группы содержат слишком много объектов
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: нельзя построить тело из экземпляра символа «{symbol}»: иллюстрация символа недоступна
@msg {_1}: the clipping path is too complex to cut the art with {_1}: обтравочный контур слишком сложен, чтобы обрезать им иллюстрацию
@@ -10829,6 +10839,10 @@ 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"
Leaf Vine Лиственная лоза
Blossom Chain Цветочная цепочка
Pennant Garland Гирлянда флажков
Lantern String Цепочка фонариков
Orbit Lines Орбитальные линии
Petal Garland Гирлянда лепестков
Lattice Braid Решётчатое плетение
Can't render this file because it is too large.
+15 -1
View File
@@ -594,6 +594,7 @@ font-technology Variable Variabla
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Hjulvy
Box View Rutvy
Show Out-of-Gamut Colors Visa färger utanför färgomfånget
Box Channel Rutans kanal
Color box Färgruta
Color Wheel Options Alternativ för färghjulet
@@ -3168,6 +3169,11 @@ digits Malayalam Malayalam
Edit Arrowheads Redigera pilspetsar
Edit Arrowheads… Redigera pilspetsar…
Reload Arrowheads Läs in pilspetsar igen
Bevels Fasningar
Edit Bevels Redigera fasningar
Edit Bevels… Redigera fasningar…
{name} (document) {name} (dokument)
Reload Bevels Läs in fasningar igen
Reset Rotate View Återställ Rotera vy
Rotate View to Selection Rotera vyn efter markeringen
Reset the rows to the artwork's colors Återställ raderna till teckningens färger
@@ -3598,6 +3604,7 @@ digits Malayalam Malayalam
Recent Commands Senaste kommandon
No recent commands Inga senaste kommandon
Type to search commands, tools, panels and effects Skriv för att söka efter kommandon, verktyg, paneler och effekter
Clear Recent Commands Rensa senaste kommandon
Search commands Sök kommandon
Search Commands… Sök kommandon…
Secondary Sekundär
@@ -6335,7 +6342,10 @@ lighting Light Ljus
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Extrudera och fasa, Rotera runt axel, Blås upp eller Rotera)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` måste vara ett objekt som bara innehåller `mode`, med värdet shaded eller wireframe
@msg its 3D effect builds no solid dess 3D-effekt bygger ingen solid
@msg bevel must be none or one of {_1} bevel måste vara none eller något av {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel måste vara none, något av {_1} eller custom med {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom kräver {BEVEL_PROFILE}, fasningens punkter
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} måste vara en sträng
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} måste vara 2 till {most} punkter [x, y], varje andel mellan 0 och 1, från [0, 0] (ändytans kant) till [1, 1] (sidoväggen)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kan inte bygga solider av den här teckningen: dess symbolinstanser, blandningar och urklippsgrupper innehåller för många objekt
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kan inte bygga en solid av instansen av symbolen ”{symbol}”: symbolens teckning är inte tillgänglig
@msg {_1}: the clipping path is too complex to cut the art with {_1}: urklippsbanan är för komplex för att klippa teckningen med
@@ -10866,6 +10876,10 @@ 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
Leaf Vine Bladranka
Blossom Chain Blomkedja
Pennant Garland Vimpelgirlang
Lantern String Lyktgirlang
Orbit Lines Banlinjer
Petal Garland Kronbladsgirlang
Lattice Braid Gallerfläta
Can't render this file because it is too large.
+18 -1
View File
@@ -4120,6 +4120,22 @@ fn three_d_refusals_translate_with_their_values() {
(refuse(vectorcraft_effects::validate_three_d(&rect, CLASSIC_EXTRUDE, &json!({"depth": "deep"}))), "must be a number", vec!["`depth`"]),
(refuse(vectorcraft_effects::validate_three_d(&instance, EXTRUDE, &json!({}))), "the symbol's art isn't available", vec!["Mine 7"]),
(refuse(vectorcraft_effects::three_d_wireframe_in(None, &rect).map(drop)), "has no 3D effect", vec![]),
(
refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"bevel": "wavy"}))),
"or custom with",
vec!["none", "classic", "custom", "bevelProfile"],
),
(
refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"bevel": "custom"}))),
"the bevel's points",
vec!["custom", "bevelProfile"],
),
(refuse(vectorcraft_effects::validate_three_d(&rect, CLASSIC_EXTRUDE, &json!({"bevelName": 3}))), "must be a string", vec!["bevelName"]),
(
refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"bevel": "custom", "bevelProfile": [[0, 0]]}))),
"each share between",
vec!["bevelProfile", "[x, y]", "[0, 0]", "[1, 1]"],
),
];
for (e, english, _) in &errors {
assert!(e.starts_with("invalid parameters for `effect.apply`: ") && e.contains(english), "{e}");
@@ -6575,7 +6591,8 @@ const NAMED_KEYS: &[(&str, &[&str])] = &[
("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{v}`", &["axis"]),
("balance must be between 0 and 100", &["balance"]),
("before must name a panel", &["before"]),
("bevel must be none or one of {_1}", &["bevel", "none"]),
("bevel custom needs {BEVEL_PROFILE}, the bevel's points", &["bevel", "custom"]),
("bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE}", &["bevel", "none", "custom"]),
("brightness must be dark|mediumDark|mediumLight|light", &["brightness", "dark", "mediumDark", "mediumLight", "light"]),
("clip must be true or false", &["clip"]),
("collapsed must be true or false", &["collapsed"]),
+15 -1
View File
@@ -592,6 +592,7 @@ font-technology Variable Değişken
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Tekerlek Görünümü
Box View Kutu Görünümü
Show Out-of-Gamut Colors Gamut Dışı Renkleri Göster
Box Channel Kutu Kanalı
Color box Renk kutusu
Color Wheel Options Renk Tekerleği Seçenekleri
@@ -3013,6 +3014,11 @@ digits Malayalam Malayalam
Edit Arrowheads Ok Uçlarını Düzenle
Edit Arrowheads… Ok Uçlarını Düzenle…
Reload Arrowheads Ok Uçlarını Yeniden Yükle
Bevels Eğimler
Edit Bevels Eğimleri Düzenle
Edit Bevels… Eğimleri Düzenle…
{name} (document) {name} (belge)
Reload Bevels Eğimleri Yeniden Yükle
Reset Rotate View Döndürme Görünümünü Sıfırla
Rotate View to Selection Görünümü Seçime Döndür
Reset the rows to the artwork's colors Satırları resmin renklerine göre sıfırlayın
@@ -3478,6 +3484,7 @@ digits Malayalam Malayalam
Recent Commands Son komutlar
No recent commands Son komut yok
Type to search commands, tools, panels and effects Komutları, araçları, panelleri ve efektleri aramak için yazın
Clear Recent Commands Son Komutları Temizle
Search commands Komutları arayın
Search Commands… Arama Komutları…
Secondary İkincil
@@ -6160,7 +6167,10 @@ lighting Light Işık
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) nesnenin 3 boyutlu efekti yok (Ekstrüzyon ve Eğim, Eksen Etrafında Döndür, Şişir veya Döndür)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render`, yalnızca değeri shaded veya wireframe olan `mode` içeren bir nesne olmalıdır
@msg its 3D effect builds no solid 3 boyutlu efekti hiçbir katı oluşturmuyor
@msg bevel must be none or one of {_1} bevel, none veya {_1} değerlerinden biri olmalıdır
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel; none, {_1} değerlerinden biri veya {BEVEL_PROFILE} ile custom olmalıdır
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom için {BEVEL_PROFILE}, yani eğimin noktaları gerekir
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} bir dize olmalıdır
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE}, 2 ile {most} arasında [x, y] noktası olmalıdır; her oran 0 ile 1 arasında, [0, 0] (uç yüzeyin kenarı) ile [1, 1] (yan duvar) arasında
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} bu resimden katı oluşturamaz: sembol örnekleri, karışımları ve kırpma grupları çok fazla nesne içeriyor
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}, “{symbol}” sembolünün örneğinden katı oluşturamaz: sembolün resmi kullanılamıyor
@msg {_1}: the clipping path is too complex to cut the art with {_1}: kırpma yolu resmi kesmek için çok karmaşık
@@ -10731,6 +10741,10 @@ 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}
Leaf Vine Yapraklı sarmaşık
Blossom Chain Çiçek zinciri
Pennant Garland Bayrak süsü
Lantern String Fener dizisi
Orbit Lines Yörünge Çizgileri
Petal Garland Taç Yaprağı Çelengi
Lattice Braid Kafes Örgü
Can't render this file because it is too large.
+15 -1
View File
@@ -607,6 +607,7 @@ font-technology Variable Варіативні
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Вигляд «Коло»
Box View Вигляд «Квадрат»
Show Out-of-Gamut Colors Показати кольори поза колірним охопленням
Box Channel Канал квадрата
Color box Колірний квадрат
Color Wheel Options Параметри колірного кола
@@ -3287,6 +3288,11 @@ digits Malayalam Малаялам
Edit Arrowheads Редагувати стрілки
Edit Arrowheads… Редагувати стрілки…
Reload Arrowheads Перезавантажити стрілки
Bevels Фаски
Edit Bevels Редагувати фаски
Edit Bevels… Редагувати фаски…
{name} (document) {name} (документ)
Reload Bevels Перезавантажити фаски
Rotate View Повернути вид
Reset Rotate View Скинути поворот виду
Rotate View to Selection Повернути вид за виділенням
@@ -3734,6 +3740,7 @@ digits Malayalam Малаялам
Recent Commands Нещодавні команди
No recent commands Немає нещодавніх команд
Type to search commands, tools, panels and effects Почніть вводити для пошуку команд, інструментів, панелей та ефектів
Clear Recent Commands Очистити список нещодавніх команд
Search commands Пошук команд
Search Commands… Пошук команд…
Secondary Вторинний
@@ -6450,7 +6457,10 @@ lighting Light Світло
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) об’єкт не має 3D-ефекту (Видавлювання та фаска, Обертання, Надування або Повернути)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` має бути об’єктом лише з полем `mode` зі значенням shaded або wireframe
@msg its 3D effect builds no solid його 3D-ефект не будує тіла
@msg bevel must be none or one of {_1} bevel має бути none або одним з: {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel має бути none, одним з: {_1}, або custom з {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points для bevel custom потрібен {BEVEL_PROFILE}, точки фаски
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} має бути рядком
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} має містити від 2 до {most} точок [x, y], кожна частка від 0 до 1, від [0, 0] (край торця) до [1, 1] (бічна стінка)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: не вдається побудувати тіла з цієї ілюстрації: її екземпляри символів, переходи та відсічні групи містять забагато об’єктів
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: не вдається побудувати тіло з екземпляра символу «{symbol}»: ілюстрація символу недоступна
@msg {_1}: the clipping path is too complex to cut the art with {_1}: відсічний контур надто складний, щоб обрізати ним ілюстрацію
@@ -10424,6 +10434,10 @@ 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}
Leaf Vine Листяна лоза
Blossom Chain Квітковий ланцюжок
Pennant Garland Гірлянда прапорців
Lantern String Ланцюжок ліхтариків
Orbit Lines Орбітальні лінії
Petal Garland Гірлянда пелюсток
Lattice Braid Ґратчасте плетіння
Can't render this file because it is too large.
+15 -1
View File
@@ -726,6 +726,7 @@ font-technology Variable Biến thiên
{name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2}
Wheel View Hiển thị bánh xe
Box View Hiển thị hộp
Show Out-of-Gamut Colors Hiện màu ngoài dải màu
Box Channel Kênh của hộp
Color box Hộp màu
Color Wheel Options Tùy chọn bánh xe màu
@@ -3598,6 +3599,11 @@ mark-style Japanese Kiểu Nhật
Edit Arrowheads Chỉnh sửa đầu mũi tên
Edit Arrowheads… Chỉnh sửa đầu mũi tên…
Reload Arrowheads Tải lại đầu mũi tên
Bevels Các kiểu vát
Edit Bevels Chỉnh sửa kiểu vát
Edit Bevels… Chỉnh sửa kiểu vát…
{name} (document) {name} (tài liệu)
Reload Bevels Tải lại kiểu vát
Rotate View Xoay chế độ xem
Reset Rotate View Đặt lại xoay chế độ xem
Rotate View to Selection Xoay chế độ xem theo vùng chọn
@@ -4088,6 +4094,7 @@ mark-style Japanese Kiểu Nhật
Recent Commands Lệnh gần đây
No recent commands Không có lệnh gần đây
Type to search commands, tools, panels and effects Nhập để tìm kiếm lệnh, công cụ, bảng và hiệu ứng
Clear Recent Commands Xóa lệnh gần đây
Search commands Tìm kiếm lệnh
Search Commands… Tìm kiếm lệnh…
Search Fonts Folder Tìm kiếm thư mục phông chữ
@@ -6202,7 +6209,10 @@ liquify-list-end {0}, {1} {0} và {1}
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) đối tượng không có hiệu ứng 3D (Kéo dài & vát, Xoay tròn, Phình hoặc Xoay)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` phải là một đối tượng chỉ chứa `mode`, với giá trị shaded hoặc wireframe
@msg its 3D effect builds no solid hiệu ứng 3D của nó không tạo ra khối nào
@msg bevel must be none or one of {_1} bevel phải là none hoặc một trong {_1}
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel phải là none, một trong {_1}, hoặc custom kèm {BEVEL_PROFILE}
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom cần {BEVEL_PROFILE}, các điểm của kiểu vát
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} phải là một chuỗi
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} phải có từ 2 đến {most} điểm [x, y], mỗi tỷ lệ từ 0 đến 1, từ [0, 0] (cạnh của mặt đầu) đến [1, 1] (thành bên)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} không thể tạo khối từ hình vẽ này: các phiên bản ký hiệu, hòa trộn và nhóm cắt của nó chứa quá nhiều đối tượng
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} không thể tạo khối từ phiên bản của ký hiệu “{symbol}”: không có hình vẽ của ký hiệu
@msg {_1}: the clipping path is too complex to cut the art with {_1}: đường dẫn cắt quá phức tạp để cắt hình vẽ
@@ -8621,6 +8631,10 @@ 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"
Leaf Vine Dây leo lá
Blossom Chain Chuỗi hoa
Pennant Garland Dây cờ tam giác
Lantern String Dây đèn lồng
Orbit Lines Đường quỹ đạo
Petal Garland Vòng hoa cánh
Lattice Braid Bện lưới
Can't render this file because it is too large.
+15 -1
View File
@@ -558,6 +558,7 @@ antiAlias Sharp 锐利
{name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2}
Wheel View 色轮视图
Box View 方块视图
Show Out-of-Gamut Colors 显示超出色域的颜色
Box Channel 方块色版
Color box 颜色方块
Color Wheel Options 色轮选项
@@ -3138,6 +3139,11 @@ digits Malayalam 马拉雅拉姆数字
Edit Arrowheads 编辑箭头
Edit Arrowheads… 编辑箭头…
Reload Arrowheads 重新载入箭头
Bevels 斜角列表
Edit Bevels 编辑斜角
Edit Bevels… 编辑斜角…
{name} (document) {name} (文档)
Reload Bevels 重新载入斜角
Reset Rotate View 重置旋转视图
Rotate View to Selection 按所选对象旋转视图
Reset the rows to the artwork's colors 将各行重置为图稿的颜色
@@ -3550,6 +3556,7 @@ digits Malayalam 马拉雅拉姆数字
Recent Commands 最近使用的命令
No recent commands 没有最近使用的命令
Type to search commands, tools, panels and effects 输入以搜索命令、工具、面板和效果
Clear Recent Commands 清除最近使用的命令
Search commands 搜索命令
Search Commands… 搜索命令…
Secondary 次要
@@ -6719,7 +6726,10 @@ lighting Light 光源
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) 该对象没有 3D 效果(突出与斜角、回转、膨胀或旋转)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` 必须是只含 `mode` 的对象,值为 shaded 或 wireframe
@msg its 3D effect builds no solid 其 3D 效果未生成任何实体
@msg bevel must be none or one of {_1} bevel 必须是 none 或 {_1} 之一
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel 必须是 none、{_1} 之一,或带 {BEVEL_PROFILE} 的 custom
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom 需要 {BEVEL_PROFILE},即斜角的点
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} 必须是字符串
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} 必须是 2 到 {most} 个 [x, y] 点,每个比例在 0 到 1 之间,从 [0, 0](端面的边缘)到 [1, 1](侧壁)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}无法从此图稿生成实体:其符号实例、混合和剪切组包含的对象过多
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}无法从符号“{symbol}”的实例生成实体:该符号的图稿不可用
@msg {_1}: the clipping path is too complex to cut the art with {_1}:剪切路径过于复杂,无法用来剪切图稿
@@ -10616,6 +10626,10 @@ 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} 像素):请降低分辨率
Leaf Vine 叶藤
Blossom Chain 花链
Pennant Garland 旗帜花环
Lantern String 灯笼串
Orbit Lines 轨道线
Petal Garland 花瓣花环
Lattice Braid 格纹编织
Can't render this file because it is too large.
+15 -1
View File
@@ -575,6 +575,7 @@ font-technology Variable 可變
{name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2}
Wheel View 色輪檢視
Box View 方塊檢視
Show Out-of-Gamut Colors 顯示超出色域的顏色
Box Channel 方塊色版
Color box 顏色方塊
Color Wheel Options 色輪選項
@@ -4588,6 +4589,11 @@ digits Malayalam 馬來亞拉姆數字
Edit Arrowheads 編輯箭頭
Edit Arrowheads… 編輯箭頭…
Reload Arrowheads 重新載入箭頭
Bevels 斜角清單
Edit Bevels 編輯斜角
Edit Bevels… 編輯斜角…
{name} (document) {name} (文件)
Reload Bevels 重新載入斜角
Rotate View 旋轉檢視
Reset Rotate View 重設旋轉檢視
Rotate View to Selection 依選取範圍旋轉檢視
@@ -5033,6 +5039,7 @@ digits Malayalam 馬來亞拉姆數字
Recent Commands 最近使用的指令
No recent commands 沒有最近使用的指令
Type to search commands, tools, panels and effects 輸入以搜尋指令、工具、面板與效果
Clear Recent Commands 清除最近使用的指令
Search commands 搜尋指令
Search Commands… 搜尋指令…
Secondary 次要
@@ -6568,7 +6575,10 @@ lighting Light 光源
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) 此物件沒有 3D 效果 (突出與斜角、迴轉、膨脹或旋轉)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` 必須是只含 `mode` 的物件,值為 shaded 或 wireframe
@msg its 3D effect builds no solid 其 3D 效果沒有產生任何實體
@msg bevel must be none or one of {_1} bevel 必須是 none 或 {_1} 其中之一
@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel 必須是 none、{_1} 其中之一,或帶有 {BEVEL_PROFILE} 的 custom
@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom 需要 {BEVEL_PROFILE},也就是斜角的點
@msg {BEVEL_NAME} must be a string {BEVEL_NAME} 必須是字串
@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} 必須是 2 到 {most} 個 [x, y] 點,每個比例介於 0 和 1 之間,從 [0, 0](端面的邊緣)到 [1, 1](側壁)
@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}無法從此圖稿產生實體:其符號實例、漸變和剪裁群組包含的物件過多
@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}無法從符號「{symbol}」的實例產生實體:該符號的圖稿無法使用
@msg {_1}: the clipping path is too complex to cut the art with {_1}:剪裁路徑過於複雜,無法用來剪裁圖稿
@@ -10431,6 +10441,10 @@ 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} 個拼貼上:請縮小
Leaf Vine 葉藤
Blossom Chain 花鏈
Pennant Garland 旗幟花環
Lantern String 燈籠串
Orbit Lines 軌道線
Petal Garland 花瓣花環
Lattice Braid 格紋編織
Can't render this file because it is too large.
+7 -2
View File
@@ -794,8 +794,13 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
"help.safeMode" => crate::dialogs::safe_mode::open(app),
"help.copyTroubleshootingInfo" => crate::troubleshooting::copy(app),
"help.commandPalette" => {
app.ui.palette_open = !app.ui.palette_open;
app.ui.palette_query.clear();
crate::palette::toggle(app);
Ok(Value::Null)
}
// A pick of it in the search is recorded and counted first, and then cleared with the rest.
"help.clearRecentCommands" => {
app.ui.recent_commands.clear();
app.ui.command_uses = Default::default();
Ok(Value::Null)
}
// Closing asks Save / Don't Save / Cancel for modified documents first (`unsaved`).
+1
View File
@@ -273,6 +273,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
"view.rotateToSelection" | crate::addons::arrange::ZOOM => app.session.active().is_some_and(|d| !d.selection.objects.is_empty()),
id if id.starts_with("file.openRecent") => recent_slot(app, id).is_some(),
"file.clearRecent" => !app.ui.recent_files.is_empty(),
"help.clearRecentCommands" => !app.ui.recent_commands.is_empty() || !app.ui.command_uses.is_empty(),
id if id.starts_with("type.recentFont") => {
id["type.recentFont".len()..].parse::<usize>().is_ok_and(|n| n >= 1 && n <= app.recent_fonts().len()) && app.session.active().is_some()
}
+7 -1
View File
@@ -1013,6 +1013,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
("help.about", "About VectorCraft", "", "{}"),
("help.checkForUpdates", "Check for Updates…", "", "{}"),
("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"),
(
"help.clearRecentCommands",
"Clear Recent Commands",
"",
"{} empty the recent picks of Help › Search Commands (the list an empty search shows and the Recent Commands list), the saved list and the pick counts that rank the results; a pick of it is not kept as a recent pick or counted. Not enabled while no picks or counts are saved",
),
(
"help.discover",
"VectorCraft Help…",
@@ -1574,7 +1580,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision}",
),
(
"ui.savePdfDialog",
+504 -16
View File
@@ -319,8 +319,8 @@ pub(crate) struct Entry {
names_item: bool,
}
/// The last query, the recent picks it was ranked with, and its ranked results.
type Ranked = (String, Vec<u32>, Arc<[u32]>);
/// The last query, the recent picks and the pick counts it was ranked with, and its ranked results.
type Ranked = (String, Vec<u32>, CommandUses, Arc<[u32]>);
/// The palette's entries, the index a query is looked up in, and the last query's ranked results.
pub(crate) struct Catalog {
@@ -522,19 +522,24 @@ pub(crate) enum Picked {
Refused,
}
/// The entries the query `q` matches, best first ([`search::rank`]), with the picks that Recent
/// Commands lists for the ids `recent_ids` ([`recent`]) first among the entries that match as well.
/// The ranking of the last query is kept, so a frame that draws the same query with the same recent
/// picks does not rank again. [`show`] lists the first [`MAX_RESULTS`] and counts the rest.
fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String]) -> Vec<&'a Entry> {
/// The entries the query `q` matches, best first ([`search::rank`]), with the commands picked most
/// often (`uses`) first among the entries that match as well, and then the picks that Recent
/// Commands lists for the ids `recent_ids` ([`recent`]). The ranking of the last query is kept, so
/// a frame that draws the same query with the same counts and recent picks does not rank again.
/// [`show`] lists the first [`MAX_RESULTS`] and counts the rest.
fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String], uses: &CommandUses) -> Vec<&'a Entry> {
let q = search::normalize(q);
let picks: Vec<u32> = recent_places(&catalog.list, recent_ids).into_iter().filter_map(|i| u32::try_from(i).ok()).collect();
let kept = catalog.ranked.lock().ok().and_then(|last| last.as_ref().filter(|(k, p, _)| *k == q && *p == picks).map(|(_, _, r)| r.clone()));
let kept = catalog
.ranked
.lock()
.ok()
.and_then(|last| last.as_ref().filter(|(k, p, c, _)| *k == q && *p == picks && c == uses).map(|(_, _, _, r)| r.clone()));
let ranked = kept.unwrap_or_else(|| {
let ranked: Arc<[u32]> = search::rank(&catalog.list, &catalog.index, &q, &picks).into();
let ranked: Arc<[u32]> = search::rank(&catalog.list, &catalog.index, &q, &picks, &uses.grades(&catalog.list)).into();
// A poisoned lock only loses the kept ranking: the next frame ranks again.
if let Ok(mut last) = catalog.ranked.lock() {
*last = Some((q, picks, ranked.clone()));
*last = Some((q, picks, uses.clone(), ranked.clone()));
}
ranked
});
@@ -1065,6 +1070,132 @@ fn recent_places(entries: &[Entry], ids: &[String]) -> Vec<usize> {
.collect()
}
/// How many command ids [`CommandUses`] counts at most.
const MAX_COUNTED_COMMANDS: usize = 200;
/// The count at which [`CommandUses::count`] halves every count.
const HALVING_COUNT: u32 = 1_000;
/// How many times each command was picked in the palette: commands picked often rank first among
/// the results that match a query as well ([`matching`]). It counts at most
/// [`MAX_COUNTED_COMMANDS`] ids. When a count reaches [`HALVING_COUNT`], every count is halved, so
/// a count is at most 999.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)]
pub struct CommandUses {
/// The number of the last pick; each pick takes the next one.
pick: u32,
/// For each command id, its count and the number of its last pick.
uses: std::collections::BTreeMap<String, (u32, u32)>,
}
impl CommandUses {
/// Counts a pick of `id`. A new id when [`MAX_COUNTED_COMMANDS`] are counted first removes
/// one id from the half of the ids picked longest ago: the one with the lowest count, of those
/// the one picked longest ago. It then counts once. When the pick number is at its limit, the
/// counted ids' pick numbers are first renumbered from 1 in their order ([`renumbered`]), so
/// the pick still takes a number above all of them.
pub(crate) fn count(&mut self, id: &str) {
if self.pick == u32::MAX {
let lasts: Vec<u64> = self.uses.values().map(|&(_, last)| u64::from(last)).collect();
for ((_, last), number) in self.uses.values_mut().zip(renumbered(&lasts)) {
*last = number;
}
self.pick = self.uses.values().map(|&(_, last)| last).max().unwrap_or(0);
}
self.pick = self.pick.saturating_add(1);
let pick = self.pick;
if let Some((n, last)) = self.uses.get_mut(id) {
*n = n.saturating_add(1);
*last = pick;
} else {
if self.uses.len() >= MAX_COUNTED_COMMANDS {
let mut by_age: Vec<(u32, u32, &String)> = self.uses.iter().map(|(k, &(n, last))| (last, n, k)).collect();
by_age.sort_unstable();
let older = by_age.len().div_ceil(2);
if let Some(least) = by_age.iter().take(older).min_by_key(|&&(last, n, _)| (n, last)).map(|&(_, _, k)| k.clone()) {
self.uses.remove(&least);
}
}
self.uses.insert(id.to_string(), (1, pick));
}
if self.uses.get(id).is_some_and(|&(n, _)| n >= HALVING_COUNT) {
for (n, _) in self.uses.values_mut() {
*n /= 2;
}
self.uses.retain(|_, (n, _)| *n > 0);
}
}
/// Whether no command is counted.
pub(crate) fn is_empty(&self) -> bool {
self.uses.is_empty()
}
/// The count of `id`'s picks as a grade from 0 (never picked) to 9: the base-2 logarithm of
/// the count plus one, so 1 pick gives 1, 3 give 2, 7 give 3, and so on.
fn grade(&self, id: &str) -> u8 {
self.uses.get(id).map_or(0, |&(n, _)| u8::try_from(n.min(HALVING_COUNT - 1).saturating_add(1).ilog2()).unwrap_or(u8::MAX))
}
/// The grade ([`CommandUses::grade`]) of each of `entries`, in their order, or none when no
/// command was picked.
fn grades(&self, entries: &[Entry]) -> Vec<u8> {
if self.uses.is_empty() {
return vec![];
}
entries.iter().map(|e| self.grade(&e.id)).collect()
}
}
/// The pick numbers `lasts` renumbered from 1 in their order, in the order of `lasts`: equal
/// numbers stay equal, and the lowest becomes 1.
fn renumbered(lasts: &[u64]) -> Vec<u32> {
let mut distinct = lasts.to_vec();
distinct.sort_unstable();
distinct.dedup();
lasts.iter().map(|last| u32::try_from(distinct.partition_point(|d| d < last) + 1).unwrap_or(u32::MAX)).collect()
}
/// Serde reader for the saved pick counts ([`crate::UiState::command_uses`]): an entry that is not
/// a pair of counts is dropped, a count above 999 reads as 999, and of more than
/// [`MAX_COUNTED_COMMANDS`] ids the ones picked most recently are kept. When a kept pick number or
/// the last pick number is above the largest the counts hold, the kept pick numbers are
/// renumbered from 1 in their order ([`renumbered`]). Anything else reads as no picks, so an
/// unknown value doesn't lose the rest of the preferences.
pub fn deserialize_command_uses<'de, D: serde::Deserializer<'de>>(d: D) -> Result<CommandUses, D::Error> {
use std::cmp::Reverse;
let v = <serde_json::Value as serde::Deserialize>::deserialize(d)?;
let number = |v: Option<&serde_json::Value>| v.and_then(serde_json::Value::as_u64);
// The heap holds at most MAX_COUNTED_COMMANDS + 1 entries, the least recent pick on top (of
// equal picks, the id that sorts last), so a long saved list is not collected whole. Pick
// numbers are compared as saved, before any is renumbered.
let mut kept: std::collections::BinaryHeap<Reverse<(u64, Reverse<&String>, u32)>> = std::collections::BinaryHeap::new();
for (id, u) in v.get("uses").and_then(serde_json::Value::as_object).into_iter().flatten() {
let (Some(n), Some(last)) = (number(u.get(0)), number(u.get(1))) else { continue };
if n == 0 || !u.as_array().is_some_and(|a| a.len() == 2) {
continue;
}
let n = u32::try_from(n.min(u64::from(HALVING_COUNT - 1))).unwrap_or(HALVING_COUNT - 1);
kept.push(Reverse((last, Reverse(id), n)));
if kept.len() > MAX_COUNTED_COMMANDS {
kept.pop();
}
}
let kept: Vec<(&String, u32, u64)> = kept.into_iter().map(|Reverse((last, Reverse(id), n))| (id, n, last)).collect();
// The pick number stays above every saved last pick, so the next pick is the most recent.
let newest = kept.iter().map(|&(_, _, last)| last).max().unwrap_or(0);
let pick = number(v.get("pick")).unwrap_or(0).max(newest);
if let Ok(pick) = u32::try_from(pick) {
let uses = kept.into_iter().map(|(id, n, last)| (id.clone(), (n, u32::try_from(last).unwrap_or(pick)))).collect();
return Ok(CommandUses { pick, uses });
}
let lasts: Vec<u64> = kept.iter().map(|&(_, _, last)| last).collect();
let uses: std::collections::BTreeMap<String, (u32, u32)> =
kept.into_iter().zip(renumbered(&lasts)).map(|((id, n, _), last)| (id.clone(), (n, last))).collect();
let pick = uses.values().map(|&(_, last)| last).max().unwrap_or(0);
Ok(CommandUses { pick, uses })
}
/// The id of the Recent Commands list's popup.
fn recent_list_id() -> egui::Id {
egui::Id::unique("palette-recent-commands")
@@ -1075,6 +1206,13 @@ pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool {
egui::Popup::is_id_open(ctx, recent_list_id())
}
/// Opens the palette with an empty search when it is closed, and closes it when it is open.
pub(crate) fn toggle(app: &mut VectorcraftApp) {
app.ui.palette_open = !app.ui.palette_open;
app.ui.palette_query.clear();
app.ui.palette_toggled = true;
}
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
// The widget that had the keyboard focus when the palette opened takes it back when the palette
// closes, unless a modal window is up (a pick opened a dialog, which focuses its own first
@@ -1083,6 +1221,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let focus_id = egui::Id::unique("palette-focus-before");
let field_id = egui::Id::unique("palette-field");
let sel_id = egui::Id::unique("palette-selected");
// A toggle can close the palette and open it again before it is drawn closed, as two runs of its
// command in one step do, so the palette forgets its highlight after any toggle.
if std::mem::take(&mut app.ui.palette_toggled) {
ctx.data_mut(|d| d.remove::<Highlight>(sel_id));
}
// The Recent Commands rows drawn in the last frame, so a pick with the keyboard, which leaves the
// focus on its row, gives the focus back too.
let rows_id = egui::Id::unique("palette-recent-rows");
@@ -1129,7 +1272,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let recent = recent(&entries.list, &app.ui.recent_commands);
// An empty search lists the recent picks, most recent first, so Enter runs the last pick again.
let empty = app.ui.palette_query.trim().is_empty();
let mut matches = if empty { recent.clone() } else { matching(&entries, &q, &app.ui.recent_commands) };
let mut matches = if empty { recent.clone() } else { matching(&entries, &q, &app.ui.recent_commands, &app.ui.command_uses) };
let total = matches.len();
// The highlighted result (#1757): Up and Down move it (wrapping), Page Up and Page Down move it
// by a page, the pointer over a result takes it, and a new query starts again from the first.
@@ -1461,15 +1604,18 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
app.ui.palette_open = false;
// A pick goes first in Recent Commands before it runs, and stays there when it ran or
// opened a dialog, even when the dialog is then canceled. A refused pick puts the list
// back as it was.
let before = (id != PALETTE_TOGGLE).then(|| app.ui.recent_commands.clone());
// back as it was. The pick is counted with it, before it runs, so Clear Recent Commands
// clears its own pick and count, and a refused pick puts the counts back too.
let before = (id != PALETTE_TOGGLE).then(|| (app.ui.recent_commands.clone(), app.ui.command_uses.clone()));
if before.is_some() {
remember(&mut app.ui.recent_commands, &id, |c| entries.list.iter().any(|e| e.id == c));
app.ui.command_uses.count(&id);
}
if run_pick(app, &id) == Picked::Refused
&& let Some(before) = before
&& let Some((recent, uses)) = before
{
app.ui.recent_commands = before;
app.ui.recent_commands = recent;
app.ui.command_uses = uses;
}
} else if outside {
app.ui.palette_open = false;
@@ -1486,6 +1632,11 @@ mod tests {
use super::*;
use crate::i18n::Lang;
/// The entries `q` matches, best first, with the recent picks `recent_ids` and no pick counts.
fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String]) -> Vec<&'a Entry> {
super::matching(catalog, q, recent_ids, &CommandUses::default())
}
#[test]
fn entries_are_built_once_per_language_and_match_english_shown_text_and_ids() {
let ctx = egui::Context::default();
@@ -1823,6 +1974,10 @@ mod tests {
remember(&mut list, id, |_| true);
}
assert_eq!(list, ["j", "i", "h", "g", "f", "e", "d", "c"]);
// A palette toggle saved before its picks were left out takes none of the eight places.
let mut list: Vec<String> = [PALETTE_TOGGLE, "a", "b", "c", "d", "e", "f", "g"].map(str::to_string).into();
remember(&mut list, "h", |_| true);
assert_eq!(list, ["h", "a", "b", "c", "d", "e", "f", "g"]);
let entries = build(Lang::EN);
let many: Vec<String> = entries.iter().take(MAX_RECENT_COMMANDS + 2).map(|e| e.id.clone()).collect();
assert_eq!(recent(&entries, &many).len(), MAX_RECENT_COMMANDS);
@@ -2104,6 +2259,250 @@ mod tests {
assert_eq!(ids(&["plugin:test.UI.palette_removed".to_string(), effect.clone()]).first(), Some(&effect));
}
/// Pick counts for the ids `counts`, picked in that order.
fn counted(counts: &[(&str, u32)]) -> CommandUses {
let uses = counts.iter().zip(1..).map(|(&(id, n), last)| (id.to_string(), (n, last))).collect();
CommandUses { pick: u32::try_from(counts.len()).unwrap(), uses }
}
/// A command picked often ranks first among the results that match the query as well as it
/// does, also when it is no longer a recent pick, and the count is saved with the other
/// interface settings.
#[test]
fn a_command_picked_often_ranks_first_among_results_that_match_as_well() {
let (tool, effect) = ("tool:rectangle", "effect:convertToShape.rectangle");
let mut open = Open::new("rect", egui::vec2(1200.0, 900.0));
// The fixture has art selected, so the effect is not dimmed and its pick is counted.
open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default());
open.app.ui.palette_open = true;
open.app.ui.palette_query = "rect".into();
open.frame(vec![]);
let before = open.listed();
assert_eq!(before.first().map(String::as_str), Some(tool));
let at = before.iter().position(|id| id == effect).unwrap();
open.press(egui::Key::ArrowDown, at);
open.press(egui::Key::Enter, 1);
assert_eq!(open.app.ui.command_uses.grade(effect), 1);
assert_eq!(open.app.ui.command_uses.grade(tool), 0);
open.app.ui.recent_commands.clear();
open.app.ui.dialog = None;
open.app.ui.palette_open = true;
open.app.ui.palette_query = "rect".into();
open.frame(vec![]);
let after = open.listed();
assert_eq!(after.first().map(String::as_str), Some(effect));
assert_eq!(after.get(1).map(String::as_str), Some(tool), "only the pick moves");
let restored: crate::state::UiState = serde_json::from_str(&serde_json::to_string(&open.app.ui).unwrap()).unwrap();
assert_eq!(restored.command_uses, open.app.ui.command_uses);
}
/// The kept ranking of a query is ranked again when a pick count changes.
#[test]
fn the_kept_ranking_follows_the_pick_counts() {
let ctx = egui::Context::default();
let entries = entries(&ctx, Lang::EN);
let first = |uses: &CommandUses| super::matching(&entries, "rect", &[], uses).first().map(|e| e.id.clone());
let effect = "effect:convertToShape.rectangle";
assert_eq!(first(&CommandUses::default()).as_deref(), Some("tool:rectangle"));
let mut uses = counted(&[("tool:rectangle", 1)]);
assert_eq!(first(&uses).as_deref(), Some("tool:rectangle"));
uses.count(effect);
assert_eq!(first(&uses).as_deref(), Some("tool:rectangle"), "the same grade: the catalog order");
uses.count(effect);
uses.count(effect);
assert_eq!(first(&uses).as_deref(), Some(effect), "three picks reach grade 2");
assert_eq!(first(&CommandUses::default()).as_deref(), Some("tool:rectangle"));
}
/// A count does not lift a result above one that matches the query better: the exact id
/// `view.goto1` lists Saved View 1 before Saved View 10, however often that was picked.
#[test]
fn a_count_does_not_pass_a_better_match() {
let ctx = egui::Context::default();
let entries = entries(&ctx, Lang::EN);
let uses = counted(&[("view.goto10", 999)]);
let ids: Vec<&str> = super::matching(&entries, "view.goto1", &[], &uses).into_iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids.first(), Some(&"view.goto1"), "{ids:?}");
assert!(ids.contains(&"view.goto10"), "{ids:?}");
}
/// Counts grow in grades that double: 1 pick gives grade 1, 3 give 2, 7 give 3, and 999 give 9.
#[test]
fn pick_counts_rank_in_grades_that_double() {
let mut uses = CommandUses::default();
let grades: Vec<u8> = (0..8)
.map(|_| {
let g = uses.grade("a");
uses.count("a");
g
})
.collect();
assert_eq!(grades, [0, 1, 1, 2, 2, 2, 2, 3]);
assert_eq!(counted(&[("a", 999)]).grade("a"), 9);
assert_eq!(counted(&[("a", u32::MAX)]).grade("a"), 9);
assert!(CommandUses::default().grades(&[]).is_empty(), "no grades without counts");
}
/// A new id when 200 are counted removes, of the 100 ids picked longest ago, the id with the
/// lowest count, of those the one picked longest ago, and keeps the new one.
#[test]
fn the_201st_command_removes_the_least_used_and_keeps_itself() {
let ids: Vec<String> = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i}")).collect();
let counts: Vec<(&str, u32)> = ids.iter().enumerate().map(|(i, id)| (id.as_str(), if i == 5 || i == 9 { 1 } else { 2 })).collect();
let mut uses = counted(&counts);
uses.count("new");
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
assert!(!uses.uses.contains_key("c5") && uses.uses.contains_key("c9"));
assert_eq!(uses.uses.get("new"), Some(&(1, 201)));
uses.count("newer");
assert!(!uses.uses.contains_key("c9"), "c9 was picked before new");
assert!(uses.uses.contains_key("new") && uses.uses.contains_key("newer"));
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
}
/// When all 200 counted ids have 2 picks or more, new ids picked in turn keep their places and
/// their counts grow; the ids removed are the ones picked longest ago.
#[test]
fn new_commands_build_up_counts_when_every_counted_one_has_more_picks() {
let ids: Vec<String> = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i}")).collect();
let counts: Vec<(&str, u32)> = ids.iter().map(|id| (id.as_str(), 2)).collect();
let mut uses = counted(&counts);
for _ in 0..3 {
for id in ["a", "b", "c"] {
uses.count(id);
}
}
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
for id in ["a", "b", "c"] {
assert_eq!(uses.uses.get(id).map(|&(n, _)| n), Some(3), "{id}");
}
assert!(!uses.uses.contains_key("c0") && !uses.uses.contains_key("c2") && uses.uses.contains_key("c3"));
assert!(uses.uses.contains_key("c199"));
}
/// When a count reaches 1,000, every count is halved and ids left at 0 are removed.
#[test]
fn counts_are_halved_at_one_thousand() {
let mut uses = counted(&[("a", 999), ("b", 1), ("c", 5)]);
uses.count("a");
assert_eq!(uses.uses.get("a"), Some(&(500, 4)));
assert_eq!(uses.uses.get("c"), Some(&(2, 3)));
assert!(!uses.uses.contains_key("b"));
}
/// At the pick number's limit, the counted ids' pick numbers are renumbered from 1 in their
/// order, so a pick still takes a number above all of them and a command picked again leaves
/// the half of the ids picked longest ago.
#[test]
fn picks_keep_their_order_at_the_pick_number_limit() {
let ids: Vec<String> = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i:03}")).collect();
let mut uses = CommandUses { pick: u32::MAX, uses: ids.iter().map(|id| (id.clone(), (2, u32::MAX))).collect() };
uses.uses.insert("c000".into(), (1, u32::MAX));
uses.count("c000");
assert_eq!(uses.uses.get("c000"), Some(&(2, 2)));
assert_eq!(uses.uses.get("c001"), Some(&(2, 1)));
uses.count("new");
assert!(uses.uses.contains_key("c000"), "c000 was picked last: {:?}", uses.uses.get("c000"));
assert!(!uses.uses.contains_key("c001"));
assert_eq!(uses.uses.get("new"), Some(&(1, 3)));
// Equal pick numbers stay equal, and the order of the others is kept.
let mut uses =
CommandUses { pick: u32::MAX, uses: [("a", (1, 7)), ("b", (1, u32::MAX)), ("c", (1, 7))].map(|(k, v)| (k.to_string(), v)).into() };
uses.count("d");
assert_eq!(
uses,
CommandUses { pick: 3, uses: [("a", (1, 1)), ("b", (1, 2)), ("c", (1, 1)), ("d", (1, 3))].map(|(k, v)| (k.to_string(), v)).into() }
);
}
/// Saved counts load what is readable: a count above 999 reads as 999, entries that are not a
/// pair of counts are dropped, of more than 200 ids the most recent picks are kept, and a value
/// of the wrong kind, or none (an older settings file), reads as no picks.
#[test]
fn saved_pick_counts_load_what_is_readable() {
let load = |v: serde_json::Value| serde_json::from_value::<crate::state::UiState>(json!({ "command_uses": v })).unwrap().command_uses;
let uses = load(json!({
"pick": 3,
"uses": {"a": [5000, 2], "b": "x", "c": [1], "d": [0, 1], "e": [2, 3, 4], "f": [-1, 2], "g": [4, 1], "h": [1.5, 1], "i": [3, 9]}
}));
assert_eq!(uses, CommandUses { pick: 9, uses: [("a", (999, 2)), ("g", (4, 1)), ("i", (3, 9))].map(|(k, v)| (k.to_string(), v)).into() });
for wrong in [json!("x"), json!(null), json!([1, 2]), json!({"uses": [1]}), json!({"pick": "x", "uses": {}})] {
assert_eq!(load(wrong.clone()), CommandUses::default(), "{wrong}");
}
let older: crate::state::UiState = serde_json::from_value(json!({})).unwrap();
assert_eq!(older.command_uses, CommandUses::default());
let many: serde_json::Map<String, serde_json::Value> = (1..=250).map(|i| (format!("c{i}"), json!([1, i]))).collect();
let uses = load(json!({ "pick": 250, "uses": many }));
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
assert!(uses.uses.contains_key("c51") && !uses.uses.contains_key("c50"));
// The next pick is the most recent, also when the saved pick number is behind.
let mut uses = load(json!({ "pick": 1, "uses": {"a": [1, 9]} }));
uses.count("b");
assert_eq!(uses.uses.get("b"), Some(&(1, 10)));
// Saved pick numbers above the largest the counts hold are compared as saved, and the kept
// ones are renumbered from 1 in their order.
let big = u64::from(u32::MAX) + 1;
let mut many: serde_json::Map<String, serde_json::Value> = (0..MAX_COUNTED_COMMANDS).map(|i| (format!("c{i:03}"), json!([1, big]))).collect();
many.insert("z".into(), json!([1, big + 1]));
let uses = load(json!({ "pick": big + 1, "uses": many }));
assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS);
assert_eq!(uses.uses.get("z"), Some(&(1, 2)), "the newest pick is kept");
assert_eq!(uses.uses.get("c000"), Some(&(1, 1)));
assert_eq!(uses.pick, 2);
let uses = load(json!({ "pick": big, "uses": {"a": [1, 5], "b": [1, 3]} }));
assert_eq!(uses, CommandUses { pick: 2, uses: [("a", (1, 2)), ("b", (1, 1))].map(|(k, v)| (k.to_string(), v)).into() });
}
/// A pick is counted only when Recent Commands records it: a refused pick and a pick of the
/// palette's own toggle are not counted, and a pick that opens a dialog is.
#[test]
fn only_a_pick_recorded_in_recent_commands_is_counted() {
for (query, id) in [("find and replace", "edit.findReplace"), ("search commands", PALETTE_TOGGLE)] {
let mut open = Open::new(query, WINDOW);
let k = open.listed().iter().position(|c| c == id).unwrap_or_else(|| panic!("{query:?} finds {id}"));
open.frame(vec![]);
open.press(egui::Key::ArrowDown, k);
assert_eq!(open.highlighted(), k, "{id}");
open.press(egui::Key::Enter, 1);
assert!(open.app.ui.recent_commands.is_empty(), "{id}");
assert_eq!(open.app.ui.command_uses, CommandUses::default(), "{id}");
}
let id = "object.path.cleanUp";
let mut open = Open::new("clean up", WINDOW);
open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default());
open.app.ui.palette_open = true;
open.app.ui.palette_query = "clean up".into();
let k = open.listed().iter().position(|c| c == id).expect("the search finds Clean Up…");
open.frame(vec![]);
open.press(egui::Key::ArrowDown, k);
open.press(egui::Key::Enter, 1);
assert!(open.app.ui.dialog.is_some());
assert_eq!(open.app.ui.recent_commands, [id]);
assert_eq!(open.app.ui.command_uses.grade(id), 1);
}
/// A refused pick leaves the recent picks and the pick counts saved before it as they were.
#[test]
fn a_refused_pick_leaves_the_earlier_counts_as_they_were() {
let id = "edit.findReplace";
let mut open = Open::new("find and replace", WINDOW);
open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into()];
for _ in 0..2 {
open.app.ui.command_uses.count("paint.swap");
}
open.app.ui.command_uses.count("object.group");
let (recent, uses) = (open.app.ui.recent_commands.clone(), open.app.ui.command_uses.clone());
let k = open.listed().iter().position(|c| c == id).expect("the search finds Find and Replace…");
open.frame(vec![]);
open.press(egui::Key::ArrowDown, k);
open.press(egui::Key::Enter, 1);
assert!(open.app.ui.dialog.is_none(), "no document: the pick is refused");
assert_eq!(open.app.ui.recent_commands, recent);
assert_eq!(open.app.ui.command_uses, uses);
assert_eq!(open.app.ui.command_uses.grade(id), 0);
}
/// #6376: with nothing picked yet, Recent Commands shows a dimmed No recent commands row.
#[test]
fn recent_commands_without_picks_show_a_dimmed_row() {
@@ -2169,6 +2568,71 @@ mod tests {
assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]);
}
/// A pick of Clear Recent Commands empties the recent picks without keeping itself, so the
/// empty search then says what to type, and the saved UI state holds an empty list.
#[test]
fn clear_recent_commands_empties_the_recent_picks() {
const CLEAR: &str = "help.clearRecentCommands";
let mut open = Open::new("clear recent commands", WINDOW);
open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into()];
assert!(menus::enabled(&open.app, CLEAR));
let k = open.listed().iter().position(|id| id == CLEAR).expect("the command's result");
open.frame(vec![]);
open.press(egui::Key::ArrowDown, k);
assert_eq!(open.highlighted(), k);
open.press(egui::Key::Enter, 1);
assert!(!open.app.ui.palette_open, "the palette closes");
assert!(open.app.ui.recent_commands.is_empty(), "{:?}", open.app.ui.recent_commands);
assert!(!menus::enabled(&open.app, CLEAR), "not enabled with nothing to clear");
let saved: serde_json::Value = serde_json::to_value(&open.app.ui).unwrap();
assert_eq!(saved["recent_commands"], serde_json::json!([]));
open.app.ui.palette_query.clear();
open.app.ui.palette_open = true;
let nodes = open.frame(vec![]);
assert!(rows(&nodes).is_empty(), "{:?}", rows(&nodes));
let labels = labels(&nodes);
assert!(labels.iter().any(|l| l == tl!("Type to search commands, tools, panels and effects")), "{labels:?}");
// Run as a command, it empties the list too.
open.app.ui.recent_commands = vec!["paint.swap".into()];
open.app.run(CLEAR, serde_json::json!({})).unwrap();
assert!(open.app.ui.recent_commands.is_empty());
// A saved id the list leaves out (a plug-in that is not loaded) still counts, and is cleared.
open.app.ui.recent_commands = vec!["plugin.notLoaded.filter".into()];
assert!(menus::enabled(&open.app, CLEAR));
open.app.run(CLEAR, serde_json::json!({})).unwrap();
assert!(open.app.ui.recent_commands.is_empty());
}
/// Clear Recent Commands also empties the pick counts, and a pick of it from the search is not
/// counted afterward; with counts left and no recent picks, it is still enabled.
#[test]
fn clear_recent_commands_also_clears_the_pick_counts() {
const CLEAR: &str = "help.clearRecentCommands";
let mut open = Open::new("clear recent commands", WINDOW);
open.app.ui.recent_commands = vec!["paint.swap".into()];
for _ in 0..3 {
open.app.ui.command_uses.count("paint.swap");
}
open.app.ui.command_uses.count("object.group");
let k = open.listed().iter().position(|id| id == CLEAR).expect("the command's result");
open.frame(vec![]);
open.press(egui::Key::ArrowDown, k);
assert_eq!(open.highlighted(), k);
open.press(egui::Key::Enter, 1);
assert!(open.app.ui.recent_commands.is_empty(), "{:?}", open.app.ui.recent_commands);
assert_eq!(open.app.ui.command_uses, CommandUses::default(), "the pick of Clear is not counted either");
let saved: crate::state::UiState = serde_json::from_value(serde_json::to_value(&open.app.ui).unwrap()).unwrap();
assert_eq!(saved.command_uses, CommandUses::default());
assert!(!menus::enabled(&open.app, CLEAR));
// Counts without recent picks (Recent Commands emptied some other way) still enable it,
// and running it as a command empties them.
open.app.ui.command_uses.count("paint.swap");
assert!(menus::enabled(&open.app, CLEAR), "enabled while a count is saved");
open.app.run(CLEAR, serde_json::json!({})).unwrap();
assert_eq!(open.app.ui.command_uses, CommandUses::default());
assert_eq!(open.app.ui.command_uses.grade("paint.swap"), 0);
}
/// The palette opens again with its first row highlighted, even when it shows the same rows.
#[test]
fn the_palette_opens_again_with_its_first_row_highlighted() {
@@ -2226,6 +2690,30 @@ mod tests {
assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]);
}
/// A palette that its command closes and opens again before it is drawn closed starts at its
/// first row, so Enter on an empty search runs the last pick.
#[test]
fn the_palette_toggled_closed_and_open_between_frames_starts_at_its_first_row() {
let mut open = Open::new("", WINDOW);
open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default());
open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into()];
open.app.ui.palette_open = true;
open.frame(vec![]);
open.press(egui::Key::ArrowDown, 1);
assert_eq!(open.highlighted(), 1);
open.app.run("help.commandPalette", json!({})).unwrap();
assert!(!open.app.ui.palette_open, "the command closes the palette");
open.app.run("help.commandPalette", json!({})).unwrap();
assert!(open.app.ui.palette_open, "and opens it again");
open.frame(vec![]);
assert_eq!(open.highlighted(), 0);
let before = open.app.session.active().unwrap().history.undo.len();
open.press(egui::Key::Enter, 1);
assert!(!open.app.ui.palette_open, "the palette closes");
assert_eq!(open.app.session.active().unwrap().history.undo.len(), before + 1, "{}", open.app.ui.status);
assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]);
}
/// A pick of the palette's own toggle is not recorded, and one saved earlier is not listed, so
/// Enter on an empty search runs the last other pick.
#[test]
@@ -2904,7 +3392,7 @@ mod tests {
let listed = if self.app.ui.palette_query.trim().is_empty() {
recent(&entries.list, &self.app.ui.recent_commands)
} else {
matching(&entries, &self.app.ui.palette_query.to_lowercase(), &self.app.ui.recent_commands)
super::matching(&entries, &self.app.ui.palette_query.to_lowercase(), &self.app.ui.recent_commands, &self.app.ui.command_uses)
};
listed.iter().take(MAX_RESULTS).map(|e| e.id.clone()).collect()
}
+62 -21
View File
@@ -682,9 +682,9 @@ fn phrase(e: &Entry, query: &str, initials: bool) -> u8 {
/// What results are ordered by, compared field by field: whether a word matched only through a
/// description, whether a word matched only through a typo, how the whole query matches, the worst
/// grade a word gets, the sum of the grades, how the whole query matches when read with the words
/// of the same meaning it matched through, the result's place among the recent picks, the kind of
/// result and the label's length.
type RankKey = (bool, bool, u8, u8, u32, u8, usize, u8, usize);
/// of the same meaning it matched through, how often the result was picked (higher first), the
/// result's place among the recent picks, the kind of result and the label's length.
type RankKey = (bool, bool, u8, u8, u32, u8, std::cmp::Reverse<u8>, usize, u8, usize);
/// The results of `entries` that the lowercased `query` matches, best first, as places in
/// `entries`. A result matches when every word of the query is text in one of its names or ids
@@ -705,12 +705,14 @@ type RankKey = (bool, bool, u8, u8, u32, u8, usize, u8, usize);
/// worst grade a word gets, the sum of the grades, how the whole query matches when read with each
/// word matched through a word of the same meaning replaced by that word ("colour" as "color"; of
/// several such words the result holds, the ones that match the whole query best),
/// then by the result's place in `recent`, the places in `entries` of the recent picks, most
/// recent first (a result not in it comes after every result in it), then the kind of result
/// ([`kind`]), the label's length and the catalog order. So a recent pick ranks above the results
/// that match the query as well as it does and below every result that matches it better. An
/// empty query lists every result in catalog order.
pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32]) -> Vec<u32> {
/// then by the grade in `uses` of how often the result was picked, highest first (`uses` holds one
/// grade per entry of `entries`, in their order; a missing grade is 0), then by the result's place
/// in `recent`, the places in `entries` of the recent picks, most recent first (a result not in it
/// comes after every result in it), then the kind of result ([`kind`]), the label's length and the
/// catalog order. So a result picked often, or recently, ranks above the results that match the
/// query as well as it does and below every result that matches it better. An empty query lists
/// every result in catalog order.
pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32], uses: &[u8]) -> Vec<u32> {
let query = normalize(query);
if query.is_empty() {
return (0..entries.len()).filter_map(|i| u32::try_from(i).ok()).collect();
@@ -858,7 +860,8 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32]
let meant_tier = if synonym { best_reading(&query, &starts, &tokens, &meant, |read| phrase(e, read, false)) } else { tier };
let length = split_name(&e.shown).0.chars().count();
let picked = recent.iter().position(|&r| r == place).unwrap_or(recent.len());
ranked.push(((described, typo, tier, worst, sum, meant_tier, picked, e.kind, length), place));
let used = std::cmp::Reverse(uses.get(i).copied().unwrap_or(0));
ranked.push(((described, typo, tier, worst, sum, meant_tier, used, picked, e.kind, length), place));
}
ranked.sort_by_key(|&(key, place)| (key, place));
ranked.into_iter().map(|(_, place)| place).collect()
@@ -966,8 +969,15 @@ mod tests {
/// The ids of the results `query` lists, best first, with the results of ids `picked` as the
/// recent picks, most recent first.
fn recently(c: &Catalog, query: &str, picked: &[&str]) -> Vec<String> {
used(c, query, picked, &[])
}
/// The ids of the results `query` lists, best first, with the results of ids `picked` as the
/// recent picks, most recent first, and the results of ids `counted` given those use grades.
fn used(c: &Catalog, query: &str, picked: &[&str], counted: &[(&str, u8)]) -> Vec<String> {
let recent: Vec<u32> = picked.iter().filter_map(|id| c.list.iter().position(|e| e.id == *id)).filter_map(|i| u32::try_from(i).ok()).collect();
rank(&c.list, &c.index, query, &recent).iter().filter_map(|&i| c.list.get(i as usize)).map(|e| e.id.clone()).collect()
let uses: Vec<u8> = c.list.iter().map(|e| counted.iter().find(|(id, _)| e.id == *id).map_or(0, |&(_, g)| g)).collect();
rank(&c.list, &c.index, query, &recent, &uses).iter().filter_map(|&i| c.list.get(i as usize)).map(|e| e.id.clone()).collect()
}
/// A result named `name` (`›`-separated, its last part the label) with id `id`.
@@ -1095,13 +1105,11 @@ mod tests {
assert_eq!(ranked(&c, "same zz"), ranked(&c, "same zz"));
}
/// For each pair of adjacent grades and whole-query tiers, a recent pick ranks above a result
/// that matches the query as well as it does and comes earlier in the catalog, and below the
/// result that matches better; of two such recent picks, the more recent ranks first.
#[test]
fn a_recent_pick_ranks_first_within_its_grades() {
/// For each pair of adjacent grades and whole-query tiers: a query, a result that matches it
/// better, one that matches it as the next grade or tier, and the description of the latter.
fn adjacent_grades() -> [(&'static str, Entry, Entry, &'static str); 14] {
let description = "{} keeps the art central on the page";
for (query, better, worse, said) in [
[
("cut zz", entry("Zz Cut", "a.one"), entry("Zz Cutter", "b.two"), ""),
("scale zz", entry("Zz Scale", "a.one"), entry("Zz Scaling", "b.two"), ""),
("scale zz", entry("Zz Scaling", "a.one"), entry("Zz Scalers", "scale.two"), ""),
@@ -1120,7 +1128,15 @@ mod tests {
("remove", entry("Zz Remove", "a.one"), entry("Zz Delete", "b.two"), ""),
// Matches through a word of the same meaning: the whole label, then a word of it.
("colour", entry("Color", "a.one"), entry("Zz Color", "b.two"), ""),
] {
]
}
/// For each pair of adjacent grades and whole-query tiers, a recent pick ranks above a result
/// that matches the query as well as it does and comes earlier in the catalog, and below the
/// result that matches better; of two such recent picks, the more recent ranks first.
#[test]
fn a_recent_pick_ranks_first_within_its_grades() {
for (query, better, worse, said) in adjacent_grades() {
let (b, w) = (better.id.clone(), worse.id.clone());
// A second result that matches as the worse one does and comes before it.
let twin = entry(&worse.shown, &format!("{w}x"));
@@ -1137,6 +1153,31 @@ mod tests {
assert_eq!(recently(&c, "", &["b.two"]), ["a.one", "b.two"]);
}
/// For each pair of adjacent grades and whole-query tiers, a result picked often ranks above a
/// result that matches the query as well as it does and comes earlier in the catalog, and below
/// the result that matches better, which was never picked. Of two such results, the
/// one with the higher use grade ranks first, and a recent pick ranks first only among results
/// of the same use grade.
#[test]
fn a_command_picked_often_ranks_first_within_its_grades() {
for (query, better, worse, said) in adjacent_grades() {
let (b, w) = (better.id.clone(), worse.id.clone());
// A second result that matches as the worse one does and comes before it.
let twin = entry(&worse.shown, &format!("{w}x"));
let t = twin.id.clone();
let c = described(vec![twin, worse, better], &[said, said, ""]);
let (b, w, t) = (b.as_str(), w.as_str(), t.as_str());
assert_eq!(used(&c, query, &[], &[(w, 1)]), [b, w, t], "{query}: one pick ranks above none");
assert_eq!(used(&c, query, &[], &[(w, 9), (t, 3)]), [b, w, t], "{query}: the higher grade first");
assert_eq!(used(&c, query, &[], &[(w, 1), (t, 3)]), [b, t, w], "{query}: the higher grade first");
assert_eq!(used(&c, query, &[w], &[(t, 1)]), [b, t, w], "{query}: a recent pick within its use grade");
assert_eq!(used(&c, query, &[w], &[(w, 1), (t, 1)]), [b, w, t], "{query}: a recent pick within its use grade");
}
// An empty query lists every result in catalog order.
let c = synthetic(vec![entry("Zz One", "a.one"), entry("Zz Two", "b.two")]);
assert_eq!(used(&c, "", &[], &[("b.two", 9)]), ["a.one", "b.two"]);
}
/// A query that is a menu's title ranks a result whose label holds it as a word above the items
/// of that menu, which match only by their menu path. A query that names the menu with `›`
/// still starts the item's name.
@@ -1147,7 +1188,7 @@ mod tests {
assert_eq!(ranked(&c, "object › pa"), ["a.one"]);
let en = catalog(Lang::EN, false);
for q in ["object", "effect", "select", "view", "type", "edit"] {
let first = rank(&en.list, &en.index, q, &[]).first().and_then(|&i| en.list.get(i as usize)).map(|e| e.shown.to_lowercase());
let first = rank(&en.list, &en.index, q, &[], &[]).first().and_then(|&i| en.list.get(i as usize)).map(|e| e.shown.to_lowercase());
let label = first.as_deref().map(|n| split_name(n).0.to_string()).unwrap_or_default();
assert!(words(&label).any(|w| w.starts_with(q)), "{q}: {first:?}");
}
@@ -1362,7 +1403,7 @@ mod tests {
] {
assert!(substring_rule(&c, typo).is_empty(), "{typo} matched nothing before");
let top = |q: &str| ranked(&c, q).into_iter().take(4).collect::<Vec<_>>();
let spelled_right: Vec<String> = rank(&c.list, &plain, word, &[]).iter().take(4).map(id).collect();
let spelled_right: Vec<String> = rank(&c.list, &plain, word, &[], &[]).iter().take(4).map(id).collect();
assert_eq!(top(typo), spelled_right, "{typo}");
assert!(place(&c, typo, tool).is_some_and(|p| p < 4), "{typo}: {:?}", ranked(&c, typo));
}
@@ -1923,7 +1964,7 @@ mod tests {
let started = std::time::Instant::now();
let runs = 100;
for _ in 0..runs {
std::hint::black_box(rank(&c.list, &c.index, q, &[]));
std::hint::black_box(rank(&c.list, &c.index, q, &[], &[]));
}
println!("{:>12}: {:?} per query", q.get(..12).unwrap_or(q), started.elapsed() / runs);
}
+80 -7
View File
@@ -96,8 +96,9 @@ pub(crate) fn field_width(ui: &Ui) -> f32 {
}
/// The Corner Radius field of a live rectangle's properties: [`corner_radius`], which a new value
/// sets on those corners. The link behind it is the `singleCornerRadius` preference: off, a field
/// for each of the four corners follows, each setting its own corner.
/// sets on those corners. The link behind it is the `singleCornerRadius` preference: on, a Corner
/// menu follows that sets the kind of all four corners; off, a row for each of the four corners
/// follows, each with a radius field and a Corner menu that set its own corner.
pub(crate) fn corner_radius_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, id: &str) {
let fw = field_width(ui);
let single = app.session.prefs.single_corner_radius;
@@ -111,27 +112,97 @@ pub(crate) fn corner_radius_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node,
transform::set_pref(app, "singleCornerRadius", !single);
}
});
if !single {
if single {
corner_kind_row(app, ui, n, id, fw);
} else {
corner_fields(app, ui, n, id, fw);
}
}
/// The Corner menu of a live rectangle whose corners share one radius field: the kind of all four
/// corners, also while some of them are Direct-Selected, blank when they differ. A pick sets it on
/// every corner of each selected live rectangle ([`set_rectangle_kinds`]).
fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, id: &str, width: f32) {
let Some(lc) = LiveCorners::of(n) else { return };
let current = lc.style(&lc.all()).1;
ui.horizontal(|ui| {
dim_label(ui, tl!("Corner:"));
if let Some(kind) = corner_kind_menu(ui, (id, "kind"), tl!("Corner:"), current, width) {
set_rectangle_kinds(app, kind, None);
}
});
}
/// Set `kind` on corner `corner` (every corner for None) of each selected live rectangle
/// ([`set_rectangle_corners`]).
fn set_rectangle_kinds(app: &mut VectorcraftApp, kind: CornerKind, corner: Option<usize>) {
set_rectangle_corners(app, json!({"kind": kind}), corner);
}
/// Run `object.setLiveShape` with `p` (a `kind` or `radius`) on corner `corner` (every corner for
/// None) of each selected live rectangle, leaving other selected objects as they are: one undo
/// step, or none when nothing changes.
fn set_rectangle_corners(app: &mut VectorcraftApp, mut p: Value, corner: Option<usize>) {
p["corners"] = corner.map_or(json!([0, 1, 2, 3]), |k| json!([k]));
// The edit the tool computes on another thread comes first: the rectangles are the ones
// selected after it.
match app.session.finish_tool_edit() {
Ok(reqs) => crate::canvas::apply_requests(app, Ok(reqs)),
Err(e) => {
app.status(e.to_string());
return;
}
}
if app.session.active().is_none() {
return;
}
// The live rectangles of the selection when it runs, so an action that records it acts on the
// rectangles selected when it plays.
p["rectanglesOnly"] = json!(true);
if let Err(e) = app.run("object.setLiveShape", p) {
app.status(e);
}
}
/// A menu of the corner kinds, `width` wide, showing `current` (blank for None) and named `name`
/// for screen readers. Returns the kind picked.
fn corner_kind_menu(ui: &mut Ui, id: impl std::hash::Hash, name: &str, current: Option<CornerKind>, width: f32) -> Option<CornerKind> {
let names: Vec<&str> = CornerKind::ALL.iter().map(|k| crate::dialogs::corners::kind_label(*k)).collect();
let shown = current.map_or("", crate::dialogs::corners::kind_label);
crate::widgets::dropdown_names_named(ui, id, Some(name), shown, &names, width).and_then(|i| CornerKind::ALL.get(i).copied())
}
/// The corners of a live rectangle in the order their fields show, with their labels.
fn rectangle_corners() -> [(usize, &'static str); 4] {
[(0, tl!("Top Left:")), (1, tl!("Top Right:")), (2, tl!("Bottom Right:")), (3, tl!("Bottom Left:"))]
}
/// One Corner Radius field per corner of a live rectangle, each on its own row with its label,
/// the fields in line.
/// One Corner Radius field and one Corner menu per corner of a live rectangle, each pair on its own
/// row with the corner's label, the fields and menus in line; in a panel too narrow for that, each
/// menu goes on the row under its field. A value typed or a kind picked is set on that corner
/// alone, of each selected live rectangle ([`set_rectangle_corners`]).
fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, id: &str, width: f32) {
let Some(lc) = LiveCorners::of(n) else { return };
let unit = app.session.general_unit();
egui::Grid::new((id, "corners")).num_columns(2).spacing(vec2(6.0, 4.0)).show(ui, |ui| {
let widest = |names: &mut dyn Iterator<Item = &str>| names.map(|t| crate::widgets::dim_label_width(ui, t)).fold(0.0, f32::max);
let labels = widest(&mut rectangle_corners().into_iter().map(|(_, label)| label));
// The longest kind name, with the room the menu's button gives around it and its arrow.
let menu_width = width.max(widest(&mut CornerKind::ALL.into_iter().map(crate::dialogs::corners::kind_label)) + 26.0);
// The two gaps between the grid's three columns are 6 points each.
let in_line = labels + width + menu_width + 12.0 <= ui.available_width();
egui::Grid::new((id, "corners")).num_columns(if in_line { 3 } else { 2 }).spacing(vec2(6.0, 4.0)).show(ui, |ui| {
for (k, label) in rectangle_corners() {
dim_label(ui, label);
if let Some(v) = crate::widgets::num_field_named(ui, (id, "corner", k), Some(label), Some(lc.radius(k)), unit, width) {
// A negative radius typed in rounds nothing: the command takes 0 or more.
app.run("object.setLiveShape", json!({"radius": v.max(0.0), "corners": [k]})).ok();
set_rectangle_corners(app, json!({"radius": v.max(0.0)}), Some(k));
}
if !in_line {
ui.end_row();
ui.label("");
}
if let Some(kind) = corner_kind_menu(ui, (id, "kind", k), label, Some(lc.kind(k)), menu_width) {
set_rectangle_kinds(app, kind, Some(k));
}
ui.end_row();
}
@@ -819,6 +890,8 @@ mod tests_color_wheel;
#[cfg(test)]
mod tests_color_wheel_box;
#[cfg(test)]
mod tests_color_wheel_gamut;
#[cfg(test)]
mod tests_color_wheel_harmony;
#[cfg(test)]
mod tests_color_wheel_vision;
+79 -3
View File
@@ -199,13 +199,21 @@ fn multi(app: &VectorcraftApp, ctx: &egui::Context, list: &[(String, String)], c
set_pstate(ctx, "br-selected", (None::<Vec<String>>, None::<ClickKey>));
return None;
}
let (names, _): (Option<Vec<String>>, Option<ClickKey>) = pstate(ctx, "br-selected");
let (names, key): (Option<Vec<String>>, Option<ClickKey>) = pstate(ctx, "br-selected");
let names = names?;
if names.is_empty() {
return Some(names);
}
let orig_len = names.len();
let kept: Vec<String> = names.into_iter().filter(|n| list.iter().any(|b| &b.0 == n)).collect();
(!kept.is_empty()).then_some(kept)
if kept.is_empty() {
set_pstate(ctx, "br-selected", (None::<Vec<String>>, key));
return None;
}
if kept.len() != orig_len {
set_pstate(ctx, "br-selected", (Some(kept.clone()), key));
}
Some(kept)
}
/// The brushes Delete Brush and Duplicate Brush act on: the multi-selection, else the selected
@@ -300,6 +308,53 @@ fn replace_drop(ui: &Ui, resp: &egui::Response, name: &str, ty: &str, replaced:
}
}
/// A brush item's right-click context menu.
fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str) {
let (current_list, current) = brushes(app);
let multi_names = multi(app, ui.ctx(), &current_list, current.as_deref());
let is_multi = multi_names.as_ref().is_some_and(|m| m.len() > 1 && m.iter().any(|b| b == name));
let targets = if is_multi { multi_names.unwrap_or_default() } else { vec![name.to_string()] };
let all_exist = app.session.active().is_some_and(|st| {
let lib = vectorcraft_brush::library(&st.doc);
targets.iter().all(|n| lib.iter().any(|b| &b.name == n))
});
let can_delete = all_exist && targets.len() < current_list.len() && current_list.len() > 1;
let can_duplicate = all_exist;
if is_multi {
if menu_item(ui, tl!("Duplicate Brushes"), can_duplicate, false) {
if let Err(e) = app.run("brush.duplicate", json!({ "names": targets })) {
app.status(e);
}
ui.close();
}
if menu_item(ui, tl!("Delete Brushes"), can_delete, false) {
delete(app, &targets, true);
ui.close();
}
} else {
let can_options = all_exist;
if menu_item(ui, tl!("Brush Options…"), can_options, false) {
if let Err(e) = app.run("ui.brushOptions", json!({ "name": name })) {
app.status(e);
}
ui.close();
}
if menu_item(ui, tl!("Duplicate Brush"), can_duplicate, false) {
if let Err(e) = app.run("brush.duplicate", json!({ "name": name })) {
app.status(e);
}
ui.close();
}
if menu_item(ui, tl!("Delete Brush"), can_delete, false) {
delete(app, &[name.to_string()], true);
ui.close();
}
}
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
let (list, current) = brushes(app);
@@ -316,6 +371,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let mut options: Option<String> = None;
let mut moved: Option<Value> = None;
let mut replaced: Option<(String, Vec<u64>)> = None;
let mut secondary_selected: Option<String> = None;
let list_rect = widgets::list_box(ui, |ui| {
ui.set_min_height(110.0);
ui.set_width(ui.available_width());
@@ -366,8 +422,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
resp.on_hover_text(name)
};
// A click applies or selects the brush; the second click of a double-click opens its
// options.
// options; a right-click selects if unselected and displays its item context menu.
let mut pick = |resp: egui::Response, name: &String| {
if resp.secondary_clicked() {
let is_selected = match &multi {
Some(m) => m.iter().any(|b| b == name),
None => sel_brush.as_deref() == Some(name) || (sel_brush.is_none() && current.as_deref() == Some(name)),
};
if !is_selected {
set_pstate(&resp.ctx, "br-anchor", name.clone());
if let Err(e) = app.run("brush.setCurrent", json!({ "name": name })) {
app.status(e);
}
let now = brushes(app).1;
let key = click_key(app, now.as_deref());
set_pstate(&resp.ctx, "br-selected", (Some(vec![name.clone()]), key));
secondary_selected = Some(name.clone());
}
}
resp.context_menu(|ui| item_context_menu(app, ui, name));
if resp.double_clicked() {
options = Some(name.clone());
} else if resp.clicked() {
@@ -417,6 +490,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
{
app.status(e);
}
if let Some(name) = secondary_selected {
multi = Some(vec![name]);
}
let highlighted = sel_brush.clone().or(current.clone());
match clicked {
// Shift and Cmd/Ctrl only select, as in the Swatches panel: they start from the
+132
View File
@@ -888,3 +888,135 @@ fn rows_of_two_brushes_with_one_name_show_the_first() {
assert_eq!(shown.ty, "art");
assert_eq!(shown.def, got, "the first of two rows of one name is the one shown");
}
/// Right-clicking a brush in the Brushes panel selects it (if unselected), displays
/// the context menu ("Brush Options…", "Duplicate Brush", "Delete Brush"), and clicking
/// an item dispatches the corresponding command. Multi-selection right-click preserves
/// selection and offers "Duplicate Brushes" / "Delete Brushes". "Delete Brush" is disabled
/// when it is the last brush in the library.
#[test]
fn right_click_context_menu_in_brushes_panel() {
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
app.run("brush.apply", json!({"name": "Tapered Stroke"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 500.0)).with_accessibility_check(false).build_ui_state(
|ui, app: &mut VectorcraftApp| {
show(app, ui);
},
app,
);
h.run_steps(2);
let right_click = |h: &mut egui_kittest::Harness<'static, VectorcraftApp>, label: &str| {
let node = h.get_by_label(label);
let pos = node.rect().center();
h.event(egui::Event::PointerMoved(pos));
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
};
// 1. Initial state: artwork uses Tapered Stroke; Charcoal is not current
assert_eq!(selected_brush(h.state()).as_deref(), Some("Tapered Stroke"));
assert_ne!(brushes(h.state_mut()).1.as_deref(), Some("Charcoal"));
// Right-click unselected "Charcoal"
right_click(&mut h, "Charcoal");
// Right-clicking selects Charcoal in panel without applying it to the selected artwork
assert_eq!(brushes(h.state_mut()).1.as_deref(), Some("Charcoal"));
assert_eq!(selected_brush(h.state()).as_deref(), Some("Tapered Stroke"), "right-click must not apply brush to artwork");
let (multi_sel, _): (Option<Vec<String>>, Option<ClickKey>) = pstate(&h.ctx, "br-selected");
assert_eq!(multi_sel, Some(vec!["Charcoal".to_string()]), "right-clicked brush is recorded as panel selection");
let (b_list, b_cur) = brushes(h.state_mut());
assert_eq!(targets(h.state(), &h.ctx, &b_list, b_cur.as_deref()), vec!["Charcoal".to_string()]);
// Context menu displays Brush Options…, Duplicate Brush, Delete Brush
let opt = h.get_by_label(" Brush Options…");
let dup = h.get_by_label(" Duplicate Brush");
let del = h.get_by_label(" Delete Brush");
assert!(!opt.accesskit_node().is_disabled());
assert!(!dup.accesskit_node().is_disabled());
assert!(!del.accesskit_node().is_disabled());
// 2. Click "Duplicate Brush" dispatches brush.duplicate and adds a copy
dup.click();
h.run_steps(2);
let all_names = names(h.state_mut());
assert!(all_names.contains(&"Charcoal copy".to_string()));
// 3. Right-click "Charcoal copy" and click "Delete Brush"
right_click(&mut h, "Charcoal copy");
let undo_before = undo_count(h.state());
h.get_by_label(" Delete Brush").click();
h.run_steps(2);
assert!(!names(h.state_mut()).contains(&"Charcoal copy".to_string()));
assert_eq!(undo_count(h.state()), undo_before + 1);
// Undo restores the deleted copy
h.state_mut().run("edit.undo", json!({})).unwrap();
assert!(names(h.state_mut()).contains(&"Charcoal copy".to_string()));
// 4. Click "Brush Options…" opens the Brush Options dialog
right_click(&mut h, "Charcoal");
h.get_by_label(" Brush Options…").click();
h.run_steps(2);
assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::brush_options::KIND));
assert_eq!(h.state().ui.dialog.as_ref().unwrap().str("name"), "Charcoal");
crate::dialogs::cancel(h.state_mut());
assert!(h.state().ui.dialog.is_none());
// 5. Multi-selection: right-clicking within multi-selection preserves it and offers
// "Duplicate Brushes" and "Delete Brushes"
let cur = brushes(h.state_mut()).1;
let key = click_key(h.state(), cur.as_deref());
set_pstate(&h.ctx, "br-selected", (Some(vec!["Charcoal".to_string(), "Tapered Stroke".to_string()]), key));
h.run_steps(1);
right_click(&mut h, "Tapered Stroke");
let (multi_sel, _): (Option<Vec<String>>, Option<ClickKey>) = pstate(&h.ctx, "br-selected");
assert_eq!(multi_sel, Some(vec!["Charcoal".to_string(), "Tapered Stroke".to_string()]));
let dup_multi = h.get_by_label(" Duplicate Brushes");
let del_multi = h.get_by_label(" Delete Brushes");
assert!(!dup_multi.accesskit_node().is_disabled());
assert!(!del_multi.accesskit_node().is_disabled());
// Click Duplicate Brushes
dup_multi.click();
h.run_steps(2);
let all_names = names(h.state_mut());
assert!(all_names.contains(&"Charcoal copy 2".to_string()));
assert!(all_names.contains(&"Tapered Stroke copy".to_string()));
// 6. Delete a brush in use by artwork prompts with the brushDelete confirmation dialog
h.state_mut().run("brush.apply", json!({ "name": "Tapered Stroke" })).unwrap();
assert_eq!(selected_brush(h.state()).as_deref(), Some("Tapered Stroke"));
right_click(&mut h, "Tapered Stroke");
h.get_by_label(" Delete Brush").click();
h.run_steps(2);
assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::brush_delete::KIND));
crate::dialogs::cancel(h.state_mut());
assert!(names(h.state_mut()).contains(&"Tapered Stroke".to_string()));
// 7. Delete Brush is disabled when it is the last brush in the library
let current_brushes = names(h.state_mut());
let to_delete: Vec<String> = current_brushes.into_iter().filter(|n| n != "Charcoal").collect();
h.state_mut().run("brush.delete", json!({ "names": to_delete })).unwrap();
assert_eq!(names(h.state_mut()), vec!["Charcoal".to_string()]);
h.run_steps(2);
right_click(&mut h, "Charcoal");
let del_last = h.get_by_label(" Delete Brush");
assert!(del_last.accesskit_node().is_disabled(), "last remaining brush cannot be deleted");
}
+101 -18
View File
@@ -12,6 +12,11 @@
//! Brightness, Red, Green or Blue). The field shows the other two components on the Color
//! Picker's axes.
//!
//! Show Out-of-Gamut Colors grays out the cells of the wheel's square and the box's field whose
//! colors the CMYK space cannot print, by the out-of-gamut warning's test ([`Cms::out_of_gamut`]),
//! on a [`GAMUT_CELLS`] by [`GAMUT_CELLS`] grid kept until the channel, its value, the color
//! settings or the loaded profiles change.
//!
//! Show Harmony puts a marker on the ring for each other color of the harmony rule picked under
//! Harmony Rule (the Color Guide's rules whose colors each have a hue of their own), filled with
//! that color. The markers follow the current color, and a click on one applies its color as a
@@ -31,13 +36,13 @@
//! (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>). The choice is kept with the
//! preferences too.
//!
//! The view, the channel, the slider rows, Show Harmony, Harmony Rule and Show Color Vision
//! Preview are kept with the preferences (`ui.colorWheel`).
//! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule
//! and Show Color Vision Preview are kept with the preferences (`ui.colorWheel`).
use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::cms::{self, Cms, ProofSetup, ProofTarget};
use vectorcraft_color::cms::{self, Cms, ColorSettings, ProofSetup, ProofTarget};
use vectorcraft_color::harmony::Harmony;
use vectorcraft_color::oklab::{self, CHROMA_FULL};
use vectorcraft_color::{Color, Paint, hsb_to_rgb, hsl_to_rgb, rgb_to_hsb, rgb_to_hsl};
@@ -94,6 +99,9 @@ pub struct Settings {
pub channel: Channel,
#[serde(deserialize_with = "deserialize_sliders")]
pub sliders: Sliders,
/// Show Out-of-Gamut Colors: gray out the colors the CMYK space cannot print.
#[serde(deserialize_with = "deserialize_flag")]
pub gamut: bool,
/// Show Harmony: markers on the ring for the other colors of `harmony_rule`.
#[serde(deserialize_with = "deserialize_flag")]
pub harmony: bool,
@@ -146,6 +154,7 @@ impl Default for Settings {
view: View::default(),
channel: Channel::default(),
sliders: Sliders::default(),
gamut: false,
harmony: false,
harmony_rule: Harmony::Complementary,
vision: false,
@@ -199,11 +208,11 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Se
Ok(serde_json::from_value(v).unwrap_or_default())
}
/// `ui.colorWheel {view?, channel?, sliders?, harmony?, harmonyRule?, vision?}`: show the wheel or
/// the box, pick the box's channel, show OKLCH Sliders, HSL Sliders or neither, show the colors of
/// a harmony rule on the wheel, and show or hide the color vision row. Keys left out or null keep
/// their values; params that are not an object, another key or a value off the list are an error
/// and change nothing.
/// `ui.colorWheel {view?, channel?, sliders?, gamut?, harmony?, harmonyRule?, vision?}`: show the
/// wheel or the box, pick the box's channel, show OKLCH Sliders, HSL Sliders or neither, show or
/// hide the out-of-gamut shading, show the colors of a harmony rule on the wheel, and show or hide
/// the color vision row. Keys left out or null keep their values; params that are not an object,
/// another key or a value off the list are an error and change nothing.
/// `sliders: "oklch"` is an error while the active document's RGB space (its assigned profile,
/// else the working RGB space) is not sRGB. → the settings.
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
@@ -214,7 +223,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri
/// Set the keys of `ui.colorWheel` params `p` in `settings`, with the color settings `cms`; on an
/// error `settings` stay as they were.
pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), String> {
const KEYS: [&str; 6] = ["view", "channel", "sliders", "harmony", "harmonyRule", "vision"];
const KEYS: [&str; 7] = ["view", "channel", "sliders", "gamut", "harmony", "harmonyRule", "vision"];
match p {
Value::Null => {}
Value::Object(o) => {
@@ -243,6 +252,11 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S
set.sliders = sliders;
}
}
let key = "gamut";
match p.get(key) {
None | Some(Value::Null) => {}
Some(v) => set.gamut = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?,
}
let key = "harmony";
match p.get(key) {
None | Some(Value::Null) => {}
@@ -265,9 +279,9 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S
Ok(())
}
/// The panel menu: Wheel View and Box View, and Box Channel while the box shows; HSL Sliders and
/// OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; and Show Color Vision
/// Preview.
/// The panel menu: Wheel View and Box View, and Box Channel while the box shows; Show Out-of-Gamut
/// Colors; HSL Sliders and OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; and
/// Show Color Vision Preview.
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let set = app.ui.color_wheel.clone();
for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] {
@@ -285,6 +299,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
});
});
ui.separator();
if menu_item(ui, tl!("Show Out-of-Gamut Colors"), true, set.gamut) {
command(app, &json!({ "gamut": !set.gamut })).ok();
}
let on = set.sliders == Sliders::Hsl;
if menu_item(ui, tl!("HSL Sliders"), true, on) {
let sliders = if on { Sliders::None } else { Sliders::Hsl };
@@ -318,6 +335,64 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// The cells across and down of the grid the out-of-gamut shading tests.
pub(crate) const GAMUT_CELLS: usize = 16;
/// The cells of a field whose colors are out of the CMYK gamut, a row per [`GAMUT_CELLS`] from the
/// top: bit `i` of a row is its cell `i` from the left.
pub(crate) type GamutGrid = [u16; GAMUT_CELLS];
/// The out-of-gamut cells of the box of channel `ch` at strip value `z` through `cms`, each tested
/// at its center by the out-of-gamut warning's test ([`Cms::out_of_gamut`]) on the working-RGB
/// color of a pick there, before any conversion to CMYK or Lab in [`stored`]. The wheel's square is
/// the box of [`Channel::Hue`] at the ring's hue.
pub(crate) fn gamut_grid(cms: &Cms, ch: Channel, z: f32) -> GamutGrid {
let n = GAMUT_CELLS as f32;
let mut grid = [0; GAMUT_CELLS];
for (row, bits) in grid.iter_mut().enumerate() {
for col in 0..GAMUT_CELLS {
let (x, y) = ((col as f32 + 0.5) / n, (row as f32 + 0.5) / n);
// A gray has no hue, and the hue a gray keeps does not change its color.
let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(box_pick(ch, z, x, y, [0.0; 3])));
if cms.out_of_gamut(&Color::rgb(r, g, b)) {
*bits |= 1 << col;
}
}
}
grid
}
/// What the out-of-gamut grid depends on: the channel, its value's bits, the color settings and
/// [`cms::profiles_generation`], which changes when a profile is loaded again under the same name.
pub(crate) type GamutKey = (Channel, u32, ColorSettings, u64);
/// The grid for `key` from `slot`, computed with `compute` and kept in `slot` when `slot` holds
/// another key's.
pub(crate) fn cached_grid(slot: &mut Option<(GamutKey, GamutGrid)>, key: GamutKey, compute: impl FnOnce() -> GamutGrid) -> GamutGrid {
match slot {
Some((k, grid)) if *k == key => *grid,
_ => {
let grid = compute();
*slot = Some((key, grid));
grid
}
}
}
/// Panel state: the out-of-gamut grid drawn last and its [`GamutKey`].
pub(crate) const GAMUT: &str = "color-wheel-gamut";
/// The out-of-gamut grid of channel `ch` at value `z` through `cms`, kept in the panel state so a
/// frame with the same channel, value, color settings and loaded profiles does not test the colors
/// again.
fn gamut_shade(ui: &Ui, cms: &Cms, ch: Channel, z: f32) -> GamutGrid {
let mut slot = pstate::<Option<(GamutKey, GamutGrid)>>(ui.ctx(), GAMUT);
let key = (ch, z.to_bits(), cms.settings().clone(), cms::profiles_generation());
let grid = cached_grid(&mut slot, key, || gamut_grid(cms, ch, z));
set_pstate(ui.ctx(), GAMUT, slot);
grid
}
/// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness,
/// or red, green and blue.
fn box_values(ch: Channel, hsb: [f32; 3]) -> [f32; 3] {
@@ -362,16 +437,19 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) {
}
/// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with
/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks,
/// and its phase.
fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> {
/// markers when `marked` and the field's out-of-gamut cells grayed out when `gamut`. Returns the
/// HSB a click, a drag, a key or a screen reader's action picks, and its phase.
fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32, gamut: Option<&Cms>) -> Option<([f32; 3], Live)> {
let (z, x, y) = box_pos(ch, hsb);
let mut pick = None;
let grid = gamut.map(|cms| gamut_shade(ui, cms, ch, z));
let shade = grid.as_ref().map_or(&[][..], |g| &g[..]);
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = STRIP_GAP;
let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size);
let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb));
if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) {
let labels = (tl!("Color box"), ch.field_axes());
if let (Some((x, y)), phase) = widgets::color_field_shaded(ui, "color-wheel-box", labels, field, (x, y), marked, (&at, shade)) {
pick = Some((box_pick(ch, z, x, y, hsb), phase));
}
// The hue strip shows the whole spectrum; the others change only their own component.
@@ -789,6 +867,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
(c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)),
};
let marked = color.is_some();
let gamut = app.ui.color_wheel.gamut.then_some(&*cms);
let mut pick: Option<([f32; 3], Live)> = None;
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
@@ -797,7 +876,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
});
let size = ui.available_width().min(MAX_WHEEL);
if app.ui.color_wheel.view == View::Box {
pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size);
pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size, gamut);
return;
}
let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked);
@@ -807,7 +886,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
[FieldAxis { name: tl!("Saturation"), units: 100.0, suffix: "%" }, FieldAxis { name: tl!("Brightness"), units: 100.0, suffix: "%" }];
let at = |x: f32, y: f32| widgets::hsb32([hsb[0], x, 1.0 - y]);
let name = tl!("Saturation and brightness");
let (field, field_phase) = widgets::color_field(&mut field_ui, "field", (name, axes), square.size(), (hsb[1], 1.0 - hsb[2]), marked, &at);
// The square is the hue box at the ring's hue, so it shares the box's grid.
let grid = gamut.map(|cms| gamut_shade(ui, cms, Channel::Hue, box_pos(Channel::Hue, hsb).0));
let shade = grid.as_ref().map_or(&[][..], |g| &g[..]);
let pos = (hsb[1], 1.0 - hsb[2]);
let (field, field_phase) = widgets::color_field_shaded(&mut field_ui, "field", (name, axes), square.size(), pos, marked, (&at, shade));
// Show Harmony: the rule's other colors for the current one, which follow it. While a press
// is held on a marker, the ring's drag under it picks nothing.
let set = &app.ui.color_wheel;
+262 -8
View File
@@ -26,7 +26,10 @@ use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::style_libs::STYLE_LIBRARIES;
use vectorcraft_doc::text::{CharStyle, TextObject};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, GraphicStyle, Node, NodeId, NodeKind, PatternDef, StrokeLayer, StyleLibrary};
use vectorcraft_doc::{
Appearance, AppearanceItem, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeId, NodeKind, PatternDef, StrokeLayer,
StyleLibrary,
};
use vectorcraft_engine::cmd::stylelib;
use vectorcraft_engine::cmd::swatchlib::LibraryInfo;
use vectorcraft_geom::{Affine, Point, shapes};
@@ -486,21 +489,84 @@ fn zone_input(ui: &Ui, zone: &Response, d: &Document, ev: &mut Events) {
}
}
/// An item's right-click context menu in the Graphic Styles panel.
fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str, sel: &[String]) {
let is_default = name == DEFAULT_GRAPHIC_STYLE;
let is_multi = sel.len() > 1 && sel.contains(&name.to_string());
let targets: Vec<String> = if is_multi {
let doc = app.session.active().map(|st| st.doc.clone());
if let Some(d) = &doc { d.graphic_styles.iter().filter(|g| sel.contains(&g.name)).map(|g| g.name.clone()).collect() } else { sel.to_vec() }
} else {
vec![name.to_string()]
};
let doomed: Vec<String> = targets.iter().filter(|s| *s != DEFAULT_GRAPHIC_STYLE).cloned().collect();
let can_options = !is_default && !is_multi;
if menu_item(ui, tl!("Graphic Style Options…"), can_options, false) {
if let Err(e) = app.run("ui.graphicStyleOptions", json!({ "name": name })) {
app.status(e);
}
ui.close();
}
let duplicate_label = if is_multi { tl!("Duplicate Graphic Styles") } else { tl!("Duplicate Graphic Style") };
if menu_item(ui, duplicate_label, true, false) {
duplicate(app, ui.ctx(), &targets);
ui.close();
}
let delete_label = if is_multi { tl!("Delete Graphic Styles") } else { tl!("Delete Graphic Style") };
let can_delete = !is_default && !doomed.is_empty();
if menu_item(ui, delete_label, can_delete, false) {
let res = if doomed.len() == 1 {
app.run("graphicStyle.delete", json!({ "name": doomed[0] }))
} else {
app.run("graphicStyle.delete", json!({ "names": doomed }))
};
if res.is_ok() {
set_pstate(ui.ctx(), "gs-sel", Vec::<String>::new());
}
ui.close();
}
ui.separator();
let has_art_sel = selection_len(app) > 0;
if menu_item(ui, tl!("Redefine Graphic Style"), has_art_sel, false) {
if let Err(e) = app.run("graphicStyle.redefine", json!({ "name": name })) {
app.status(e);
}
ui.close();
}
let is_linked = app.session.selection_graphic_style().is_some_and(|(g, linked)| linked && g.name == name);
if menu_item(ui, tl!("Break Link to Graphic Style"), is_linked, false) {
if let Err(e) = app.run("graphicStyle.breakLink", json!({})) {
app.status(e);
}
ui.close();
}
}
/// The thumbnail grid (Thumbnail View and the Control bar's picker), `sel` outlined.
fn tiles(app: &VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &[String], ev: &mut Events) {
fn tiles(app: &mut VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &mut Vec<String>, ev: &mut Events, in_panel: bool) {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(3.0, 3.0);
for (i, g) in s.d.graphic_styles.iter().enumerate() {
let (r, resp) = ui.allocate_exact_size(vec2(TILE, TILE), Sense::click_and_drag());
s.paint(app, ui, r, i);
outline(ui, r, sel.contains(&g.name), resp.hovered());
cell_input(ui, &resp.on_hover_text(&g.name), s.d, i, false, ev);
let resp = resp.on_hover_text(&g.name);
cell_input(ui, &resp, s.d, i, false, ev);
if in_panel {
if resp.secondary_clicked() && !sel.contains(&g.name) {
*sel = vec![g.name.clone()];
set_pstate(ui.ctx(), "gs-anchor", g.name.clone());
set_pstate(ui.ctx(), "gs-sel", sel.clone());
}
resp.context_menu(|ui| item_context_menu(app, ui, &g.name, sel));
}
}
});
}
/// The list views' rows (`row`: height and thumbnail side), `sel` highlighted.
fn rows(app: &VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &[String], row: (f32, f32), ev: &mut Events) {
fn rows(app: &mut VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &mut Vec<String>, row: (f32, f32), ev: &mut Events) {
let t = Tokens::get(ui.ctx());
let (h, side) = row;
for (i, g) in s.d.graphic_styles.iter().enumerate() {
@@ -514,7 +580,14 @@ fn rows(app: &VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &[String], row: (f32,
s.paint(app, ui, th, i);
ui.painter().rect_stroke(th, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside);
ui.painter().text(pos2(th.right() + 8.0, r.center().y), egui::Align2::LEFT_CENTER, &g.name, egui::FontId::proportional(12.0), t.text);
let resp = resp.on_hover_text(&g.name);
cell_input(ui, &resp, s.d, i, true, ev);
if resp.secondary_clicked() && !sel.contains(&g.name) {
*sel = vec![g.name.clone()];
set_pstate(ui.ctx(), "gs-anchor", g.name.clone());
set_pstate(ui.ctx(), "gs-sel", sel.clone());
}
resp.context_menu(|ui| item_context_menu(app, ui, &g.name, sel));
}
}
@@ -588,7 +661,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
};
let looks = look_hashes(ui.ctx(), app);
let shown = Shown { d: &doc, looks: &looks, preview: pstate(ui.ctx(), "gs-preview") };
let sel = selected(ui.ctx(), &doc);
let mut sel = selected(ui.ctx(), &doc);
let view = app.ui.graphic_styles_view;
let mut ev = Events::default();
// In a sized panel the list fills the space above the footer (#2992), as the Artboards list
@@ -609,8 +682,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
return;
}
match view.row() {
Some(row) => rows(app, ui, &shown, &sel, row, &mut ev),
None => tiles(app, ui, &shown, &sel, &mut ev),
Some(row) => rows(app, ui, &shown, &mut sel, row, &mut ev),
None => tiles(app, ui, &shown, &mut sel, &mut ev, true),
}
});
// The drop zone is the part of the list on screen: when the list shrinks to its rows,
@@ -674,8 +747,9 @@ pub(crate) fn picker(app: &mut VectorcraftApp, ui: &mut Ui) {
let looks = look_hashes(ui.ctx(), app);
let shown = Shown { d: &doc, looks: &looks, preview: pstate(ui.ctx(), "gs-preview") };
let mut ev = Events::default();
let mut sel = Vec::new();
ui.set_max_width(6.0 * (TILE + 3.0));
tiles(app, ui, &shown, &[], &mut ev);
tiles(app, ui, &shown, &mut sel, &mut ev, false);
act(app, ui, &shown, ev, true);
}
@@ -1755,4 +1829,184 @@ mod tests {
frame_with(&ctx, click(false), |ui| picker(&mut app, ui));
assert_eq!(app.session.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name, true)));
}
#[test]
fn right_click_context_menu_in_graphic_styles_panel() {
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = app();
app.run("graphicStyle.new", json!({"name": "Style A"})).unwrap();
app.run("graphicStyle.new", json!({"name": "Style B"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state(
|ui, app: &mut VectorcraftApp| {
show(app, ui);
},
app,
);
h.run_steps(2);
// Initially "Style B" was added last; "Style A" is unselected.
let pos_a = h.get_by_label("Style A").rect().center();
// 1. Right-click unselected "Style A"
h.event(egui::Event::PointerMoved(pos_a));
h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
// Right-clicking unselected "Style A" selects it.
let doc = h.state().session.active().unwrap().doc.clone();
assert_eq!(selected(&h.ctx, &doc), vec!["Style A"]);
// Context menu items are displayed
let options = h.get_by_label(" Graphic Style Options…");
let duplicate = h.get_by_label(" Duplicate Graphic Style");
let delete = h.get_by_label(" Delete Graphic Style");
let redefine = h.get_by_label(" Redefine Graphic Style");
let break_link = h.get_by_label(" Break Link to Graphic Style");
assert!(!options.accesskit_node().is_disabled());
assert!(!duplicate.accesskit_node().is_disabled());
assert!(!delete.accesskit_node().is_disabled());
assert!(!redefine.accesskit_node().is_disabled()); // Art is selected
assert!(break_link.accesskit_node().is_disabled()); // Art not linked to Style A
// 2. Click "Duplicate Graphic Style"
duplicate.click();
h.run_steps(3);
let doc = h.state().session.active().unwrap().doc.clone();
assert!(doc.graphic_style("Style A copy").is_some());
assert_eq!(selected(&h.ctx, &doc), vec!["Style A copy"]);
// 3. Apply Style A to the active art and verify Break Link
h.state_mut().run("graphicStyle.apply", json!({"name": "Style A"})).unwrap();
// Modify appearance so style is out of sync (not linked)
h.state_mut().run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
h.run_steps(2);
let pos_a = h.get_by_label("Style A").rect().center();
h.event(egui::Event::PointerMoved(pos_a));
h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
let break_link = h.get_by_label(" Break Link to Graphic Style");
assert!(break_link.accesskit_node().is_disabled(), "Break link is disabled when style is out of sync");
// Close menu
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
h.run_steps(2);
// Reapply Style A so it is in sync
h.state_mut().run("graphicStyle.apply", json!({"name": "Style A"})).unwrap();
h.run_steps(2);
let pos_a = h.get_by_label("Style A").rect().center();
h.event(egui::Event::PointerMoved(pos_a));
h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
let break_link = h.get_by_label(" Break Link to Graphic Style");
assert!(!break_link.accesskit_node().is_disabled(), "Break link is enabled when style is in sync");
break_link.click();
h.run_steps(3);
assert!(h.state().session.selection_graphic_style().is_none());
// 4. Right-click Style A and click "Delete Graphic Style"
let pos_a = h.get_by_label("Style A").rect().center();
h.event(egui::Event::PointerMoved(pos_a));
h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
let delete = h.get_by_label(" Delete Graphic Style");
assert!(!delete.accesskit_node().is_disabled());
delete.click();
h.run_steps(3);
let doc = h.state().session.active().unwrap().doc.clone();
assert!(doc.graphic_style("Style A").is_none());
// Verify one undo step restores it
h.state_mut().run("edit.undo", json!({})).unwrap();
let doc = h.state().session.active().unwrap().doc.clone();
assert!(doc.graphic_style("Style A").is_some());
}
#[test]
fn right_click_context_menu_default_style_disables_options_and_delete() {
use egui_kittest::kittest::{NodeT, Queryable};
let app = app();
let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state(
|ui, app: &mut VectorcraftApp| {
show(app, ui);
},
app,
);
h.run_steps(2);
let pos_def = h.get_by_label(DEFAULT_GRAPHIC_STYLE).rect().center();
h.event(egui::Event::PointerMoved(pos_def));
h.event(egui::Event::PointerButton { pos: pos_def, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: pos_def, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
let options = h.get_by_label(" Graphic Style Options…");
let duplicate = h.get_by_label(" Duplicate Graphic Style");
let delete = h.get_by_label(" Delete Graphic Style");
assert!(options.accesskit_node().is_disabled(), "Options disabled on Default Graphic Style");
assert!(!duplicate.accesskit_node().is_disabled(), "Duplicate enabled on Default Graphic Style");
assert!(delete.accesskit_node().is_disabled(), "Delete disabled on Default Graphic Style");
}
#[test]
fn right_click_context_menu_preserves_multiselection_and_works_in_list_view() {
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = app();
app.ui.graphic_styles_view = View::SmallList;
app.run("graphicStyle.new", json!({"name": "Style 1"})).unwrap();
app.run("graphicStyle.new", json!({"name": "Style 2"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state(
|ui, app: &mut VectorcraftApp| {
show(app, ui);
},
app,
);
h.run_steps(2);
set_pstate(&h.ctx, "gs-sel", vec!["Style 1".to_string(), "Style 2".to_string()]);
h.run_steps(1);
let pos_2 = h.get_by_label("Style 2").rect().center();
h.event(egui::Event::PointerMoved(pos_2));
h.event(egui::Event::PointerButton { pos: pos_2, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });
h.event(egui::Event::PointerButton { pos: pos_2, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
let doc = h.state().session.active().unwrap().doc.clone();
assert_eq!(selected(&h.ctx, &doc), vec!["Style 1", "Style 2"]);
let options = h.get_by_label(" Graphic Style Options…");
let duplicate = h.get_by_label(" Duplicate Graphic Styles");
let delete = h.get_by_label(" Delete Graphic Styles");
assert!(options.accesskit_node().is_disabled(), "Options disabled on multi-selection");
assert!(!duplicate.accesskit_node().is_disabled());
assert!(!delete.accesskit_node().is_disabled());
duplicate.click();
h.run_steps(3);
let doc = h.state().session.active().unwrap().doc.clone();
assert!(doc.graphic_style("Style 1 copy").is_some());
assert!(doc.graphic_style("Style 2 copy").is_some());
}
}
@@ -1575,11 +1575,11 @@ fn direct_selected_corners_show_their_kind_and_radius() {
// The whole path selected.
app.run("select.set", json!({"ids": [star]})).unwrap();
assert!(!shows(&tall(&mut app, &ctx, vec![]), "Corner:"), "no corner selected");
// A live rectangle's corner: its own Corner Radius row, once.
// A live rectangle's corner: its own Corner Radius row and Corner menu, once each.
let r = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap();
app.run("select.anchors", json!({"id": r, "anchors": [[0, 1]], "mode": "set"})).unwrap();
let texts = tall(&mut app, &ctx, vec![]);
assert!(!shows(&texts, "Corner:"), "{texts:?}");
assert_eq!(texts.iter().filter(|(t, _)| t == "Corner:").count(), 1, "{texts:?}");
assert_eq!(texts.iter().filter(|(t, _)| t == "Corner Radius:").count(), 1, "{texts:?}");
}
@@ -199,6 +199,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
json!("bristle-brushes"),
json!("paint"),
json!("pattern-borders"),
json!("decorative"),
json!("scatter-shapes"),
json!("stipple"),
json!("game-trails"),
@@ -249,6 +250,17 @@ 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);
// Without brushes there is nothing to save.
let all: Vec<String> = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect();
app.run("brush.delete", json!({ "names": all })).unwrap();
let entries = crate::menus::menu_entries(&app);
assert!(entries.iter().any(|e| under(e) && e.command.as_deref() == Some("ui.saveBrushLibrary") && !e.enabled));
}
#[test]
fn pressure_decorative_paint_and_image_libraries_add_a_brush_in_one_step() {
let mut app = app();
let ctx = context();
let r = app.run("window.brushLibrary", json!({"library": "Pressure Sensitive"})).unwrap();
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("pressure-sensitive"), Some(4)));
let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap();
@@ -260,11 +272,22 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(),
Some("Flex Ribbon")
);
let r = app.run("window.brushLibrary", json!({"library": "Decorative"})).unwrap();
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("decorative"), Some(4)));
let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap();
let undo = undo_len(&app);
click(&mut app, &ctx, "Leaf Vine", Modifiers::NONE, 5.0);
assert!(has(&app, "Leaf Vine") && !has(&app, "Lantern String"));
assert_eq!(undo_len(&app), undo + 1);
assert_eq!(
app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(),
Some("Leaf Vine")
);
let r = app.run("window.brushLibrary", json!({"library": "Paint"})).unwrap();
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("paint"), Some(4)));
let path = app.run("shape.line", json!({"x1": 10, "y1": 140, "x2": 180, "y2": 140})).unwrap()["id"].as_u64().unwrap();
let undo = undo_len(&app);
click(&mut app, &ctx, "Flat Sweep", Modifiers::NONE, 5.0);
click(&mut app, &ctx, "Flat Sweep", Modifiers::NONE, 6.0);
assert!(has(&app, "Flat Sweep") && !has(&app, "Dry Drag"));
assert_eq!(undo_len(&app), undo + 1);
assert_eq!(
@@ -274,14 +297,9 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
let r = app.run("window.brushLibrary", json!({"library": "Image Brush"})).unwrap();
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("image-brush"), Some(4)));
let undo = undo_len(&app);
click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 6.0);
click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 8.0);
assert!(has(&app, "Soft Bloom") && !has(&app, "Color Flecks"));
assert_eq!(undo_len(&app), undo + 1);
// Without brushes there is nothing to save.
let all: Vec<String> = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect();
app.run("brush.delete", json!({ "names": all })).unwrap();
let entries = crate::menus::menu_entries(&app);
assert!(entries.iter().any(|e| under(e) && e.command.as_deref() == Some("ui.saveBrushLibrary") && !e.enabled));
}
#[test]
@@ -1072,7 +1072,7 @@ fn ui_color_wheel_sets_and_reads_the_sliders() {
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none"));
assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hwb"})).unwrap_err(), "`sliders` must be none, oklch or hsl");
let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap();
let want = json!({"view": "box", "channel": "red", "harmony": false, "harmonyRule": "complementary", "vision": false, "sliders": "oklch"});
let want = json!({"view": "box", "channel": "red", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false, "sliders": "oklch"});
assert_eq!(got, want);
let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hwb"})).unwrap_err();
assert_eq!(e, "`sliders` must be none, oklch or hsl");
@@ -167,7 +167,7 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() {
#[test]
fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let harmony = json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "vision": false});
let harmony = json!({"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false});
let with = |v: serde_json::Value| {
let mut v = v;
v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone());
@@ -217,9 +217,9 @@ fn ui_color_wheel_rejects_other_params() {
let e = app.run("ui.colorWheel", json!([1])).unwrap_err();
assert_eq!(e, "the params must be an object, not [1]");
let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err();
assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, sliders, harmony, harmonyRule, vision");
assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision");
let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err();
assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders, harmony, harmonyRule, vision");
assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing");
}
@@ -277,7 +277,7 @@ fn ui_color_wheel_answers_junk_params_without_a_panic() {
#[test]
fn the_settings_are_kept_and_read_leniently() {
let ui = crate::UiState {
color_wheel: Settings { view: View::Box, channel: Channel::Blue, vision: true, ..Default::default() },
color_wheel: Settings { view: View::Box, channel: Channel::Blue, gamut: true, vision: true, ..Default::default() },
color_rgb_percent: true,
..Default::default()
};
@@ -0,0 +1,265 @@
//! The Color Wheel panel's Show Out-of-Gamut Colors: the grid of out-of-gamut cells, its cache, the
//! wheel's square and the box sharing it, `ui.colorWheel {gamut}`, the panel menu and the saved
//! setting.
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use vectorcraft_color::cms::{self, Cms, ColorSettings};
use vectorcraft_color::{Color, hsb_to_rgb};
use vectorcraft_engine::Session;
use super::color_wheel::{GAMUT, GAMUT_CELLS, GamutGrid, GamutKey, Settings, View, box_pick, cached_grid, gamut_grid, show};
use crate::VectorcraftApp;
use crate::dialogs::color_picker::Channel;
/// Whether cell `col` of row `row` (from the top-left) of `grid` is out of gamut.
fn marked(grid: &GamutGrid, col: usize, row: usize) -> bool {
(grid[row] >> col) & 1 == 1
}
/// An app with a selected rectangle filled with `fill`, its Color Wheel panel on `view` with Show
/// Out-of-Gamut Colors set to `gamut`.
fn app(fill: &str, view: &str, gamut: bool) -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
app.run("paint.setFill", json!({"color": fill})).unwrap();
app.run("ui.colorWheel", json!({"view": view, "channel": "hue", "gamut": gamut})).unwrap();
app
}
fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> {
let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app);
h.run_steps(2);
h
}
/// The grid the panel drew last, with its key.
fn drawn(h: &Harness<'static, VectorcraftApp>) -> Option<(GamutKey, GamutGrid)> {
super::pstate::<Option<(GamutKey, GamutGrid)>>(&h.ctx, GAMUT)
}
/// At hue 240° the field's top-right cell is nearly pure blue, which the CMYK space cannot print,
/// and its bottom-left cell is nearly black, which it can. Each cell is the color a pick at its
/// center stores, tested as the out-of-gamut warning tests it.
#[test]
fn the_hue_grid_marks_blue_and_leaves_black() {
let cms = Cms::default();
let grid = gamut_grid(&cms, Channel::Hue, 240.0 / 360.0);
let last = GAMUT_CELLS - 1;
assert!(marked(&grid, last, 0), "{grid:04x?}");
assert!(!marked(&grid, 0, last), "{grid:04x?}");
for row in 0..GAMUT_CELLS {
for col in 0..GAMUT_CELLS {
let n = GAMUT_CELLS as f32;
let hsb = box_pick(Channel::Hue, 240.0 / 360.0, (col as f32 + 0.5) / n, (row as f32 + 0.5) / n, [0.0; 3]);
let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(hsb));
assert_eq!(marked(&grid, col, row), cms.out_of_gamut(&Color::rgb(r, g, b)), "cell {col}, {row}");
}
}
}
/// In the Blue box at full blue, the field's bottom-left cell (no red, no green) is nearly pure
/// blue.
#[test]
fn an_rgb_box_marks_its_own_cells() {
let grid = gamut_grid(&Cms::default(), Channel::Blue, 1.0);
assert!(marked(&grid, 0, GAMUT_CELLS - 1), "{grid:04x?}");
}
/// With uncalibrated CMYK as the CMYK space every color counts as printable, as the out-of-gamut
/// warning has it, so no cell is marked.
#[test]
fn uncalibrated_cmyk_marks_nothing() {
let cms = Cms::new(&ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..ColorSettings::default() }).unwrap();
assert_eq!(gamut_grid(&cms, Channel::Hue, 240.0 / 360.0), [0; GAMUT_CELLS]);
}
/// The cache computes a grid once per key: the same channel, value, color settings and profile
/// generation reuse it, and a change of any of them computes it again.
#[test]
fn the_cache_computes_once_per_key() {
let mut slot = None;
let mut runs = 0;
let settings = ColorSettings::default();
let mut get = |slot: &mut Option<(GamutKey, GamutGrid)>, key: GamutKey| {
cached_grid(slot, key, || {
runs += 1;
[runs; GAMUT_CELLS]
})
};
let key = (Channel::Hue, 0.5f32.to_bits(), settings.clone(), 0);
assert_eq!(get(&mut slot, key.clone()), [1; GAMUT_CELLS]);
assert_eq!(get(&mut slot, key.clone()), [1; GAMUT_CELLS], "the same key is not computed again");
assert_eq!(get(&mut slot, (Channel::Hue, 0.25f32.to_bits(), settings.clone(), 0)), [2; GAMUT_CELLS]);
assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), settings.clone(), 0)), [3; GAMUT_CELLS]);
let device = ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..settings };
assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), device.clone(), 0)), [4; GAMUT_CELLS]);
assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), device, 1)), [5; GAMUT_CELLS], "a profile loaded again");
}
/// A profile loaded again under the same name can change which colors are printable while the
/// color settings stay the same, so the panel tests the colors again after a profile is
/// registered.
#[test]
fn the_grid_is_computed_again_after_a_profile_is_loaded() {
let mut h = harness(app("#3366cc", "box", true));
let Some((before, _)) = drawn(&h) else { panic!("the box drew no grid") };
/// Unregisters the profile when dropped, also after a failed assertion.
struct Unregister(&'static str);
impl Drop for Unregister {
fn drop(&mut self) {
cms::unregister_icc(self.0);
}
}
let name = "Color Wheel Gamut Reload CMYK";
let bytes = cms::icc_bytes(cms::GENERIC_CMYK).unwrap();
cms::register_icc(&bytes, Some(name.into())).unwrap();
let _unregister = Unregister(name);
h.run_steps(2);
let Some((after, _)) = drawn(&h) else { panic!("the box drew no grid") };
assert_eq!((after.0, after.1, &after.2), (before.0, before.1, &before.2));
assert!(after.3 > before.3, "the key follows the loaded profiles: {} then {}", before.3, after.3);
}
/// The wheel's square is the hue box at the ring's hue: both draw the same grid, under one key, so
/// a switch between them does not test the colors again.
#[test]
fn the_wheel_and_the_hue_box_shade_the_same_cells() {
let mut h = harness(app("#3366cc", "wheel", true));
let cms = cms::active();
let Some((key, grid)) = drawn(&h) else { panic!("the wheel drew no grid") };
let z = f32::from_bits(key.1);
assert_eq!((key.0, &key.2), (Channel::Hue, cms.settings()));
assert!((z * 360.0 - 220.0).abs() < 0.5, "the ring's hue: {}", z * 360.0);
assert_eq!(grid, gamut_grid(&cms, Channel::Hue, z));
h.state_mut().run("ui.colorWheel", json!({"view": "box"})).unwrap();
h.run_steps(2);
// Other tests in this process may register profiles between the frames, which changes the
// key's profile generation; the channel, value, settings and grid stay the same.
let Some((boxed, boxed_grid)) = drawn(&h) else { panic!("the box drew no grid") };
assert_eq!((boxed.0, boxed.1, &boxed.2, boxed_grid), (key.0, key.1, &key.2, grid));
}
/// With Show Out-of-Gamut Colors off, the panel tests no colors.
#[test]
fn with_the_setting_off_no_grid_is_computed() {
let h = harness(app("#3366cc", "box", false));
assert_eq!(drawn(&h), None);
}
/// `ui.colorWheel {gamut}` sets the setting and keeps the others; a key set to null keeps its value
/// while the other keys apply; a value that is not true or false is an error that changes nothing,
/// translated where messages are.
#[test]
fn ui_color_wheel_sets_gamut() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let with = |v: serde_json::Value| {
let mut v = v;
let rest = json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "vision": false});
v.as_object_mut().unwrap().extend(rest.as_object().unwrap().clone());
v
};
app.run("ui.colorWheel", json!({"view": "box"})).unwrap();
assert_eq!(app.run("ui.colorWheel", json!({"gamut": true})).unwrap(), with(json!({"view": "box", "channel": "hue", "gamut": true})));
let e = app.run("ui.colorWheel", json!({"view": "wheel", "gamut": "yes"})).unwrap_err();
assert_eq!(e, "`gamut` must be true or false");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, gamut: true, ..Default::default() }, "an error changes nothing");
assert_eq!(app.run("ui.colorWheel", json!({"gamut": null})).unwrap()["gamut"], json!(true), "null keeps the value");
app.run("ui.colorWheel", json!({"channel": "red"})).unwrap();
let got = app.run("ui.colorWheel", json!({"view": "wheel", "channel": null, "gamut": null})).unwrap();
assert_eq!(got, with(json!({"view": "wheel", "channel": "red", "gamut": true})), "null keeps a value while the other keys apply");
let got = app.run("ui.colorWheel", json!({"view": null, "gamut": false})).unwrap();
assert_eq!(got, with(json!({"view": "wheel", "channel": "red", "gamut": false})), "a null view keeps the view while gamut applies");
for code in ["de", "fr", "ja", "zh-hans"] {
let lang = crate::i18n::Lang::from_code(code).expect("registered");
let shown = crate::i18n::message(lang, &e);
assert_ne!(shown, e, "{code}");
assert!(shown.contains("`gamut`"), "{code}: {shown}");
}
}
/// The setting survives a JSON round trip of the preferences, and a saved value that is not true
/// or false reads as off without losing the other settings.
#[test]
fn the_gamut_setting_is_kept_and_read_leniently() {
let ui = crate::UiState { color_wheel: Settings { view: View::Box, gamut: true, ..Default::default() }, ..Default::default() };
let saved = serde_json::to_value(&ui).unwrap();
assert_eq!(saved["color_wheel"]["gamut"], json!(true));
let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(back.color_wheel, ui.color_wheel);
let mut odd = saved;
odd["color_wheel"] = json!({"view": "box", "channel": "red", "gamut": "yes"});
let back: crate::UiState = serde_json::from_value(odd).unwrap();
assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::Red, gamut: false, ..Default::default() });
}
/// The panel menu's Show Out-of-Gamut Colors is checked while the setting is on, and switches it.
#[test]
fn the_panel_menu_switches_the_shading() {
let app = app("#ff0000", "wheel", false);
let mut fonts = false;
let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
// The fonts, which draw the check mark, take effect from the next frame.
if !fonts {
crate::theme::install_fonts(ui.ctx());
fonts = true;
return;
}
assert!(super::panel_menu_items(app, ui, super::color_wheel::ID));
},
app,
);
h.run_steps(3);
h.get_by_label(" Show Out-of-Gamut Colors").click();
h.run_steps(2);
assert!(h.state().ui.color_wheel.gamut);
assert!(h.query_by_label("✓ Show Out-of-Gamut Colors").is_some());
h.get_by_label("✓ Show Out-of-Gamut Colors").click();
h.run_steps(2);
assert!(!h.state().ui.color_wheel.gamut);
}
/// The edge runs between the marked cells and the others, inside the grid only, and bits past the
/// grid's width are not cells.
#[test]
fn the_edge_runs_between_marked_and_unmarked_cells() {
assert_eq!(crate::widgets::shade_edges(&[0b01, 0b00]), vec![[(1, 0), (1, 1)], [(0, 1), (1, 1)]]);
assert_eq!(crate::widgets::shade_edges(&[0b11, 0b11]), Vec::<[(usize, usize); 2]>::new(), "all marked");
assert_eq!(crate::widgets::shade_edges(&[0b100]), Vec::<[(usize, usize); 2]>::new(), "bit 2 is past a 1 × 1 grid");
assert_eq!(crate::widgets::shade_edges(&[]), Vec::<[(usize, usize); 2]>::new());
}
/// The gray covers each marked cell and no other, and each edge is drawn dark, then light on top.
#[test]
fn the_gray_covers_the_marked_cells_only() {
use egui::{Pos2, Rect, Shape};
let ctx = egui::Context::default();
let rect = Rect::from_min_size(Pos2::new(10.0, 20.0), vec2(16.0, 16.0));
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::widgets::shade_cells(ui.painter(), rect, &[0b01, 0b10]));
out.textures_delta.clear();
let grays: Vec<Rect> = out
.shapes
.iter()
.filter_map(|c| match &c.shape {
Shape::Rect(r) if r.fill == crate::widgets::SHADE => Some(r.rect),
_ => None,
})
.collect();
let cell = |col: f32, row: f32| Rect::from_min_size(Pos2::new(10.0 + col * 8.0, 20.0 + row * 8.0), vec2(8.0, 8.0));
assert_eq!(grays, vec![cell(0.0, 0.0), cell(1.0, 1.0)]);
let lines: Vec<(f32, egui::Color32)> = out
.shapes
.iter()
.filter_map(|c| match &c.shape {
Shape::LineSegment { stroke, .. } => Some((stroke.width, stroke.color)),
_ => None,
})
.collect();
let dark = vec![(2.0, egui::Color32::BLACK); 4];
let light = vec![(1.0, egui::Color32::WHITE); 4];
assert_eq!(lines, [dark, light].concat(), "four edges, dark under light");
}
@@ -225,7 +225,7 @@ fn the_panel_menu_turns_the_row_on_and_off() {
#[test]
fn ui_color_wheel_sets_and_reads_the_settings() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none"});
let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none"});
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false));
assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), settings("wheel", true));
assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["vision"], true);
@@ -236,7 +236,7 @@ fn ui_color_wheel_sets_and_reads_the_settings() {
assert_eq!(app.run("ui.colorWheel", json!(5)).unwrap_err(), "the params must be an object, not 5");
assert_eq!(
app.run("ui.colorWheel", json!({"visoin": false})).unwrap_err(),
"unknown parameter `visoin`; the command takes: view, channel, sliders, harmony, harmonyRule, vision"
"unknown parameter `visoin`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision"
);
assert!(app.ui.color_wheel.vision);
assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true);
+122
View File
@@ -253,6 +253,128 @@ fn a_change_reaches_each_selected_3d_effect_and_no_other_effect() {
assert_eq!(fx(c)[0].params, c_shadow);
}
/// A custom bevel picked in the panel sends its name and points with `bevel`, to the effects that
/// take a bevel only, and another custom bevel replaces them.
#[test]
fn a_custom_bevel_sends_its_name_and_points() {
let mut app = app();
let a = app.session.active().unwrap().selection.objects[0].0;
set_type(&mut app, "extrude").unwrap();
let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": "threeD.inflate", "item": null})).unwrap();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let ctx = egui::Context::default();
let pick = |name: &str, points: Value| {
Map::from_iter([
("bevel".to_string(), json!("custom")),
(vectorcraft_effects::BEVEL_NAME.to_string(), json!(name)),
(vectorcraft_effects::BEVEL_PROFILE.to_string(), points),
])
};
let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]);
send(&mut app, &ctx, pick("Notch", notch.clone()), false);
let fx = |app: &VectorcraftApp, id: u64| {
app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params.clone()
};
let p = fx(&app, a);
assert_eq!(
(&p["bevel"], &p[vectorcraft_effects::BEVEL_NAME], &p[vectorcraft_effects::BEVEL_PROFILE]),
(&json!("custom"), &json!("Notch"), &notch)
);
assert!(fx(&app, b).get(vectorcraft_effects::BEVEL_PROFILE).is_none());
let steps = json!([[0.0, 0.0], [0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [1.0, 1.0]]);
send(&mut app, &ctx, pick("Steps", steps.clone()), false);
let p = fx(&app, a);
assert_eq!((&p[vectorcraft_effects::BEVEL_NAME], &p[vectorcraft_effects::BEVEL_PROFILE]), (&json!("Steps"), &steps));
}
/// With one Extrude & Bevel on a custom bevel and one without, picking that custom bevel sends its
/// name and points too, though the form already held them, so both effects take it.
#[test]
fn a_custom_bevel_picked_for_a_mixed_selection_reaches_every_effect() {
let mut app = app();
let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]);
let custom = json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch});
app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": custom})).unwrap();
let a = app.session.active().unwrap().selection.objects[0].0;
let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let mut fields = target(&app).map(|t| vectorcraft_effects::merged_params(&t.effect, &t.params)).unwrap().as_object().cloned().unwrap();
super::mark_mixed(&app, &mut fields);
assert_eq!((&fields["bevel"], &fields[vectorcraft_effects::BEVEL_NAME]), (&Value::Null, &json!("Notch")));
let before = Value::Object(fields.clone());
fields.insert("bevel".into(), json!("custom"));
let changed = changed_settings(&before, &Value::Object(fields));
assert_eq!(Value::Object(changed.clone()), json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch}));
send(&mut app, &egui::Context::default(), changed, false);
let st = app.session.active().unwrap();
for id in [a, b] {
let p = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params;
assert_eq!((&p["bevel"], &p[vectorcraft_effects::BEVEL_PROFILE]), (&json!("custom"), &notch), "{id}");
}
}
/// Two custom bevels the bevels file does not list: the mixed selection unsets the shown points,
/// and Bevel Shape still lists the first effect's own bevel, which then reaches both effects.
#[test]
fn a_mixed_selection_still_lists_the_first_effects_own_custom_bevel() {
use crate::dialogs::revolve::{OWN_BEVEL, bevel_options};
let mut app = app();
let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]);
let steps = json!([[0.0, 0.0], [0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [1.0, 1.0]]);
let custom = |name: &str, points: &Value| json!({"bevel": "custom", "bevelName": name, "bevelProfile": points});
app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": custom("Notch", &notch)})).unwrap();
let a = app.session.active().unwrap().selection.objects[0].0;
let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": custom("Steps", &steps)})).unwrap();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let mut fields = target(&app).map(|t| vectorcraft_effects::merged_params(&t.effect, &t.params)).unwrap().as_object().cloned().unwrap();
let own = super::own_bevel(&fields).unwrap();
super::mark_mixed(&app, &mut fields);
assert_eq!(fields[vectorcraft_effects::BEVEL_PROFILE], Value::Null);
fields.insert(OWN_BEVEL.into(), own);
let (options, builtin) = bevel_options(&app, &fields, "threeD.extrude");
assert_eq!(options.len(), builtin + 1);
let (label, value, picked) = options[builtin].clone();
assert_eq!((label.as_str(), value), ("Notch", json!("custom")));
let (name, points) = picked.unwrap();
assert_eq!(points, notch);
// Picking it sends the whole bevel to both effects.
fields.remove(OWN_BEVEL);
let before = Value::Object(fields.clone());
fields.insert(vectorcraft_effects::BEVEL_NAME.into(), json!(name));
fields.insert(vectorcraft_effects::BEVEL_PROFILE.into(), points);
send(&mut app, &egui::Context::default(), changed_settings(&before, &Value::Object(fields)), false);
let st = app.session.active().unwrap();
for id in [a, b] {
let p = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params;
assert_eq!((&p[vectorcraft_effects::BEVEL_NAME], &p[vectorcraft_effects::BEVEL_PROFILE]), (&json!("Notch"), &notch), "{id}");
}
}
/// An effect's own custom bevel named like a bevel of the bevels file with other points is listed
/// under its own label, so Bevel Shape does not show two entries of one name.
#[test]
fn an_own_custom_bevel_named_like_a_file_bevel_gets_its_own_label() {
use crate::dialogs::revolve::bevel_options;
let dir = std::env::temp_dir().join(format!("vectorcraft-ui-bevels-own-label-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut app = app();
app.session.attach_bevels_file(dir.join(vectorcraft_engine::cmd::bevels::FILE_NAME).to_string_lossy().to_string());
app.run("threeD.bevels.edit", json!({})).unwrap();
let file = app.session.bevels.get("Example Bevel").unwrap().profile_json();
let other = json!([[0.0, 0.0], [0.5, 0.5], [1.0, 1.0]]);
assert_ne!(file, other);
let fields = json!({"bevel": "custom", "bevelName": "Example Bevel", "bevelProfile": other}).as_object().cloned().unwrap();
let (options, builtin) = bevel_options(&app, &fields, "threeD.extrude");
let _ = std::fs::remove_dir_all(&dir);
let labels: Vec<&str> = options[builtin..].iter().map(|(l, _, _)| l.as_str()).collect();
assert_eq!(labels, ["Example Bevel", "Example Bevel (document)"]);
assert_eq!(options[builtin + 1].2, Some(("Example Bevel".to_string(), other)));
}
#[test]
fn the_panel_finds_a_3d_effect_on_a_fill() {
let mut app = app();
+40 -3
View File
@@ -11,10 +11,11 @@
use egui::Ui;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node, NodeId, NodeKind};
use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, THREE_D_TYPES, is_three_d};
use vectorcraft_effects::{BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, THREE_D_TYPES, is_three_d};
use super::{live_run, pstate, set_pstate};
use crate::VectorcraftApp;
use crate::dialogs::revolve::OWN_BEVEL;
use crate::dialogs::three_d_materials as materials;
use crate::state::Dialog;
use crate::theme::Tokens;
@@ -155,9 +156,11 @@ pub(crate) fn send(app: &mut VectorcraftApp, ctx: &egui::Context, changed: Map<S
.iter()
.filter_map(|(id, t, same_lights)| {
let takes = vectorcraft_effects::default_params(&t.effect).unwrap_or(Value::Null);
// A custom bevel's name and points go with `bevel` to the effects that take one.
let custom_bevel = |k: &str| (k == BEVEL_NAME || k == BEVEL_PROFILE) && takes.get("bevel").is_some();
let params: Map<String, Value> = pending
.iter()
.filter(|(k, _)| takes.get(k.as_str()).is_some() && (k.as_str() != "lights" || *same_lights))
.filter(|(k, _)| (takes.get(k.as_str()).is_some() || custom_bevel(k)) && (k.as_str() != "lights" || *same_lights))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
(!params.is_empty())
@@ -240,13 +243,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
// The applied effect's settings in the dialog's form, with the controls' own state.
let mut fields = vectorcraft_effects::merged_params(&t.effect, &t.params).as_object().cloned().unwrap_or_default();
let own_bevel = own_bevel(&fields);
mark_mixed(app, &mut fields);
fields.extend(pstate::<Map<String, Value>>(&ctx, UI_STATE));
fields.insert("__effect".into(), json!(t.effect));
fields.insert("__panel".into(), json!(true));
if let Some(own) = own_bevel {
fields.insert(OWN_BEVEL.into(), own);
}
let mut d = Dialog { kind: ID.into(), fields };
let before = crate::dialogs::form::params(&d);
crate::dialogs::revolve::controls(app, ui, &mut d);
d.fields.remove(OWN_BEVEL);
let edit_bevels = d.fields.remove("__editBevels").is_some();
let action = d.fields.remove(materials::ACTION).and_then(|v| materials::Action::from_value(&v));
let state: Map<String, Value> = d
.fields
@@ -259,6 +268,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let changed = changed_settings(&before, &after);
let dragging = ctx.input(|i| i.pointer.any_down());
send(app, &ctx, changed, dragging);
// Bevel Shape's Edit Bevels…: the bevels file opens as a document of its own.
if edit_bevels {
finish(app, &ctx);
if let Err(e) = app.run("threeD.bevels.edit", json!({})) {
app.ui.status = e;
}
return;
}
if quick_actions_shown(&d) {
ui.add_space(10.0);
let t = Tokens::get(ui.ctx());
@@ -581,10 +598,30 @@ pub(crate) fn mark_mixed(app: &VectorcraftApp, fields: &mut Map<String, Value>)
}
}
/// The custom bevel of an effect's settings `fields`, `[name, points]`, when its `bevel` is
/// `"custom"` with points (the Bevel Shape menu lists it while a mixed selection unsets them).
pub(crate) fn own_bevel(fields: &Map<String, Value>) -> Option<Value> {
let points = fields.get(BEVEL_PROFILE).filter(|v| !v.is_null())?;
let name = fields.get(BEVEL_NAME).and_then(Value::as_str).unwrap_or_default();
(fields.get("bevel").and_then(Value::as_str) == Some("custom")).then(|| json!([name, points]))
}
/// The settings whose values differ between `before` and `after`, with their values in `after`.
/// A change to a custom bevel (`bevel` `"custom"`, its name or its points) sends all three, so an
/// effect of a mixed selection that had none takes the whole bevel.
pub(crate) fn changed_settings(before: &Value, after: &Value) -> Map<String, Value> {
let Some(after) = after.as_object() else { return Map::new() };
after.iter().filter(|(k, v)| before.get(k.as_str()) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect()
let mut changed: Map<String, Value> =
after.iter().filter(|(k, v)| before.get(k.as_str()) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect();
let custom = ["bevel", BEVEL_NAME, BEVEL_PROFILE];
if after.get("bevel").and_then(Value::as_str) == Some("custom") && custom.iter().any(|k| changed.contains_key(*k)) {
for k in custom {
if let Some(v) = after.get(k) {
changed.insert(k.into(), v.clone());
}
}
}
changed
}
#[cfg(test)]
@@ -136,6 +136,101 @@ fn a_polygon_shows_its_polygon_properties() {
assert!(live(&app).polygon_sides_equal());
}
/// A live rectangle's Rectangle Properties show one Corner menu for all four corners while Corner
/// Radius is linked, blank when the corners' kinds differ, and one per corner when it is unlinked,
/// in the Transform panel and the Properties panel's Transform section.
#[test]
fn a_rectangle_shows_linked_and_unlinked_corner_types() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 120, "height": 80, "radius": 10})).unwrap();
let count = |shown: &[String], t: &str| shown.iter().filter(|s| *s == t).count();
let draws = [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section];
set_pref(&mut app, "singleCornerRadius", true);
for draw in draws {
let shown = texts(&mut app, draw);
assert_eq!((count(&shown, "Corner:"), count(&shown, "Round")), (1, 1), "{shown:?}");
}
// Kinds that differ leave the linked menu blank.
app.run("object.setLiveShape", json!({"kind": "chamfer", "corners": [2]})).unwrap();
for draw in draws {
let shown = texts(&mut app, draw);
assert_eq!((count(&shown, "Corner:"), count(&shown, "Round"), count(&shown, "Chamfer")), (1, 0, 0), "{shown:?}");
}
set_pref(&mut app, "singleCornerRadius", false);
for draw in draws {
let shown = texts(&mut app, draw);
for t in ["Top Left:", "Top Right:", "Bottom Right:", "Bottom Left:"] {
assert_eq!(count(&shown, t), 1, "{t} in {shown:?}");
}
assert_eq!((count(&shown, "Round"), count(&shown, "Chamfer")), (3, 1), "{shown:?}");
}
}
/// A corner kind set with no live rectangle selected leaves the selected polygon, the document and
/// its undo history as they are.
#[test]
fn a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing() {
use vectorcraft_geom::shapes::CornerKind::Chamfer;
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.run("shape.polygon", json!({"cx": 150, "cy": 150, "radius": 40, "sides": 6})).unwrap();
let st = app.session.active().unwrap();
let (before, steps) = (st.doc.clone(), st.history.undo.len());
crate::panels::set_rectangle_kinds(&mut app, Chamfer, None);
crate::panels::set_rectangle_kinds(&mut app, Chamfer, Some(2));
let st = app.session.active().unwrap();
assert!(st.doc == before, "the document changed");
assert_eq!(st.history.undo.len(), steps);
}
/// A corner kind picked while a Shape Builder merge is computed on another thread applies the
/// merge first, and sets the kind on the live rectangles selected after it.
#[test]
fn a_rectangle_corner_kind_applies_a_merge_on_another_thread_first() {
use vectorcraft_geom::shapes::CornerKind::Chamfer;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 800, "height": 200})).unwrap();
for k in 0..40 {
app.run("shape.rectangle", json!({"x": k * 10, "y": 0, "width": 20, "height": 20})).unwrap();
}
app.run("select.all", json!({})).unwrap();
app.run("tool.select", json!({"tool": "shapeBuilder"})).unwrap();
let view = app.view_info();
let at = |kind| PointerEvent {
kind,
pos: vectorcraft_geom::Point::new(15.0, 10.0),
mods: Mods::default(),
pressure: 1.0,
backquote: false,
pen: None,
};
crate::canvas::dispatch(&mut app, &at(PointerKind::Move), view);
app.session.tool_poll(view, true).unwrap();
crate::canvas::dispatch(&mut app, &at(PointerKind::Down), view);
crate::canvas::dispatch(&mut app, &at(PointerKind::Up), view);
assert!(app.session.tool_editing());
crate::panels::set_rectangle_kinds(&mut app, Chamfer, None);
assert!(!app.session.tool_editing());
let st = app.session.active().unwrap();
let labels: Vec<_> = st.history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect();
assert_eq!(labels, ["Live Shape", "Shape Builder"]);
let kinds: Vec<_> = st
.selection
.objects
.iter()
.filter_map(|id| match &st.doc.node(*id)?.kind {
NodeKind::Path { live: Some(l), .. } => match &**l {
LiveShape::Rectangle { kinds, .. } => Some(*kinds),
_ => None,
},
_ => None,
})
.collect();
assert!(!kinds.is_empty() && kinds.iter().all(|k| *k == [Chamfer; 4]), "{kinds:?}");
}
/// #3451: a live ellipse shows pie start/end angles and Invert Pie in the Transform panel and
/// the Properties panel's Transform section; typed angles update the shape.
#[test]
+36 -68
View File
@@ -2030,6 +2030,37 @@ fn description_line_rects(ctx: &egui::Context) -> DescriptionRects {
DescriptionRects { column, line }
}
/// Scrolls the field list with the wheel until the last text `label` in `texts` lies wholly inside
/// the list, above the spacing and the gap over the description line, and stays put there (the
/// wheel scrolls smoothly over several frames) → the texts of the last frame.
fn scroll_into_view(a: &mut VectorcraftApp, ctx: &egui::Context, mut texts: Vec<(String, egui::Rect)>, label: &str) -> Vec<(String, egui::Rect)> {
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -40.0),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
source: egui::MouseWheelSource::Unknown,
};
let at = |texts: &[(String, egui::Rect)]| texts.iter().rev().find(|(t, _)| t == label).map(|(_, r)| *r);
let inside = |r: Option<egui::Rect>| {
let DescriptionRects { column, line } = description_line_rects(ctx);
let bottom = line.min.y - DESCRIPTION_GAP - ctx.global_style().spacing.item_spacing.y;
let list = egui::Rect::from_min_max(column.min, egui::pos2(column.max.x, bottom));
r.is_some_and(|r| list.contains_rect(r))
};
for _ in 0..80 {
let shown = inside(at(&texts));
let next = description_frame(a, ctx, if shown { vec![] } else { vec![wheel.clone()] }).0;
let still = shown && at(&next) == at(&texts);
texts = next;
if still {
break;
}
}
assert!(inside(at(&texts)), "`{label}` lies wholly inside the field list: {texts:?}");
texts
}
/// A row with no sentence leaves the description line empty, also after another category's row
/// was described, and the dialog keeps its size.
#[test]
@@ -2517,7 +2548,7 @@ fn hovering_a_plugins_and_scratch_disks_row_shows_its_description() {
};
let rows = [
("Additional Plug-ins Folder:", "pluginsFolder"),
("Plug-in Instruction Budget", "pluginInstructionBudget"),
("Plug-in Instruction", "pluginInstructionBudget"),
("Primary:", "scratchPrimary"),
("Secondary:", "scratchSecondary"),
];
@@ -2614,31 +2645,10 @@ fn hovering_a_user_interface_row_shows_its_description() {
("Language:", "interfaceLanguage"),
];
let sentences: Vec<_> = rows.iter().map(|(_, key)| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect();
// The Language row is under the bottom of the list: the wheel scrolls it wholly into view.
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -40.0),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
source: egui::MouseWheelSource::Unknown,
};
// The Language row is under the bottom of the list: the wheel scrolls it into view.
let mut texts = texts;
for (i, (label, _)) in rows.iter().enumerate() {
for _ in 0..20 {
if texts.iter().any(|(t, _)| t == label) {
break;
}
texts = whole_texts_frame(&mut a, &ctx, vec![wheel.clone()]);
}
// The wheel scrolls smoothly over several frames: wait until the row stays put.
for _ in 0..60 {
let next = description_frame(&mut a, &ctx, vec![]).0;
let still = row(&next, label) == row(&texts, label);
texts = next;
if still {
break;
}
}
texts = scroll_into_view(&mut a, &ctx, texts, label);
description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]);
let (after, _) = description_frame(&mut a, &ctx, vec![]);
for (j, sentence) in sentences.iter().enumerate() {
@@ -2705,30 +2715,9 @@ fn hovering_a_performance_row_shows_its_description() {
}
let sentences: Vec<_> = rows.iter().map(|(_, key)| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect();
// The last rows can be under the bottom of the list: the wheel scrolls them into view.
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -40.0),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
source: egui::MouseWheelSource::Unknown,
};
let mut texts = texts;
for (i, (label, _)) in rows.iter().enumerate() {
for _ in 0..20 {
if texts.iter().any(|(t, _)| t == label) {
break;
}
texts = description_frame(&mut a, &ctx, vec![wheel.clone()]).0;
}
// The wheel scrolls smoothly over several frames: wait until the row stays put.
for _ in 0..60 {
let next = description_frame(&mut a, &ctx, vec![]).0;
let still = row(&next, label) == row(&texts, label);
texts = next;
if still {
break;
}
}
texts = scroll_into_view(&mut a, &ctx, texts, label);
description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]);
let (after, _) = description_frame(&mut a, &ctx, vec![]);
for (j, sentence) in sentences.iter().enumerate() {
@@ -2791,30 +2780,9 @@ fn hovering_a_file_handling_row_shows_its_description() {
];
let sentences: Vec<_> = rows.iter().map(|(_, key)| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect();
// The last rows can be under the bottom of the list: the wheel scrolls them into view.
let wheel = egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -40.0),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
source: egui::MouseWheelSource::Unknown,
};
let mut texts = texts;
for (i, (label, _)) in rows.iter().enumerate() {
for _ in 0..20 {
if texts.iter().any(|(t, _)| t == label) {
break;
}
texts = description_frame(&mut a, &ctx, vec![wheel.clone()]).0;
}
// The wheel scrolls smoothly over several frames: wait until the row stays put.
for _ in 0..60 {
let next = description_frame(&mut a, &ctx, vec![]).0;
let still = row(&next, label) == row(&texts, label);
texts = next;
if still {
break;
}
}
texts = scroll_into_view(&mut a, &ctx, texts, label);
description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]);
let (after, _) = description_frame(&mut a, &ctx, vec![]);
for (j, sentence) in sentences.iter().enumerate() {
+3 -2
View File
@@ -992,9 +992,10 @@ fn listed_on_its_own(c: &vectorcraft_engine::CommandSpec) -> bool {
/// Is UI command `id` (default key `sc`, params doc `params`) listed in Edit › Keyboard Shortcuts
/// whether or not an item of the menu bar runs it? It is when it has a default key or a params doc
/// of `{}` or `{path…}`. Rename has no default key, and a key press names the selection: it needs
/// no `id`.
/// no `id`. Color Picker… has no default key either, and a key press opens it for the proxy in
/// front.
fn ui_listed_on_its_own(id: &str, sc: &str, params: &str) -> bool {
!sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || id == "ui.rename"
!sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || id == "ui.rename" || id == "ui.colorPicker"
}
/// Does a menu bar item run the command with no params, so that it does what its label says and opens
+42
View File
@@ -1638,6 +1638,45 @@ fn polygonal_lasso_takes_backspace_delete_enter_and_escape_while_a_loop_is_open(
assert_eq!(sel.anchors.get(&id).map(|a| a.len()), Some(1), "only the corner inside the loop");
}
/// Color Picker… (`ui.colorPicker`) has no default key. Keyboard Shortcuts lists it, and a key
/// assigned there opens the picker for the proxy in front: with no document open, with nothing
/// selected and with an object selected, and for the stroke while the Stroke proxy is in front,
/// with or without a document open.
#[test]
fn a_key_assigned_to_the_color_picker_opens_it_for_the_proxy_in_front() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
crate::shortcut_editor::sync(&app.ui);
assert_eq!(crate::shortcut_editor::default_command_shortcut("ui.colorPicker"), None);
let listed = app.run("shortcuts.list", json!({"query": "ui.colorPicker"})).unwrap();
let rows: Vec<_> = listed.as_array().expect("rows").iter().map(|r| r["label"].clone()).collect();
assert_eq!(rows, [json!("Color Picker…")], "Keyboard Shortcuts lists it");
app.run("shortcuts.set", json!({"id": "ui.colorPicker", "shortcut": "Cmd+Alt+Shift+F12"})).unwrap();
crate::shortcut_editor::sync(&app.ui);
let key = || press(Key::F12, Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT);
let opened = |app: &mut VectorcraftApp| {
let stroke = app.ui.dialog.as_ref().filter(|d| d.kind == "colorPicker").map(|d| d.bool("stroke"));
app.ui.dialog = None;
stroke
};
frame(&mut app, key());
assert_eq!(opened(&mut app), Some(false), "no document: the fill");
app.run("paint.toggleActive", json!({"fill": false})).unwrap();
frame(&mut app, key());
assert_eq!(opened(&mut app), Some(true), "no document, the Stroke proxy in front: the stroke");
app.run("paint.toggleActive", json!({"fill": true})).unwrap();
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
frame(&mut app, key());
assert_eq!(opened(&mut app), Some(false), "nothing selected: the fill");
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [id]})).unwrap();
frame(&mut app, key());
assert_eq!(opened(&mut app), Some(false), "an object selected: the fill");
app.run("paint.toggleActive", json!({})).unwrap();
frame(&mut app, key());
assert_eq!(opened(&mut app), Some(true), "the Stroke proxy in front: the stroke");
crate::shortcut_editor::sync(&crate::state::UiState::default());
}
/// Binds Show Grid to `chord`, or with `None` leaves every command its default shortcut.
fn bind_grid(app: &mut VectorcraftApp, chord: Option<&str>) {
app.ui.shortcut_overrides.clear();
@@ -2080,13 +2119,16 @@ fn the_command_search_that_opens_while_enter_is_down_waits_for_a_new_press() {
// The empty search lists the recent picks, so the last pick is the highlighted result.
app.ui.recent_commands = vec!["paint.swap".into()];
app.ui.palette_open = true;
let before = undo_len(&app);
for repeat in 0..4 {
held.press(&mut app);
assert!(app.ui.palette_open, "repeat {repeat}: it stays open");
assert_eq!(undo_len(&app), before, "repeat {repeat}: nothing ran");
}
held.release(&mut app);
held.press(&mut app);
assert!(!app.ui.palette_open, "a new press runs the highlighted result");
assert_eq!(undo_len(&app), before + 1, "Swap Fill and Stroke ran on the rectangle: {}", app.ui.status);
}
/// Enter on a command search result whose menu item opens a dialog (Create Gradient Mesh…) opens
+14 -2
View File
@@ -651,6 +651,11 @@ pub struct UiState {
pub status_notes: Option<(String, Vec<String>)>,
pub palette_open: bool,
pub palette_query: String,
/// Set when the palette's shortcut, its command or the search icon opens or closes the palette,
/// so that the palette starts at its first row the next time it is drawn, even when it closed
/// and opened again before then. Not saved.
#[serde(skip)]
pub palette_toggled: bool,
/// Screen mode: 0 normal, 1 full screen with menu, 2 full screen, 3 presentation. Not saved:
/// the app always starts in Normal Screen Mode, with its menus and panels (#472: a saved
/// Presentation Mode came back on restart with no way out).
@@ -762,6 +767,10 @@ pub struct UiState {
/// Help › Search Commands' Recent Commands list: the ids of the last picks, most recent first.
#[serde(default)]
pub recent_commands: Vec<String>,
/// How many times each command was picked in Help › Search Commands, which ranks the commands
/// picked most often first among results that match as well.
#[serde(default, deserialize_with = "crate::palette::deserialize_command_uses")]
pub command_uses: crate::palette::CommandUses,
/// Families starred in the font menus (the ★ filter shows only these).
#[serde(default)]
pub favorite_fonts: Vec<String>,
@@ -825,8 +834,9 @@ pub struct UiState {
/// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]).
#[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")]
pub color_rgb_percent: bool,
/// Color Wheel panel: the wheel or the box, the box's channel, the slider rows and the color
/// vision row (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]).
/// Color Wheel panel: the wheel or the box, the box's channel, the slider rows, the
/// out-of-gamut shading and the color vision row
/// (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]).
#[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")]
pub color_wheel: crate::panels::color_wheel::Settings,
/// Swatches panel: Show Recent Colors in its panel menu, which draws the panel's Recent Colors
@@ -1319,6 +1329,7 @@ impl Default for UiState {
status_notes: None,
palette_open: false,
palette_query: String::new(),
palette_toggled: false,
screen_mode: 0,
tiled: false,
tile_layout: crate::canvas::TileLayout::Grid,
@@ -1348,6 +1359,7 @@ impl Default for UiState {
recent_files: vec![],
recent_fonts: vec![],
recent_commands: vec![],
command_uses: Default::default(),
favorite_fonts: vec![],
engine_prefs: Value::Null,
original_editor: Default::default(),
+142
View File
@@ -744,6 +744,148 @@ fn the_shape_properties_popup_keeps_its_corner_dropdown() {
assert!(!kinds.is_empty() && kinds.iter().all(|k| *k == vectorcraft_geom::shapes::CornerKind::Chamfer), "{kinds:?}");
}
/// A rectangle's Corner menu in the popup sets the kind of all four corners in one undo step while
/// Corner Radius is linked; picking the kind they already have adds no step. Unlinked, each
/// corner's menu sets that corner alone.
#[test]
fn the_shape_properties_popup_changes_a_rectangle_corner_type() {
use vectorcraft_geom::shapes::CornerKind::{Chamfer, Round};
let mut app = app();
app.run("tool.select", json!({"tool": "selection"})).unwrap();
app.run("prefs.set", json!({"key": "singleCornerRadius", "value": true})).unwrap();
let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60, "radius": 10})).unwrap());
select(&mut app, &[rect]);
let kinds = |app: &VectorcraftApp| match live(app, rect) {
vectorcraft_doc::LiveShape::Rectangle { kinds, radii, .. } => (kinds, radii),
l => panic!("{l:?}"),
};
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let (ctx, texts) = click_lock_slot(&mut app);
let click = |app: &mut VectorcraftApp, p: Pos2| {
let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() };
frame(app, &ctx, vec![Event::PointerMoved(p), press(true), press(false)]);
frame(app, &ctx, vec![])
};
// The open list's entry for `name`, drawn after the closed menu that may show the same name.
let entry = |texts: &[(String, Rect)], name: &str| texts.iter().rev().find(|(t, _)| t == name).map(|(_, r)| r.center()).unwrap();
let before = steps(&app);
let texts = click(&mut app, at(&texts, "Round"));
let texts = click(&mut app, entry(&texts, "Chamfer"));
assert_eq!(kinds(&app), ([Chamfer; 4], [10.0; 4]), "all four corners, radii kept");
assert_eq!(steps(&app), before + 1, "one undo step");
let texts = click(&mut app, at(&texts, "Chamfer"));
// The list is open: its Chamfer row shows as well as the closed menu's, and the pick closes it.
assert_eq!(texts.iter().filter(|(t, _)| t == "Chamfer").count(), 2, "{texts:?}");
assert!(texts.iter().any(|(t, _)| t == "Inverted Round"), "{texts:?}");
let texts = click(&mut app, entry(&texts, "Chamfer"));
assert!(!texts.iter().any(|(t, _)| t == "Inverted Round"), "the pick closes the list: {texts:?}");
assert_eq!(steps(&app), before + 1, "the same kind adds no undo step");
app.run("prefs.set", json!({"key": "singleCornerRadius", "value": false})).unwrap();
let texts = frame(&mut app, &ctx, vec![]);
assert_eq!(texts.iter().filter(|(t, _)| t == "Chamfer").count(), 4, "{texts:?}");
// The first menu is the top left corner's.
let texts = click(&mut app, at(&texts, "Chamfer"));
click(&mut app, entry(&texts, "Round"));
assert_eq!(kinds(&app), ([Round, Chamfer, Chamfer, Chamfer], [10.0; 4]));
assert_eq!(steps(&app), before + 2);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(kinds(&app).0, [Chamfer; 4]);
}
/// One Transform panel frame `width` points wide: the texts drawn, with their rectangles.
fn panel_frame(app: &mut VectorcraftApp, ctx: &egui::Context, width: f32, events: Vec<Event>) -> Vec<(String, Rect)> {
let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 700.0));
let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() };
let mut out = ctx.run_ui(input, |ui| crate::panels::transform::show(app, ui));
out.textures_delta.clear();
shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::<Vec<_>>())
}
/// With several rectangles selected, the linked Corner menu sets the kind on every corner of each
/// of them, also when the rectangle the panel shows already has it, and leaves a selected polygon
/// as it is.
#[test]
fn the_linked_corner_menu_sets_every_selected_rectangle() {
use vectorcraft_geom::shapes::CornerKind::{Chamfer, Round};
let mut app = app();
app.run("prefs.set", json!({"key": "singleCornerRadius", "value": true})).unwrap();
let a = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 60, "radius": 8})).unwrap());
let b = id(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 80, "height": 60, "radius": 8})).unwrap());
let polygon = id(app.run("shape.polygon", json!({"cx": 200, "cy": 200, "radius": 40, "sides": 6})).unwrap());
app.run("object.setLiveShape", json!({"ids": [a], "kind": "chamfer"})).unwrap();
select(&mut app, &[a, b, polygon]);
let kinds = |app: &VectorcraftApp, id: u64| match live(app, id) {
vectorcraft_doc::LiveShape::Rectangle { kinds, .. } => kinds,
l => panic!("{l:?}"),
};
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let click = |app: &mut VectorcraftApp, p: Pos2| {
let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() };
panel_frame(app, &ctx, 300.0, vec![Event::PointerMoved(p), press(true), press(false)]);
panel_frame(app, &ctx, 300.0, vec![])
};
panel_frame(&mut app, &ctx, 300.0, vec![]);
let texts = panel_frame(&mut app, &ctx, 300.0, vec![]);
let steps = app.session.active().unwrap().history.undo.len();
let texts = click(&mut app, at(&texts, "Chamfer"));
let entry = texts.iter().rev().find(|(t, _)| t == "Chamfer").map(|(_, r)| r.center()).unwrap();
click(&mut app, entry);
assert_eq!((kinds(&app, a), kinds(&app, b)), ([Chamfer; 4], [Chamfer; 4]));
let vectorcraft_doc::LiveShape::Polygon { kinds: sides, .. } = live(&app, polygon) else { panic!("not a polygon") };
assert!(sides.iter().all(|k| *k == Round), "the polygon keeps its corners: {sides:?}");
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(kinds(&app, b), [Round; 4]);
}
/// Unlinked, a corner's radius field rounds that corner of each selected rectangle and leaves a
/// selected polygon as it is.
#[test]
fn an_unlinked_corner_radius_leaves_other_selected_shapes() {
let mut app = app();
app.run("prefs.set", json!({"key": "singleCornerRadius", "value": false})).unwrap();
let rect = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 60, "radius": 7})).unwrap());
let polygon = id(app.run("shape.polygon", json!({"cx": 200, "cy": 200, "radius": 40, "sides": 6})).unwrap());
select(&mut app, &[rect, polygon]);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
panel_frame(&mut app, &ctx, 300.0, vec![]);
let texts = panel_frame(&mut app, &ctx, 300.0, vec![]);
// The top left corner's field is the first that shows the radius.
let p = at(&texts, "7 pt");
let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() };
panel_frame(&mut app, &ctx, 300.0, vec![Event::PointerMoved(p), press(true), press(false)]);
panel_frame(&mut app, &ctx, 300.0, vec![]);
panel_frame(&mut app, &ctx, 300.0, vec![Event::Text("15".into())]);
let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
panel_frame(&mut app, &ctx, 300.0, vec![enter]);
panel_frame(&mut app, &ctx, 300.0, vec![]);
let vectorcraft_doc::LiveShape::Rectangle { radii, .. } = live(&app, rect) else { panic!("not a rectangle") };
assert_eq!(radii, [15.0, 7.0, 7.0, 7.0]);
let vectorcraft_doc::LiveShape::Polygon { radii, .. } = live(&app, polygon) else { panic!("not a polygon") };
assert!(radii.iter().all(|r| *r == 0.0), "the polygon keeps its corners: {radii:?}");
}
/// Unlinked, the four corner rows keep their Corner menus inside a panel at its narrowest.
#[test]
fn the_unlinked_corner_menus_fit_a_narrow_panel() {
let mut app = app();
app.run("prefs.set", json!({"key": "singleCornerRadius", "value": false})).unwrap();
let rect = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 60, "radius": 8})).unwrap());
app.run("object.setLiveShape", json!({"ids": [rect], "kind": "invertedRound"})).unwrap();
select(&mut app, &[rect]);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let width = 220.0;
panel_frame(&mut app, &ctx, width, vec![]);
let texts = panel_frame(&mut app, &ctx, width, vec![]);
let menus: Vec<_> = texts.iter().filter(|(t, _)| t.starts_with("Inverted")).collect();
assert_eq!(menus.len(), 4, "{texts:?}");
assert!(menus.iter().all(|(_, r)| r.right() <= width), "{menus:?}");
}
/// Every other selection keeps Lock: a plain closed path, a star (a plain path), a path with live
/// corners, a group and several objects. The Direct Selection tool keeps it for a basic shape.
#[test]
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more