mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 18:04:03 +01:00
Merge origin/main into feat/layers-guide-context-menu
This commit is contained in:
commit
175c180a62
161 files changed
+11744
-1145
No files matched your search
Generated
+10
@@ -1009,6 +1009,15 @@ dependencies = [
|
||||
"ruzstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
@@ -6727,6 +6736,7 @@ dependencies = [
|
||||
name = "vectorcraft-color"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-cms",
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
"proptest",
|
||||
|
||||
@@ -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 = "e7873217287876f76a045550369c90a541693c33" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
|
||||
@@ -157,6 +157,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
|
||||
@@ -9,6 +9,7 @@ description = "VectorCraft color"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-cms = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
+65
-449
@@ -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, PaletteGroup, PaletteSwatch};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary};
|
||||
@@ -83,18 +85,54 @@ 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.
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
fn swatches_to_cms(list: &[Swatch]) -> Vec<PaletteSwatch> {
|
||||
list.iter()
|
||||
.filter_map(|w| w.paint.color().map(|c| PaletteSwatch { name: w.name.clone(), color: 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()
|
||||
}
|
||||
|
||||
/// The most colors and groups one swatch exchange file holds, read or written (craft-cms reads
|
||||
/// as many).
|
||||
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";
|
||||
|
||||
fn to_cms_palette(lib: &SwatchLibrary) -> Palette {
|
||||
Palette {
|
||||
name: lib.name.clone(),
|
||||
swatches: swatches_to_cms(&lib.swatches),
|
||||
groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches) }).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(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 +151,18 @@ 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(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl),
|
||||
PaletteFormat::Ase => {
|
||||
let p = to_cms_palette(lib);
|
||||
// Counted here, so the message is VectorCraft's own and its translations apply.
|
||||
let entries = p.swatches.len() + p.groups.iter().map(|g| 1 + g.swatches.len()).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}"
|
||||
));
|
||||
}
|
||||
return cms_palette::write_palette(&p, cms_palette::PaletteFormat::Ase);
|
||||
}
|
||||
PaletteFormat::Css => write_css(lib, keep),
|
||||
};
|
||||
Ok(text.into_bytes())
|
||||
@@ -125,49 +173,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);
|
||||
@@ -276,97 +281,10 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
/// 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(text.as_bytes(), name).map(from_cms_palette);
|
||||
}
|
||||
if text.starts_with('{') {
|
||||
let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?;
|
||||
@@ -391,11 +309,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 cms_palette::sniff_palette(bytes) {
|
||||
return cms_palette::read_palette(bytes, name).map(from_cms_palette);
|
||||
}
|
||||
read(&String::from_utf8_lossy(bytes), name)
|
||||
}
|
||||
@@ -403,309 +318,10 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
|
||||
/// Are `bytes` a library [`read_bytes`] understands? Text that isn't valid UTF-8 is checked as
|
||||
/// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough).
|
||||
pub fn sniff_bytes(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(ASE_SIGNATURE)
|
||||
|| bytes.starts_with(ACB_SIGNATURE)
|
||||
cms_palette::sniff_palette(bytes)
|
||||
|| std::str::from_utf8(bytes).is_ok_and(sniff)
|
||||
|| 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;
|
||||
@@ -2,6 +2,12 @@ use super::*;
|
||||
use crate::{Gradient, GradientPaint, GradientStop};
|
||||
use proptest::prelude::*;
|
||||
|
||||
// The swatch exchange file's signature and block types, which craft-cms keeps private.
|
||||
const ASE_SIGNATURE: &[u8] = b"ASEF";
|
||||
const ASE_GROUP_START: u16 = 0xC001;
|
||||
const ASE_GROUP_END: u16 = 0xC002;
|
||||
const ASE_COLOR: u16 = 0x0001;
|
||||
|
||||
#[test]
|
||||
fn gpl_blank_name_keeps_fallback() {
|
||||
let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n";
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
//! Flare objects: the settings a flare group was drawn with (the Flare tool, `shape.flare`). Its
|
||||
//! children are ordinary paths for every renderer and exporter; the settings let it be drawn again.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Vec2, shapes};
|
||||
|
||||
use crate::Appearance;
|
||||
use crate::node::{Node, NodeId, NodeKind};
|
||||
|
||||
/// The seed of the sizes a flare's rays and rings take when its settings give none.
|
||||
pub const DEFAULT_SEED: u64 = 0x2545_f491_4f6c_dd1d;
|
||||
|
||||
/// One part of a flare: its name, outline, fill and opacity.
|
||||
pub type Part = (&'static str, PathData, Paint, f32);
|
||||
|
||||
/// The number `key` of the settings `v`, or `default`.
|
||||
fn number(v: &Value, key: &str, default: f64) -> f64 {
|
||||
v.get(key).and_then(Value::as_f64).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// The parts of a flare with the settings `v` (`shape.flare`'s params, each one given): a bright
|
||||
/// center, a halo ring, rays of varying length and rings along the path to the end point.
|
||||
pub fn parts(v: &Value) -> Vec<Part> {
|
||||
let c = Point::new(number(v, "cx", 0.0), number(v, "cy", 0.0));
|
||||
let end = Point::new(number(v, "x2", c.x), number(v, "y2", c.y));
|
||||
let pct = |k: &str| (number(v, k, 0.0) / 100.0).clamp(0.0, 10.0);
|
||||
let r = (number(v, "diameter", 100.0) / 2.0).max(0.5);
|
||||
let opacity = pct("opacity").min(1.0) as f32;
|
||||
let brightness = pct("brightness").min(1.0) as f32;
|
||||
let growth = pct("growth");
|
||||
let fuzz = pct("fuzziness").min(1.0);
|
||||
let rays = v.get("rays").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
|
||||
let longest = pct("longest");
|
||||
let ray_fuzz = pct("rayFuzziness").min(1.0);
|
||||
let ray_turn = number(v, "rotation", 0.0).to_radians();
|
||||
let rings = v.get("rings").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
|
||||
let largest = pct("largest");
|
||||
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
|
||||
// along the path from a sequence of its own; their count and sizes and the other parts stay.
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
};
|
||||
let mut rnd = random(v.get("seed").and_then(Value::as_u64).unwrap_or(DEFAULT_SEED) | 1);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
|
||||
let mut ring_at = v.get("ringSeed").and_then(Value::as_u64).filter(|r| *r < 1 << 53).map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
g.geom = Some(GradientGeom { start: centre, end: centre + Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
|
||||
let mut parts: Vec<Part> = vec![];
|
||||
// Halo: a soft ring just outside the centre.
|
||||
let halo_r = r * (1.0 + growth) * 1.6;
|
||||
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
|
||||
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
|
||||
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
|
||||
// `rotation` turns them clockwise about the center.
|
||||
if rays > 0 {
|
||||
let mut bp = BezPath::new();
|
||||
let mut reach: f64 = 0.0;
|
||||
for i in 0..rays {
|
||||
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
|
||||
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
|
||||
reach = reach.max(len);
|
||||
let w = r * 0.035;
|
||||
let dir = Vec2::new(a.cos(), a.sin());
|
||||
let n = Vec2::new(-dir.y, dir.x) * w;
|
||||
bp.move_to(c + n);
|
||||
bp.line_to(c + dir * len);
|
||||
bp.line_to(c - n);
|
||||
bp.line_to(c - dir * (w * 4.0));
|
||||
bp.close_path();
|
||||
}
|
||||
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
|
||||
}
|
||||
// Centre: bright core fading to transparent.
|
||||
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
|
||||
// Rings along the path to the end point (Largest = % of the average ring size).
|
||||
for _ in 0..rings {
|
||||
let t = rnd();
|
||||
let t = ring_at.as_mut().map_or(t, |next| next());
|
||||
let at = c + (end - c) * t;
|
||||
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
|
||||
let solid = rnd() < 0.5;
|
||||
let stops = if solid {
|
||||
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
|
||||
} else {
|
||||
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
|
||||
};
|
||||
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Part `part` of a flare as the object `id`, transformed by `xf` (the transform its flare has had
|
||||
/// since it was drawn), with the pixel-aligned property when `aligned`.
|
||||
pub fn part_node(id: NodeId, part: Part, xf: Affine, aligned: bool) -> Node {
|
||||
let (name, pd, paint, op) = part;
|
||||
let mut n = Node::path(id, pd, Appearance::basic(paint, Paint::None, 0.0));
|
||||
n.name = Some(name.into());
|
||||
n.blend = BlendMode::Screen;
|
||||
n.opacity = op;
|
||||
if aligned {
|
||||
n.extras_mut().pixel_aligned = true;
|
||||
}
|
||||
if xf != Affine::IDENTITY {
|
||||
n.transform(xf, false);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The ellipse of a radial gradient's placement `geom` as the symmetric matrix `[xx, xy, yy]` that
|
||||
/// maps it to the unit circle's: the same for every end point and aspect that give that ellipse
|
||||
/// (transforms applied one by one and all at once can put the end on different axes of it).
|
||||
fn ellipse(geom: &GradientGeom) -> [f64; 3] {
|
||||
let u = geom.end - geom.start;
|
||||
let w = Vec2::new(-u.y, u.x) * geom.aspect;
|
||||
[u.x * u.x + w.x * w.x, u.x * u.y + w.x * w.y, u.y * u.y + w.y * w.y]
|
||||
}
|
||||
|
||||
/// The ellipse `[xx, xy, yy]` ([`ellipse`]) as its size, the length of its longer half-axis, and
|
||||
/// its shape: the ratio of its shorter axis to its longer one, then the cosine and sine of twice
|
||||
/// the longer axis's angle, each times one minus that ratio (0 for a circle). Each number is a
|
||||
/// length or a ratio of lengths, never a squared length that a tiny flare or a narrow gradient
|
||||
/// makes smaller than the tolerance.
|
||||
fn ellipse_size_and_shape(geom: &GradientGeom) -> (f64, [f64; 3]) {
|
||||
let [xx, xy, yy] = ellipse(geom);
|
||||
let half_diff = (xx - yy) / 2.0;
|
||||
let d = half_diff.hypot(xy);
|
||||
let longer = (xx + yy) / 2.0 + d;
|
||||
if longer.is_nan() || longer <= 0.0 {
|
||||
return (0.0, [0.0; 3]);
|
||||
}
|
||||
// The product of the half-axes is the area factor of the map from the unit circle, `u` across
|
||||
// `w` as [`ellipse`] builds them: a sum of squares times the aspect, without the cancellation
|
||||
// of `xx * yy - xy * xy` for a narrow ellipse.
|
||||
let u = geom.end - geom.start;
|
||||
let w = Vec2::new(-u.y, u.x) * geom.aspect;
|
||||
let ratio = ((u.x * w.y - u.y * w.x).abs() / longer).min(1.0);
|
||||
let (cos, sin) = if d > 0.0 { (half_diff / d, xy / d) } else { (0.0, 0.0) };
|
||||
(longer.sqrt(), [ratio, (1.0 - ratio) * cos, (1.0 - ratio) * sin])
|
||||
}
|
||||
|
||||
/// `n` as JSON without what depends on how its transforms were applied: its id, the angle of its
|
||||
/// bounding box, and which axis of a gradient's ellipse its end point is on (the ellipse stays: its
|
||||
/// size in the placement, and its shape beside the placement, out of reach of a pixel-aligned
|
||||
/// part's snap allowance, which is a length).
|
||||
fn comparable(n: &Node) -> Value {
|
||||
fn strip(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
for key in ["id", "bbox_angle"] {
|
||||
m.remove(key);
|
||||
}
|
||||
if let Some(geom) = m.get_mut("geom")
|
||||
&& let Ok(g) = serde_json::from_value::<GradientGeom>(geom.clone())
|
||||
&& let Value::Object(geom) = geom
|
||||
{
|
||||
let (size, shape) = ellipse_size_and_shape(&g);
|
||||
geom.remove("end");
|
||||
geom.remove("aspect");
|
||||
geom.insert("ellipse".into(), serde_json::json!(size));
|
||||
m.insert("ellipseShape".into(), serde_json::json!(shape));
|
||||
}
|
||||
m.values_mut().for_each(strip);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(strip),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut v = serde_json::to_value(n).unwrap_or(Value::Null);
|
||||
strip(&mut v);
|
||||
v
|
||||
}
|
||||
|
||||
/// How close, relative to its size, a number in an outline or a gradient's placement must be to the
|
||||
/// one its transforms give: a few thousandths of a point near the edge of the canvas.
|
||||
const GEOMETRY_TOL: f64 = 1e-9;
|
||||
|
||||
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size; each
|
||||
/// number in an outline (`path`) or a gradient's placement (`geom`) is within [`GEOMETRY_TOL`]
|
||||
/// relative to its size (or `tol`, when smaller), and `snap` points as well.
|
||||
fn close(a: &Value, b: &Value, tol: f64, snap: f64, geometry: bool) -> bool {
|
||||
match (a, b) {
|
||||
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
|
||||
(Some(x), Some(y)) => {
|
||||
let (snap, tol) = if geometry { (snap, tol.min(GEOMETRY_TOL)) } else { (0.0, tol) };
|
||||
(x - y).abs() <= snap + tol * (1.0 + x.abs().max(y.abs()))
|
||||
}
|
||||
_ => x == y,
|
||||
},
|
||||
(Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| close(x, y, tol, snap, geometry)),
|
||||
(Value::Object(x), Value::Object(y)) => {
|
||||
x.len() == y.len()
|
||||
&& x.iter().all(|(k, v)| {
|
||||
// A gradient's shape is ratios: compared as closely as geometry, without the snap.
|
||||
let snap = if k == "ellipseShape" { 0.0 } else { snap };
|
||||
y.get(k).is_some_and(|w| close(v, w, tol, snap, geometry || k == "path" || k == "geom" || k == "ellipseShape"))
|
||||
})
|
||||
}
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size.
|
||||
pub fn json_close(a: &Value, b: &Value, tol: f64) -> bool {
|
||||
close(a, b, tol, 0.0, false)
|
||||
}
|
||||
|
||||
/// How far a pixel-aligned object's points may be from where its transforms put them: snapping to
|
||||
/// the pixel grid moves each by up to a pixel.
|
||||
const PIXEL_SNAP: f64 = 1.0;
|
||||
|
||||
/// The settings of a flare group ([`crate::NodeExtras::flare`]).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FlareSpec {
|
||||
/// `shape.flare`'s params the flare was drawn with, each one given: the center (`cx`, `cy`) and
|
||||
/// the rings' end point (`x2`, `y2`) are in the coordinates it was drawn in.
|
||||
pub params: serde_json::Value,
|
||||
/// The transform its art has had since it was drawn (moves, scales, rotations, reflections and
|
||||
/// shears).
|
||||
#[serde(default = "identity", skip_serializing_if = "is_identity")]
|
||||
pub transform: Affine,
|
||||
}
|
||||
|
||||
fn identity() -> Affine {
|
||||
Affine::IDENTITY
|
||||
}
|
||||
|
||||
fn is_identity(a: &Affine) -> bool {
|
||||
*a == Affine::IDENTITY
|
||||
}
|
||||
|
||||
impl FlareSpec {
|
||||
/// The settings of a flare drawn with `params`, not transformed since.
|
||||
pub fn new(params: serde_json::Value) -> Self {
|
||||
Self { params, transform: Affine::IDENTITY }
|
||||
}
|
||||
|
||||
/// The point `key_x`, `key_y` of the params, where it is in the document now.
|
||||
fn point(&self, key_x: &str, key_y: &str) -> Option<Point> {
|
||||
let x = self.params.get(key_x)?.as_f64()?;
|
||||
let y = self.params.get(key_y)?.as_f64()?;
|
||||
Some(self.transform * Point::new(x, y)).filter(|p| p.x.is_finite() && p.y.is_finite())
|
||||
}
|
||||
|
||||
/// The flare's center, where it is in the document now.
|
||||
pub fn center(&self) -> Option<Point> {
|
||||
self.point("cx", "cy")
|
||||
}
|
||||
|
||||
/// The rings' end point, where it is in the document now.
|
||||
pub fn end(&self) -> Option<Point> {
|
||||
self.point("x2", "y2")
|
||||
}
|
||||
|
||||
/// Its art transformed by `a`.
|
||||
pub fn transform(&mut self, a: Affine) {
|
||||
self.transform = a * self.transform;
|
||||
}
|
||||
|
||||
/// Whether `group`'s parts are still the ones these settings draw, in place: none was edited,
|
||||
/// distorted, removed or added, and the transform can be undone. The parts are compared where
|
||||
/// they are in the document, at any scale.
|
||||
pub fn draws(&self, group: &Node) -> bool {
|
||||
let NodeKind::Group { children, .. } = &group.kind else { return false };
|
||||
if !self.transform.is_finite() || self.transform.determinant() == 0.0 || !self.transform.inverse().is_finite() {
|
||||
return false;
|
||||
}
|
||||
let expected = parts(&self.params);
|
||||
expected.len() == children.len()
|
||||
&& expected.into_iter().zip(children).all(|(part, child)| {
|
||||
let aligned = child.extras().pixel_aligned;
|
||||
let snap = if aligned { PIXEL_SNAP } else { 0.0 };
|
||||
close(&comparable(&part_node(child.id, part, self.transform, aligned)), &comparable(child), 1e-6, snap, false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// A flare's center and end point follow its art through a transform, and a save and reload
|
||||
/// keeps its settings.
|
||||
#[test]
|
||||
fn a_flare_keeps_its_settings_through_a_transform_and_a_save() {
|
||||
let mut g = Node::group(NodeId(1), vec![std::sync::Arc::new(Node::path(NodeId(2), PathData::default(), Default::default()))]);
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec::new(json!({ "cx": 10.0, "cy": 20.0, "x2": 110.0, "y2": 20.0, "seed": 7 }))));
|
||||
g.transform(Affine::translate((5.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2), false);
|
||||
let spec = g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
|
||||
let c = spec.center().unwrap_or_else(|| panic!("no center"));
|
||||
let e = spec.end().unwrap_or_else(|| panic!("no end"));
|
||||
assert!((c.x - -15.0).abs() < 1e-9 && (c.y - 10.0).abs() < 1e-9, "{c:?}");
|
||||
assert!((e.x - -15.0).abs() < 1e-9 && (e.y - 110.0).abs() < 1e-9, "{e:?}");
|
||||
let text = serde_json::to_string(&g).unwrap_or_else(|e| panic!("{e}"));
|
||||
let back: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(back.extras().flare.as_deref(), Some(&spec));
|
||||
// A flare that was not transformed writes no transform.
|
||||
let plain = FlareSpec::new(json!({ "cx": 1.0 }));
|
||||
assert_eq!(serde_json::to_value(&plain).unwrap_or_default(), json!({ "params": { "cx": 1.0 } }));
|
||||
}
|
||||
|
||||
/// A flare group draws its settings until a part's gradient, opacity or outline is edited; a
|
||||
/// pixel-aligned part may sit up to a pixel from where its transforms put it, but only in its
|
||||
/// outline and its gradient's placement.
|
||||
#[test]
|
||||
fn a_flare_with_an_edited_part_no_longer_draws_its_settings() {
|
||||
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0,
|
||||
"opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0,
|
||||
"rotation": 0.0, "largest": 50.0 });
|
||||
let flare = |aligned: bool| {
|
||||
let xf = Affine::rotate(0.3) * Affine::scale_non_uniform(1.5, 0.75);
|
||||
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
|
||||
let mut g = Node::group(NodeId(1), children.collect());
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
|
||||
g
|
||||
};
|
||||
let spec = |g: &Node| g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
|
||||
let edit = |g: &mut Node, f: &dyn Fn(&mut Node)| {
|
||||
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
|
||||
// The center, drawn at half opacity.
|
||||
f(std::sync::Arc::make_mut(&mut children[2]));
|
||||
};
|
||||
for aligned in [false, true] {
|
||||
let g = flare(aligned);
|
||||
assert!(spec(&g).draws(&g), "aligned {aligned}");
|
||||
let mut moved = g.clone();
|
||||
edit(&mut moved, &|n| n.transform(Affine::translate((0.4, 0.0)), false));
|
||||
assert_eq!(spec(&moved).draws(&moved), aligned, "a fraction of a pixel, aligned {aligned}");
|
||||
let mut faded = g.clone();
|
||||
edit(&mut faded, &|n| n.opacity *= 0.8);
|
||||
assert!(!spec(&faded).draws(&faded), "opacity, aligned {aligned}");
|
||||
let mut shifted = g.clone();
|
||||
edit(&mut shifted, &|n| {
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
geom.start.x += 20.0;
|
||||
}
|
||||
});
|
||||
assert!(!spec(&shifted).draws(&shifted), "gradient placement, aligned {aligned}");
|
||||
let mut squashed = g.clone();
|
||||
edit(&mut squashed, &|n| {
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
geom.aspect *= 0.5;
|
||||
}
|
||||
});
|
||||
assert!(!spec(&squashed).draws(&squashed), "gradient shape, aligned {aligned}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An ellipse's size and shape are the same whichever axis its end point is on, and a narrow
|
||||
/// gradient made narrower, or turned, changes its shape by more than [`GEOMETRY_TOL`].
|
||||
#[test]
|
||||
fn an_ellipse_shape_tells_narrow_gradients_apart() {
|
||||
let geom = |end: (f64, f64), aspect: f64| GradientGeom { start: Point::new(1.0, 2.0), end: Point::new(end.0, end.1), aspect, focal: None };
|
||||
let of = ellipse_size_and_shape;
|
||||
let (size, shape) = of(&geom((11.0, 2.0), 0.5));
|
||||
// The same ellipse with its end point on the other axis.
|
||||
let (size2, shape2) = of(&geom((1.0, 7.0), 2.0));
|
||||
assert!((size - size2).abs() < 1e-12 && shape.iter().zip(shape2).all(|(a, b)| (a - b).abs() < 1e-12), "{shape:?} {shape2:?}");
|
||||
// A very narrow ellipse, given both ways, keeps its shape to within the tolerance.
|
||||
let (thin, thin2) = (of(&geom((11.0, 2.0), 1e-8)).1, of(&geom((1.0, 2.0 + 1e-7), 1e8)).1);
|
||||
assert!(thin.iter().zip(thin2).all(|(a, b)| (a - b).abs() < GEOMETRY_TOL), "{thin:?} {thin2:?}");
|
||||
let narrow = of(&geom((11.0, 2.0), 1e-4)).1;
|
||||
for other in [of(&geom((11.0, 2.0), 5e-5)).1, of(&geom((1.0, 12.0), 1e-4)).1] {
|
||||
assert!(narrow.iter().zip(other).any(|(a, b)| (a - b).abs() > 1e3 * GEOMETRY_TOL), "{narrow:?} {other:?}");
|
||||
}
|
||||
assert_eq!(of(&geom((1.0, 2.0), 1.0)), (0.0, [0.0; 3]));
|
||||
}
|
||||
|
||||
/// A flare scaled far down, in one direction or in all, anywhere on the canvas, still draws its
|
||||
/// settings, and a part's gradient whose shape was edited is still told apart; a flattened flare
|
||||
/// does not draw its settings.
|
||||
#[test]
|
||||
fn a_flare_scaled_far_down_still_draws_its_settings() {
|
||||
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0 });
|
||||
let flare_aligned = |xf: Affine, aligned: bool| {
|
||||
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
|
||||
let mut g = Node::group(NodeId(1), children.collect());
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
|
||||
g
|
||||
};
|
||||
let flare = |xf: Affine| flare_aligned(xf, false);
|
||||
// The center's gradient placement, to edit.
|
||||
let center_geom = |g: &mut Node, f: &dyn Fn(&mut GradientGeom)| {
|
||||
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = std::sync::Arc::make_mut(&mut children[2]).appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
f(geom);
|
||||
} else {
|
||||
panic!("the center has no gradient fill");
|
||||
}
|
||||
};
|
||||
let draws = |g: &Node| g.extras().flare.as_deref().is_some_and(|spec| spec.draws(g));
|
||||
assert!(draws(&flare(Affine::scale(1e-7))), "scaled to 0.00001%");
|
||||
assert!(draws(&flare(Affine::rotate(0.3) * Affine::scale_non_uniform(1.0, 1e-10))), "shrunk far on one axis");
|
||||
assert!(draws(&flare(Affine::translate((crate::MAX_COORD - 1000.0, 0.0)) * Affine::scale(0.5))), "near the edge of the canvas");
|
||||
assert!(draws(&flare(Affine::translate((1000.0, 0.0)) * Affine::scale(1e-5))), "scaled to 0.001% and moved away");
|
||||
assert!(!draws(&flare(Affine::scale_non_uniform(1.0, 0.0))), "flattened");
|
||||
// At that size a part whose gradient's shape was edited no longer draws the settings.
|
||||
let mut squashed = flare(Affine::scale(1e-6));
|
||||
assert!(draws(&squashed), "scaled to 0.0001%");
|
||||
center_geom(&mut squashed, &|geom| geom.aspect *= 0.5);
|
||||
assert!(!draws(&squashed), "gradient shape at 0.0001%");
|
||||
// A pixel-aligned part may sit up to a pixel off, but its gradient's shape may not change,
|
||||
// even when the ellipse keeps its size.
|
||||
let mut reshaped = flare_aligned(Affine::IDENTITY, true);
|
||||
assert!(draws(&reshaped), "aligned");
|
||||
center_geom(&mut reshaped, &|geom| {
|
||||
let a = geom.aspect;
|
||||
geom.aspect = a * 0.5;
|
||||
geom.end = geom.start + (geom.end - geom.start) * ((1.0 + a * a) / (1.0 + a * a / 4.0)).sqrt();
|
||||
});
|
||||
assert!(!draws(&reshaped), "gradient shape of the same size, aligned");
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ pub mod corners;
|
||||
pub mod decode;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
pub mod flare;
|
||||
pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
@@ -170,7 +171,7 @@ use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use stored_art::{StoredPlace, StoredRoot};
|
||||
pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number};
|
||||
pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
|
||||
@@ -271,6 +271,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
.as_deref()
|
||||
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
|
||||
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
|
||||
b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::<crate::flare::FlareSpec>() + json_bytes(&f.params));
|
||||
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
|
||||
if e.intertwine_tiers.capacity() > 0 {
|
||||
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
|
||||
|
||||
@@ -41,6 +41,9 @@ pub struct NodeExtras {
|
||||
/// Dimension object: the live measurement it draws; its ordinary group children hold its
|
||||
/// exportable appearance (Object › Dimensions, the Dimension tool).
|
||||
pub dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
/// Flare object: the settings its group was drawn with (the Flare tool); its ordinary group
|
||||
/// children hold its art.
|
||||
pub flare: Option<Box<crate::flare::FlareSpec>>,
|
||||
/// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates,
|
||||
/// filled non-zero) where this object is drawn over the group's other members.
|
||||
pub intertwine: Option<Box<PathData>>,
|
||||
@@ -100,6 +103,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
slice: None,
|
||||
perspective: None,
|
||||
dimension: None,
|
||||
flare: None,
|
||||
intertwine: None,
|
||||
intertwine_tiers: Vec::new(),
|
||||
live_paint_gaps: None,
|
||||
|
||||
@@ -520,6 +520,12 @@ impl Node {
|
||||
{
|
||||
dimension.transform(a);
|
||||
}
|
||||
// So does a flare's center and end point.
|
||||
if let Some(e) = self.extras_if_any()
|
||||
&& let Some(flare) = &mut e.flare
|
||||
{
|
||||
flare.transform(a);
|
||||
}
|
||||
// The path the objects are attached to, before it is transformed.
|
||||
let on_path_before = self.on_path_data().cloned();
|
||||
if !self.is_layer() {
|
||||
|
||||
@@ -45,6 +45,7 @@ impl Serialize for Node {
|
||||
is_default(&self.bbox_angle),
|
||||
e.perspective.is_none(),
|
||||
e.dimension.is_none(),
|
||||
e.flare.is_none(),
|
||||
e.intertwine.is_none(),
|
||||
e.intertwine_tiers.is_empty(),
|
||||
e.live_paint_gaps.is_none(),
|
||||
@@ -91,6 +92,7 @@ impl Serialize for Node {
|
||||
field!("bbox_angle", &self.bbox_angle);
|
||||
field!("perspective", &e.perspective);
|
||||
field!("dimension", &e.dimension);
|
||||
field!("flare", &e.flare);
|
||||
field!("intertwine", &e.intertwine);
|
||||
field!("intertwine_tiers", &e.intertwine_tiers);
|
||||
field!("live_paint_gaps", &e.live_paint_gaps);
|
||||
@@ -228,6 +230,8 @@ pub(super) struct NodeWire {
|
||||
#[serde(default)]
|
||||
dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
#[serde(default)]
|
||||
flare: Option<Box<crate::flare::FlareSpec>>,
|
||||
#[serde(default)]
|
||||
intertwine: Option<Box<PathData>>,
|
||||
#[serde(default, deserialize_with = "counted_list")]
|
||||
intertwine_tiers: Vec<PathData>,
|
||||
@@ -271,6 +275,7 @@ impl From<NodeWire> for Node {
|
||||
slice: w.slice,
|
||||
perspective: w.perspective,
|
||||
dimension: w.dimension,
|
||||
flare: w.flare,
|
||||
intertwine: w.intertwine,
|
||||
intertwine_tiers: w.intertwine_tiers,
|
||||
live_paint_gaps: w.live_paint_gaps,
|
||||
|
||||
@@ -94,11 +94,59 @@ fn a_very_long_expression_reads_as_nothing() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `x`, `X` and `×` multiply as `*` does (#8435), units and percentages included; a lowercase `x`
|
||||
/// right after a `p` stays the `px` unit.
|
||||
#[test]
|
||||
fn x_is_a_multiplication_sign() {
|
||||
let (mm, cm) = (72.0 / 25.4, 72.0 / 2.54);
|
||||
for (u, s, want) in [
|
||||
(Unit::Points, "10x2", 20.0),
|
||||
(Unit::Points, "10 x 2", 20.0),
|
||||
(Unit::Points, "10X2", 20.0),
|
||||
(Unit::Points, "10×2", 20.0),
|
||||
(Unit::Points, "10x-2", -20.0),
|
||||
(Unit::Points, "10/2x5", 25.0),
|
||||
(Unit::Points, "1+2x3", 7.0),
|
||||
(Unit::Millimeters, "2x3 mm", 6.0 * mm),
|
||||
(Unit::Points, "2x3mm", 6.0 * mm),
|
||||
(Unit::Points, "3mm x 2", 6.0 * mm),
|
||||
(Unit::Centimeters, "3cmx50%", 1.5 * cm),
|
||||
(Unit::Points, "2p x 2", 48.0),
|
||||
(Unit::Points, "10px", 10.0),
|
||||
(Unit::Points, "2px x 3", 6.0),
|
||||
(Unit::Points, "2pxx3", 6.0),
|
||||
(Unit::Millimeters, "4x3 px", 12.0),
|
||||
// Only a lowercase x after a p is the px suffix.
|
||||
(Unit::Points, "2pX3", 72.0),
|
||||
(Unit::Points, "2p×3", 72.0),
|
||||
// Text that used to be refused now reads as a product.
|
||||
(Unit::Points, "8.5x11 in", 93.5 * 72.0),
|
||||
(Unit::Points, "0x10", 0.0),
|
||||
] {
|
||||
let got = u.parse(s).unwrap_or_else(|| panic!("{u:?} can't read `{s}`"));
|
||||
assert!((got - want).abs() < 1e-9, "{u:?}: `{s}` → {got}, want {want}");
|
||||
}
|
||||
for s in ["x", "x2", "5x", "5 x x 2", "xx", "2px3"] {
|
||||
assert_eq!(Unit::Points.parse(s), None, "{s}");
|
||||
}
|
||||
assert_eq!(crate::parse_number("45x2"), Some(90.0));
|
||||
assert_eq!(crate::parse_number(" 45 X 2 "), Some(90.0));
|
||||
assert_eq!(crate::parse_number("45×2"), Some(90.0));
|
||||
assert_eq!(crate::parse_number("90x-1"), Some(-90.0));
|
||||
assert_eq!(crate::parse_number("x"), None);
|
||||
// Each sign counts toward the 128-sign limit as a `*` would.
|
||||
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(128))), Some(1.0));
|
||||
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(129))), None);
|
||||
assert_eq!(crate::parse_number(&format!("1{}", "×1".repeat(129))), None);
|
||||
assert_eq!(crate::arithmetic_signs("1+2x3X4×5*6/7-8"), 7);
|
||||
assert_eq!(crate::arithmetic_signs("2px x 3"), 1);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
|
||||
/// or as nothing and does not panic.
|
||||
#[test]
|
||||
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxinmcfyd-]{0,24}") {
|
||||
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxXinmcfyd×-]{0,24}") {
|
||||
for u in Unit::ALL {
|
||||
if let Some(v) = u.parse(&s) {
|
||||
prop_assert!(v.is_finite(), "{u:?}: `{s}` → {v}");
|
||||
|
||||
+51
-5
@@ -157,12 +157,17 @@ impl Unit {
|
||||
/// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A
|
||||
/// percentage on its own (`50%`) reads as nothing.
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs reads as nothing.
|
||||
/// `x`, `X` and `×` multiply as `*` does (`10x2` is 20, `2x3 mm` is 6 mm), except a lowercase
|
||||
/// `x` right after a `p`, which is the `px` suffix (`2px x 3` is 6 px, and `2px3` reads as
|
||||
/// nothing; write `2p x 3` for picas). `X` and `×` after a `p` multiply (`2pX3` is 6 picas).
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs ([`arithmetic_signs`], a multiplication sign counted
|
||||
/// as `*`) reads as nothing.
|
||||
pub fn parse(self, s: &str) -> Option<f64> {
|
||||
if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS {
|
||||
if arithmetic_signs(s) > MAX_MEASURE_OPERATORS {
|
||||
return None;
|
||||
}
|
||||
parse_measure(s, self).filter(|v| v.is_finite())
|
||||
parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
@@ -215,6 +220,46 @@ impl Unit {
|
||||
/// The most `+ - * /` signs [`Unit::parse`] reads in one text.
|
||||
const MAX_MEASURE_OPERATORS: usize = 128;
|
||||
|
||||
/// The number of `+ - * /` signs in `s`, each multiplication sign typed as `x`, `X` or `×`
|
||||
/// ([`Unit::parse`]) counted as a `*`.
|
||||
pub fn arithmetic_signs(s: &str) -> usize {
|
||||
let mut prev = None;
|
||||
s.chars()
|
||||
.filter(|&c| {
|
||||
let sign = matches!(c, '+' | '-' | '*' | '/') || is_times(c, prev);
|
||||
prev = Some(c);
|
||||
sign
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Is `c`, after `prev`, a multiplication sign typed as `x`, `X` or `×`? A lowercase `x` right
|
||||
/// after a `p` is the `px` suffix (`2px x 3`), also where a number follows it (`2px3`).
|
||||
fn is_times(c: char, prev: Option<char>) -> bool {
|
||||
matches!(c, 'X' | '×') || (c == 'x' && prev != Some('p'))
|
||||
}
|
||||
|
||||
/// `s` with each multiplication sign ([`is_times`]) written as `*` (`10 x 2` is `10 * 2`); text
|
||||
/// without one is not copied.
|
||||
fn times_as_asterisks(s: &str) -> std::borrow::Cow<'_, str> {
|
||||
let mut prev = None;
|
||||
let any = s.chars().any(|c| {
|
||||
let times = is_times(c, prev);
|
||||
prev = Some(c);
|
||||
times
|
||||
});
|
||||
if !any {
|
||||
return s.into();
|
||||
}
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut prev = None;
|
||||
for c in s.chars() {
|
||||
out.push(if is_times(c, prev) { '*' } else { c });
|
||||
prev = Some(c);
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
|
||||
fn parse_measure(s: &str, default: Unit) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
// Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2").
|
||||
@@ -348,9 +393,10 @@ pub fn finite_in_every_unit(pt: f64) -> bool {
|
||||
}
|
||||
|
||||
/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as
|
||||
/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing.
|
||||
/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as
|
||||
/// nothing.
|
||||
pub fn parse_number(s: &str) -> Option<f64> {
|
||||
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/".contains(c)) {
|
||||
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) {
|
||||
return None;
|
||||
}
|
||||
// A leading `+` is a sign (`+5`), as a plain number read it.
|
||||
|
||||
@@ -32,6 +32,7 @@ pub mod expand;
|
||||
pub(crate) mod fileinfo;
|
||||
pub mod fileio;
|
||||
pub mod findfiles;
|
||||
pub mod flare;
|
||||
pub mod flatten;
|
||||
pub mod fontfiles;
|
||||
mod fonts;
|
||||
@@ -885,7 +886,8 @@ pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]).
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps.
|
||||
pub use attributes::RECENT_URLS;
|
||||
pub use overprint::AttributesInfo;
|
||||
|
||||
/// Object → Flatten Transparency settings (`object.flattenTransparency`).
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
|
||||
//! circles, replacing the circles or added above them.
|
||||
//! circles, or three or more each joined the same way to the others within reach and united where
|
||||
//! the bridges connect, replacing the circles or added above them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
@@ -20,6 +21,12 @@ const LABEL: &str = "Smooth Bridge";
|
||||
/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range.
|
||||
const RADIUS: f64 = 100.0;
|
||||
const RADII: (f64, f64) = (1.0, 1000.0);
|
||||
/// The gap (pt) added to the smaller circle's radius to give the arcs' radius: the range.
|
||||
const GAPS: (f64, f64) = (0.0, 1000.0);
|
||||
/// How far apart (pt) the outlines of two of three or more circles may be for a bridge between
|
||||
/// them: by default, and the range.
|
||||
const REACH: f64 = 10.0;
|
||||
const REACHES: (f64, f64) = (0.0, 10000.0);
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -27,16 +34,33 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Smooth Bridge",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}",
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
|
||||
let percent = given(p, "radius", Some(RADII), C)?;
|
||||
let gap = given(p, "gap", Some(GAPS), C)?;
|
||||
let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH);
|
||||
if percent.is_some() && gap.is_some() {
|
||||
// As the parameter check words it (`EXCLUSIVE_KEYS`), for a caller that skips that check.
|
||||
let (key, other) = ("radius", "gap");
|
||||
return Err(bad(C, format!("give `{key}` or `{other}`, not both")));
|
||||
}
|
||||
let arc = match gap {
|
||||
Some(gap) => pt::ArcRadius::Gap(gap),
|
||||
None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0),
|
||||
};
|
||||
let keep = switch_or(p, "keepOriginals", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
// An id given twice is one circle.
|
||||
roots.sort_unstable();
|
||||
roots.dedup();
|
||||
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
|
||||
return Err(bad(C, "select at most 2000 circles to bridge"));
|
||||
}
|
||||
let circles: Vec<(NodeId, pt::Circle)> = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
@@ -48,48 +72,93 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else {
|
||||
return Err(bad(C, "select two circles to bridge"));
|
||||
};
|
||||
let (below, above) = (*below, *above);
|
||||
let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0);
|
||||
let outline = match at(percent) {
|
||||
Ok(sp) => PathData::single(sp),
|
||||
Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")),
|
||||
// A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed.
|
||||
Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => {
|
||||
return Err(bad(C, "the circles are too far apart for this radius: raise the radius"));
|
||||
if circles.len() != roots.len() || circles.len() < 2 {
|
||||
return Err(bad(C, "select two or more circles to bridge"));
|
||||
}
|
||||
let only: Vec<pt::Circle> = circles.iter().map(|(_, c)| *c).collect();
|
||||
// Each shape: the circles it joins, in paint order, and its outline.
|
||||
let (shapes, alone): (Vec<(Vec<NodeId>, PathData)>, Vec<NodeId>) = match only.as_slice() {
|
||||
[a, b] => match pt::smooth_bridge(*a, *b, arc.between(*a, *b)) {
|
||||
Ok(sp) => (vec![(roots_of(&circles, &[0, 1]), PathData::single(sp))], vec![]),
|
||||
Err(e) => return Err(refusal(e, arc, |largest| pt::smooth_bridge(*a, *b, largest.between(*a, *b)).is_ok())),
|
||||
},
|
||||
_ => {
|
||||
let made = pt::bridge_many(&only, arc, reach).map_err(|e| match e {
|
||||
pt::ManyError::TooManyCircles => bad(C, "select at most 2000 circles to bridge"),
|
||||
pt::ManyError::TooManyBridges => bad(C, "that makes too many bridges (at most 8000): lower the reach"),
|
||||
pt::ManyError::NoneInReach => bad(C, "no two circles are within reach: raise the reach"),
|
||||
pt::ManyError::TooComplex => bad(C, "the bridged circles are too complex to unite"),
|
||||
// Under the many-circle rules: a pair the largest radius or gap bridges on its own
|
||||
// can still have a neck too thin to unite among the others.
|
||||
pt::ManyError::Pair(_, _, e) => refusal(e, arc, |largest| pt::bridges_any(&only, largest, reach)),
|
||||
pt::ManyError::Bad => bad(C, "select two or more circles to bridge"),
|
||||
})?;
|
||||
let shapes = made.joined.into_iter().map(|j| (roots_of(&circles, &j.members), j.outline)).collect();
|
||||
(shapes, roots_of(&circles, &made.alone))
|
||||
}
|
||||
Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")),
|
||||
Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")),
|
||||
};
|
||||
let id = s.edit(LABEL, |d, sel| {
|
||||
let id = if keep {
|
||||
// A copy of the upper circle (its appearance) with the outline as its path, right above
|
||||
// it; the circles stay as they are, live shapes included.
|
||||
// Fresh ids throughout, its opacity mask's art included.
|
||||
let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?;
|
||||
let mut n = d.reid(&upper);
|
||||
if let NodeKind::Path { path, live, .. } = &mut n.kind {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
let made = s.edit(LABEL, |d, sel| {
|
||||
let mut made = Vec::with_capacity(shapes.len());
|
||||
if keep {
|
||||
// A copy of each shape's topmost circle (its appearance) with the outline as its path,
|
||||
// right above it; the circles stay as they are, live shapes included. Fresh ids
|
||||
// throughout, an opacity mask's art included.
|
||||
let tops: Vec<NodeId> = shapes.iter().filter_map(|(members, _)| members.last().copied()).collect();
|
||||
let mut beside = Beside::above(d, &tops);
|
||||
for ((_, outline), top) in shapes.into_iter().zip(tops) {
|
||||
let upper = d.node(top).cloned().ok_or(EngineError::NoNode(top))?;
|
||||
let mut n = d.reid(&upper);
|
||||
if let NodeKind::Path { path, live, .. } = &mut n.kind {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
made.push(n.id);
|
||||
beside.put(d, top, vec![n])?;
|
||||
}
|
||||
let id = n.id;
|
||||
let mut beside = Beside::above(d, &[above]);
|
||||
beside.put(d, above, vec![n])?;
|
||||
beside.finish(d)?;
|
||||
id
|
||||
} else {
|
||||
// The upper circle becomes the outline (a plain path now) and the lower one goes.
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
// Each shape's topmost circle becomes its outline (a plain path now) and the others go.
|
||||
let mut gone = vec![];
|
||||
for (members, outline) in shapes {
|
||||
let Some((&top, rest)) = members.split_last() else { continue };
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(top).map(|n| &mut n.kind) {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
made.push(top);
|
||||
gone.extend_from_slice(rest);
|
||||
}
|
||||
remove_each(d, &[below])?;
|
||||
above
|
||||
};
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
remove_each(d, &gone)?;
|
||||
}
|
||||
sel.set(made.iter().chain(&alone).copied());
|
||||
Ok(made)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
let mut out = json!({ "ids": made.iter().map(|id| id.0).collect::<Vec<_>>(), "alone": alone.iter().map(|id| id.0).collect::<Vec<_>>() });
|
||||
if let ([id], 2) = (made.as_slice(), only.len()) {
|
||||
out["id"] = json!(id.0);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
|
||||
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
|
||||
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
|
||||
}
|
||||
|
||||
/// The error for circles that arcs of `arc` can't bridge. A larger radius or gap bridges circles a
|
||||
/// smaller one cannot, so it suggests one only when `bridges` says the largest allowed would.
|
||||
fn refusal(e: pt::BridgeError, arc: pt::ArcRadius, bridges: impl FnOnce(pt::ArcRadius) -> bool) -> EngineError {
|
||||
let largest = match arc {
|
||||
pt::ArcRadius::Share(_) => pt::ArcRadius::Share(RADII.1 / 100.0),
|
||||
pt::ArcRadius::Gap(_) => pt::ArcRadius::Gap(GAPS.1),
|
||||
};
|
||||
let would = e == pt::BridgeError::TooFar && bridges(largest);
|
||||
match (e, arc, would) {
|
||||
(pt::BridgeError::Inside, ..) => bad(C, "one circle is inside the other"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), true) => bad(C, "the circles are too far apart for this radius: raise the radius"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), false) => bad(C, "the circles are too far apart for this radius"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), true) => bad(C, "the circles are too far apart for this gap: raise the gap"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), false) => bad(C, "the circles are too far apart for this gap"),
|
||||
(pt::BridgeError::Bad, ..) => bad(C, "select two or more circles to bridge"),
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
|
||||
//! and what it refuses.
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius or
|
||||
//! gap, many circles joined to their neighbors within reach, and what it refuses.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
@@ -46,6 +46,8 @@ fn two_circles_become_one_outline_in_the_upper_ones_place() {
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute(BRIDGE, &json!({})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0));
|
||||
assert_eq!(r["ids"], json!([b.0]), "the same result fields as for more circles");
|
||||
assert_eq!(r["alone"], json!([]));
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") };
|
||||
@@ -158,9 +160,11 @@ fn far_apart_nested_and_other_objects_are_refused() {
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other"));
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}");
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, square.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two or more circles to bridge"), "{ids}");
|
||||
}
|
||||
// Three circles: each two within reach are bridged, and one inside another is refused there too.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0, inner.0]})).contains("one circle is inside the other"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number"));
|
||||
@@ -169,6 +173,174 @@ fn far_apart_nested_and_other_objects_are_refused() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100).
|
||||
fn grid(s: &mut Session) -> Vec<NodeId> {
|
||||
(0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect()
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_of_circles_joins_each_to_its_neighbors_in_one_shape() {
|
||||
let mut s = session();
|
||||
let g = grid(&mut s);
|
||||
select(&mut s, &g);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// Reach 5: the side neighbors (4 apart) are bridged, the diagonal ones (about 13.9 apart) not.
|
||||
let r = s.execute(BRIDGE, &json!({"gap": 4, "reach": 5})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [g[8]], "one shape, in the topmost circle's place");
|
||||
assert_eq!(ids(&r["alone"]), []);
|
||||
assert_eq!(top_level(&s), [g[8]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g[8]]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
// Its outline and a hole in each square of four circles, which no diagonal bridge fills.
|
||||
let outline = path(&s, g[8]);
|
||||
assert_eq!(outline.subpaths.len(), 5, "{}", outline.subpaths.len());
|
||||
let inside = |p: &vectorcraft_geom::PathData, x: f64, y: f64| p.to_bezpath().winding(vectorcraft_geom::kurbo::Point::new(x, y)) != 0;
|
||||
assert!(inside(&outline, 112.0, 100.0) && inside(&outline, 100.0, 112.0) && !inside(&outline, 112.0, 112.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(top_level(&s), g);
|
||||
// Reach 15 takes in the diagonal neighbors, whose bridges fill the middle of each square.
|
||||
select(&mut s, &g);
|
||||
s.execute(BRIDGE, &json!({"gap": 4, "reach": 15})).unwrap();
|
||||
let outline = path(&s, g[8]);
|
||||
assert_eq!(outline.subpaths.len(), 1);
|
||||
assert!(inside(&outline, 112.0, 112.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_with_no_neighbor_in_reach_stays_as_it_is() {
|
||||
let mut s = session();
|
||||
let g = grid(&mut s);
|
||||
let far = circle(&mut s, 300.0, 250.0, 10.0);
|
||||
let pair = [circle(&mut s, 300.0, 40.0, 8.0), circle(&mut s, 320.0, 40.0, 8.0)];
|
||||
let mut all = g.clone();
|
||||
all.extend([far, pair[0], pair[1]]);
|
||||
let r = s.execute(BRIDGE, &json!({"ids": all.iter().map(|i| i.0).collect::<Vec<_>>(), "reach": 5})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [g[8], pair[1]]);
|
||||
assert_eq!(ids(&r["alone"]), [far]);
|
||||
assert_eq!(top_level(&s), [g[8], far, pair[1]]);
|
||||
assert!(matches!(&s.doc().unwrap().doc.node(far).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "untouched");
|
||||
let mut selected = s.doc().unwrap().selection.objects.to_vec();
|
||||
selected.sort();
|
||||
let mut want = vec![g[8], pair[1], far];
|
||||
want.sort();
|
||||
assert_eq!(selected, want, "the shapes and the circle left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_originals_adds_each_shape_above_its_topmost_circle() {
|
||||
let mut s = session();
|
||||
let row: Vec<NodeId> = (0..3).map(|i| circle(&mut s, 100.0 + 25.0 * i as f64, 100.0, 10.0)).collect();
|
||||
let other = [circle(&mut s, 100.0, 200.0, 10.0), circle(&mut s, 122.0, 200.0, 10.0)];
|
||||
s.execute("paint.setFill", &json!({"ids": [row[2].0], "color": "#00ff00"})).unwrap();
|
||||
let all: Vec<u64> = row.iter().chain(&other).map(|i| i.0).collect();
|
||||
let r = s.execute(BRIDGE, &json!({"ids": all, "keepOriginals": true})).unwrap();
|
||||
let made = ids(&r["ids"]);
|
||||
assert_eq!(made.len(), 2);
|
||||
assert_eq!(top_level(&s), [row[0], row[1], row[2], made[0], other[0], other[1], made[1]]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(made[0]).unwrap().appearance, d.node(row[2]).unwrap().appearance, "painted as the topmost circle");
|
||||
let b = d.node(made[0]).unwrap().path_data().unwrap().bounds().unwrap();
|
||||
assert!((b.x0 - 90.0).abs() < 1e-2 && (b.x1 - 160.0).abs() < 1e-2, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gap_form_gives_arcs_the_smaller_radius_plus_the_gap() {
|
||||
let area_with = |p: Value| {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 124.0, 100.0, 10.0);
|
||||
let mut p = p;
|
||||
p["ids"] = json!([a.0, b.0]);
|
||||
let id = NodeId(s.execute(BRIDGE, &p).unwrap()["id"].as_u64().unwrap());
|
||||
area(&s, id)
|
||||
};
|
||||
// Radius 10 plus a gap of 4 is 140% of 10.
|
||||
let (gap, percent) = (area_with(json!({"gap": 4})), area_with(json!({"radius": 140})));
|
||||
assert!((gap - percent).abs() < 1e-9, "{gap} {percent}");
|
||||
assert!(area_with(json!({"gap": 0})) < gap && gap < area_with(json!({"gap": 20})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_circle_and_gap_refusals() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 50.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 250.0, 100.0, 10.0);
|
||||
let c = circle(&mut s, 330.0, 100.0, 10.0);
|
||||
let far = circle(&mut s, 380.0, 100.0, 10.0);
|
||||
let before = top_level(&s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "radius": 100, "gap": 4})).contains("give `radius` or `gap`, not both"));
|
||||
// Centers 200 apart: a gap of 0 does not bridge them, the largest (1000 pt) does. With centers
|
||||
// 330 apart even that one closes the neck: it stays open only below 2 × √(10² + 2 × 10 × 1010)
|
||||
// ≈ 285.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 0})).ends_with("too far apart for this gap: raise the gap"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "gap": 0})).ends_with("the circles are too far apart for this gap"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 5})).contains("no two circles are within reach: raise the reach"));
|
||||
// b and c are 60 apart: within a reach of 100, but too far for the default radius.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 100})).ends_with("too far apart for this radius: raise the radius"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": -1})).contains("`reach` must be from 0 to 10000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 1001})).contains("`gap` must be from 0 to 1000"));
|
||||
assert_eq!(top_level(&s), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_larger_radius_is_suggested_only_when_it_bridges_among_the_other_circles() {
|
||||
let mut s = session();
|
||||
// Centers 91.65 apart: the largest radius (1000%, 100 pt) bridges these two on their own, but
|
||||
// with a neck about 0.0007 pt wide, too thin to unite among three or more circles.
|
||||
let a = circle(&mut s, 20.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 111.65, 100.0, 10.0);
|
||||
let far = circle(&mut s, 380.0, 100.0, 10.0);
|
||||
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": 1000})).is_ok());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).ends_with("too far apart for this radius: raise the radius"));
|
||||
for radius in [100, 1000] {
|
||||
let e = err(&mut s, json!({"ids": [a.0, b.0, far.0], "radius": radius, "reach": 100}));
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_circles_or_bridges_are_refused() {
|
||||
let mut s = session();
|
||||
// 130 overlapping circles in a row: 8,385 pairs within reach.
|
||||
let row: Vec<u64> = (0..130).map(|i| circle(&mut s, 20.0 + i as f64 * 0.2, 100.0, 10.0).0).collect();
|
||||
assert!(err(&mut s, json!({ "ids": row })).contains("that makes too many bridges (at most 8000): lower the reach"));
|
||||
let many: Vec<u64> = (0..2001).map(|i| circle(&mut s, 20.0 + (i % 50) as f64 * 7.0, 150.0 + (i / 50) as f64 * 3.0, 1.0).0).collect();
|
||||
assert!(err(&mut s, json!({ "ids": many })).contains("select at most 2000 circles to bridge"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_given_twice_is_one_circle() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
let r = s.execute(BRIDGE, &json!({"ids": [a.0, a.0, b.0]})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0), "two circles, bridged");
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() {
|
||||
let mut s = session();
|
||||
// Radius 3: arcs of 3 pt (100%) join a and b (2 apart) but close before reaching c (6 from b,
|
||||
// within the default reach of 10).
|
||||
let (a, b, c) = (circle(&mut s, 100.0, 100.0, 3.0), circle(&mut s, 108.0, 100.0, 3.0), circle(&mut s, 120.0, 100.0, 3.0));
|
||||
let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [b]);
|
||||
assert_eq!(ids(&r["alone"]), [c]);
|
||||
assert_eq!(top_level(&s), [b, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let mut s = session();
|
||||
@@ -176,9 +348,9 @@ fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
@@ -22,8 +22,8 @@ const SELECTION_SIZE: &str = "addon.units.selectionSize";
|
||||
const SHOWN_CHARS: usize = 64;
|
||||
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
|
||||
const MAX_TEXT_LEN: usize = 1024;
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
|
||||
/// level of recursion per sign.
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`, a multiplication sign
|
||||
/// counted as a `*`: [`Unit::parse`] takes one level of recursion per sign.
|
||||
const MAX_OPERATORS: usize = 128;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
@@ -88,9 +88,9 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
|
||||
/// signs?
|
||||
/// signs, a multiplication sign typed as `x`, `X` or `×` counted as a `*` ([`arithmetic_signs`])?
|
||||
fn readable(s: &str) -> bool {
|
||||
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
|
||||
s.len() <= MAX_TEXT_LEN && arithmetic_signs(s) <= MAX_OPERATORS
|
||||
}
|
||||
|
||||
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
|
||||
|
||||
@@ -76,6 +76,12 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
// x, X and × multiply as * does, and each counts toward the 128 signs.
|
||||
assert!(near(pt(&mut s, json!({"value": "2x3 mm"})), 6.0 * 72.0 / 25.4));
|
||||
assert!(near(pt(&mut s, json!({"value": "10X2"})), 20.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "0,5×4 in"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "x1".repeat(128))})), 1.0));
|
||||
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -12,8 +12,9 @@ use super::overprint::{AttributesInfo, apply_overprint, edit_counted, overprint_
|
||||
use super::path::paths_in;
|
||||
use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, str_param, targets};
|
||||
|
||||
/// How many URLs the Attributes panel's recent list keeps.
|
||||
const RECENT_URLS: usize = 10;
|
||||
/// How many URLs the Attributes panel's recent list keeps: the most its Panel Options lets the
|
||||
/// URL menu list.
|
||||
pub const RECENT_URLS: usize = 30;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -22,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
|
||||
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info, newest first, at most 30) → {changed: objects}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
|
||||
@@ -12,7 +12,8 @@ use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{
|
||||
self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation,
|
||||
self as brush, ArtBrush, ArtScale, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter,
|
||||
Variation,
|
||||
};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
@@ -180,6 +181,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
|
||||
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -233,6 +235,54 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length).
|
||||
fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush {
|
||||
Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Art(ArtBrush {
|
||||
art,
|
||||
scale: ArtScale::BetweenGuides { start, end },
|
||||
colorization: Colorization::Tints,
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Arrows: original art brushes whose stems stretch while their heads keep their proportions.
|
||||
fn arrows() -> BrushLibrary {
|
||||
let shaft = || black(shapes::rectangle(Rect::new(0.0, -1.0, 82.0, 1.0)));
|
||||
let head = || black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (82.0, 0.0)]));
|
||||
let solid = group(vec![shaft(), head()]);
|
||||
let outline = group(vec![shaft(), black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (78.0, 4.0), (91.0, 0.0), (78.0, -4.0)]))]);
|
||||
let double = group(vec![
|
||||
black(shapes::rectangle(Rect::new(18.0, -1.0, 82.0, 1.0))),
|
||||
head(),
|
||||
black(polygon(&[(24.0, -7.0), (0.0, 0.0), (24.0, 7.0), (18.0, 0.0)])),
|
||||
]);
|
||||
let chevrons = group(vec![shaft(), head(), black(polygon(&[(53.0, -5.0), (66.0, 0.0), (53.0, 5.0), (56.0, 0.0)]))]);
|
||||
let dashed = group(
|
||||
(0..5)
|
||||
.map(|i| {
|
||||
let x = f64::from(i) * 16.0;
|
||||
black(shapes::rectangle(Rect::new(x, -1.0, x + 10.0, 1.0)))
|
||||
})
|
||||
.chain(std::iter::once(head()))
|
||||
.collect(),
|
||||
);
|
||||
built(
|
||||
"Arrows",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
arrow_art("Solid Arrow", solid, 0.0, 0.76),
|
||||
arrow_art("Open Arrow", outline, 0.0, 0.76),
|
||||
arrow_art("Double Arrow", double, 0.24, 0.76),
|
||||
// The second chevron starts at 53 pt, so only the shaft before it stretches.
|
||||
arrow_art("Chevron Arrow", chevrons, 0.0, 0.53),
|
||||
arrow_art("Dashed Arrow", dashed, 0.0, 0.76),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's
|
||||
/// own pattern, Pinstripes.
|
||||
fn art_ribbons() -> BrushLibrary {
|
||||
|
||||
+10
-144
@@ -55,7 +55,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
super::flare::flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.editFlare",
|
||||
"Edit Flare",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?: flares (default: the selected flares), cx?, cy? (the center, where it is drawn now), x2?, y2? (the rings' end point, where it is drawn now; else pathLength at direction from the center, both where it is drawn now, when either is given; else where it was), diameter?, opacity?, brightness?, growth?, fuzziness?, rays?, longest?, rayFuzziness?, rotation? (deg, turns the rays clockwise), pathLength?, rings?, largest?, direction? (as shape.flare: what is left out stays as it was)} draws each flare again in its place, moved, scaled, rotated, reflected or sheared as it has been since it was drawn, as one undo step (none when nothing changes); a flare whose parts were edited, or that is locked or hidden, is not one → {ids}",
|
||||
has_doc,
|
||||
super::flare::edit_flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.circleThroughPoints",
|
||||
@@ -515,149 +524,6 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot))
|
||||
}
|
||||
|
||||
/// Flare tool: a lens flare built from radial-gradient paths in Screen mode — a bright centre, a halo
|
||||
/// ring, rays of varying length and rings along the path to the end point.
|
||||
fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_color::{BlendMode, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let c = Point::new(f64_req(p, "cx", "shape.flare")?, f64_req(p, "cy", "shape.flare")?);
|
||||
let numbers = [
|
||||
"diameter",
|
||||
"opacity",
|
||||
"brightness",
|
||||
"growth",
|
||||
"fuzziness",
|
||||
"rays",
|
||||
"longest",
|
||||
"rayFuzziness",
|
||||
"rotation",
|
||||
"rings",
|
||||
"largest",
|
||||
"x2",
|
||||
"y2",
|
||||
"direction",
|
||||
"pathLength",
|
||||
"seed",
|
||||
"ringSeed",
|
||||
];
|
||||
check_numbers(p, &numbers, "shape.flare")?;
|
||||
let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0);
|
||||
let r = (f64_or(p, "diameter", 100.0) / 2.0).max(0.5);
|
||||
let opacity = pct("opacity", 50.0).min(1.0) as f32;
|
||||
let brightness = pct("brightness", 30.0).min(1.0) as f32;
|
||||
let growth = pct("growth", 20.0);
|
||||
let fuzz = pct("fuzziness", 50.0).min(1.0);
|
||||
let rays = p.get("rays").and_then(Value::as_u64).unwrap_or(15).min(50) as usize;
|
||||
let longest = pct("longest", 300.0);
|
||||
let ray_fuzz = pct("rayFuzziness", 100.0).min(1.0);
|
||||
let ray_turn = f64_or(p, "rotation", 0.0).to_radians();
|
||||
let rings = p.get("rings").and_then(Value::as_u64).unwrap_or(10).min(50) as usize;
|
||||
let largest = pct("largest", 50.0);
|
||||
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
|
||||
(Some(x), Some(y)) => Point::new(x, y),
|
||||
_ => {
|
||||
let a = f64_or(p, "direction", 45.0).to_radians();
|
||||
c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0)
|
||||
}
|
||||
};
|
||||
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
|
||||
// along the path from a sequence of its own; their count and sizes and the other parts stay.
|
||||
let seed_of = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
};
|
||||
let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
|
||||
let ring_seed = match seed_of("ringSeed")? {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let mut ring_at = ring_seed.map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
g.geom = Some(GradientGeom { start: centre, end: centre + vectorcraft_geom::Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
|
||||
let mut parts: Vec<(&str, PathData, Paint, f32)> = vec![];
|
||||
// Halo: a soft ring just outside the centre.
|
||||
let halo_r = r * (1.0 + growth) * 1.6;
|
||||
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
|
||||
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
|
||||
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
|
||||
// `rotation` turns them clockwise about the center.
|
||||
if rays > 0 {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
let mut reach: f64 = 0.0;
|
||||
for i in 0..rays {
|
||||
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
|
||||
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
|
||||
reach = reach.max(len);
|
||||
let w = r * 0.035;
|
||||
let dir = vectorcraft_geom::Vec2::new(a.cos(), a.sin());
|
||||
let n = vectorcraft_geom::Vec2::new(-dir.y, dir.x) * w;
|
||||
bp.move_to(c + n);
|
||||
bp.line_to(c + dir * len);
|
||||
bp.line_to(c - n);
|
||||
bp.line_to(c - dir * (w * 4.0));
|
||||
bp.close_path();
|
||||
}
|
||||
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
|
||||
}
|
||||
// Centre: bright core fading to transparent.
|
||||
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
|
||||
// Rings along the path to the end point (Largest = % of the average ring size).
|
||||
for _ in 0..rings {
|
||||
let t = rnd();
|
||||
let t = ring_at.as_mut().map_or(t, |next| next());
|
||||
let at = c + (end - c) * t;
|
||||
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
|
||||
let solid = rnd() < 0.5;
|
||||
let stops = if solid {
|
||||
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
|
||||
} else {
|
||||
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
|
||||
};
|
||||
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Flare", |d, sel| {
|
||||
let children = parts
|
||||
.into_iter()
|
||||
.map(|(name, pd, paint, op)| {
|
||||
let mut n = Node::path(d.alloc_id(), pd, Appearance::basic(paint, Paint::None, 0.0));
|
||||
n.name = Some(name.into());
|
||||
n.blend = BlendMode::Screen;
|
||||
n.opacity = op;
|
||||
super::object::align_new_object(d, &mut n);
|
||||
std::sync::Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = Some("Flare".into());
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Point::new(f64_req(p, "x1", "shape.line")?, f64_req(p, "y1", "shape.line")?);
|
||||
let b = Point::new(f64_req(p, "x2", "shape.line")?, f64_req(p, "y2", "shape.line")?);
|
||||
|
||||
@@ -182,7 +182,7 @@ impl Expandable {
|
||||
n.walk(&mut |c| {
|
||||
let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
e.text |= matches!(c.kind, NodeKind::Text(_));
|
||||
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. });
|
||||
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some();
|
||||
e.effects |= !c.appearance.effects.is_empty();
|
||||
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
|
||||
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
|
||||
@@ -503,10 +503,14 @@ fn end_dimension_links(s: &mut Session, ended: &mut Vec<EndedLink>) -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Makes the live shapes in `n` plain paths, and the flares plain groups of their parts.
|
||||
fn drop_live(n: &mut Node) {
|
||||
if let NodeKind::Path { live, .. } = &mut n.kind {
|
||||
*live = None;
|
||||
}
|
||||
if n.extras().flare.is_some() {
|
||||
n.extras_mut().flare = None;
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
drop_live(Arc::make_mut(c));
|
||||
|
||||
@@ -297,7 +297,17 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
// Never a half-written file: see [`write_atomic`].
|
||||
write_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the
|
||||
/// file was put in place ([`vectorcraft_format::write_atomic_with`]), otherwise the path and the reason.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
if error.get_ref().is_some_and(|e| e.is::<vectorcraft_doc::cancel::Cancelled>()) {
|
||||
return EngineError::Cancelled;
|
||||
}
|
||||
EngineError::Other(format!("{path}: {error}"))
|
||||
}
|
||||
|
||||
/// [`write_file`] with what `fill` writes into the file (a save streamed into it).
|
||||
@@ -305,7 +315,7 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
|
||||
@@ -324,8 +334,10 @@ pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::W
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
let reason = format!("{path}: {error}");
|
||||
if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) }
|
||||
if !vectorcraft_format::read_only_location(&error) {
|
||||
return write_error(path, error);
|
||||
}
|
||||
EngineError::ReadOnlyLocation(format!("{path}: {error}"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -962,7 +962,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
|
||||
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
|
||||
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
|
||||
/// clipping path ([`image_clip`]).
|
||||
/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes
|
||||
/// it) is read with that path.
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
@@ -1139,13 +1140,15 @@ pub fn texture_image(bytes: &[u8]) -> Result<String> {
|
||||
texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture"))
|
||||
}
|
||||
|
||||
/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed.
|
||||
/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a
|
||||
/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]).
|
||||
fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result<RasterImage> {
|
||||
if width == 0 || height == 0 {
|
||||
return Err(err("the image is empty"));
|
||||
}
|
||||
let blob = ImageBlob::new(mime, bytes);
|
||||
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None })
|
||||
let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd));
|
||||
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip })
|
||||
}
|
||||
|
||||
/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from
|
||||
|
||||
@@ -69,7 +69,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
name: "bleed",
|
||||
ty: "object",
|
||||
default: "null",
|
||||
description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning",
|
||||
description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so do objects that reach the trim edge on a side with a bleed but stop short of the bleed edge",
|
||||
},
|
||||
FormatOption {
|
||||
name: "output",
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
@@ -295,6 +295,8 @@ pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Op
|
||||
o.insert("preserveEditing".into(), json!(false));
|
||||
}
|
||||
let (bytes, mut notes) = encode(cmd, &art, &q)?;
|
||||
// The page is the art's bounds, so every object at its edge would count.
|
||||
notes.retain(|n| !is_short_of_bleed(&n.text));
|
||||
if left_out {
|
||||
notes.push(Note::setting(EDITING_NEEDS_THE_ARTBOARDS));
|
||||
}
|
||||
@@ -317,6 +319,191 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
|
||||
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
|
||||
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
|
||||
|
||||
/// How far, in points, an object's edge may sit inside the trim edge, or short of the bleed edge,
|
||||
/// and still count as reaching it in [`short_of_bleed`]. A side whose bleed is no larger has none.
|
||||
const EDGE_TOLERANCE: f64 = 0.5;
|
||||
|
||||
/// How many objects of `doc` reach the trim edge (an artboard's edge, within [`EDGE_TOLERANCE`]) of
|
||||
/// one of `artboards` (`None`: all of them) on a side where `bleed` (`[top, bottom, left, right]`
|
||||
/// in points) is set, but end before that side's bleed edge. The objects are the members of the
|
||||
/// visible layers and sublayers, a group counted as one, measured as [`drawn_bounds`] measures them
|
||||
/// and cut to the clipping paths of the layers they are on. Template layers, layers with an opacity
|
||||
/// mask and, unless `non_printing`, layers whose Print option is off are left out. A side whose
|
||||
/// bleed is [`EDGE_TOLERANCE`] or less counts as having none. Each object counts once.
|
||||
pub fn short_of_bleed(doc: &Document, bleed: [f64; 4], artboards: Option<&[usize]>, non_printing: bool) -> usize {
|
||||
let bleed = bleed.map(|b| if b.is_finite() && b > EDGE_TOLERANCE { b } else { 0.0 });
|
||||
if bleed.iter().all(|b| *b == 0.0) {
|
||||
return 0;
|
||||
}
|
||||
let trims: Vec<vectorcraft_geom::Rect> = match artboards {
|
||||
Some(picked) => picked.iter().filter_map(|&i| doc.artboards.get(i)).map(|a| a.rect).collect(),
|
||||
None => doc.artboards.iter().map(|a| a.rect).collect(),
|
||||
};
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut count = 0;
|
||||
// Each object with the clipping path of the layers above it.
|
||||
let mut stack: Vec<(&Node, Option<vectorcraft_geom::Rect>)> = doc.layers.iter().map(|l| (&**l, None)).collect();
|
||||
while let Some((n, clip)) = stack.pop() {
|
||||
if let NodeKind::Layer { template, printable, children, clip: clipping, .. } = &n.kind {
|
||||
// An opacity mask decides what shows, so a masked layer's art is not measured.
|
||||
if !n.visible || *template || !(*printable || non_printing) || n.opacity <= 0.0 || n.extras().mask.is_some() {
|
||||
continue;
|
||||
}
|
||||
// A clipping layer's first child clips the others, and its fills and strokes are an
|
||||
// object of their own.
|
||||
let (inner, members) = if *clipping {
|
||||
let Some(own) = clip_region(children, &symbols) else { continue };
|
||||
let inner = clip.map_or(own, |c| c.intersect(own));
|
||||
if let Some(first) = children.first()
|
||||
&& let Drawn::Bounds(b) = clip_paint_drawn(first, inner, &symbols)
|
||||
{
|
||||
let b = clip.map_or(b, |c| c.intersect(b));
|
||||
if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
(Some(inner), children.get(1..).unwrap_or_default())
|
||||
} else {
|
||||
(clip, &children[..])
|
||||
};
|
||||
stack.extend(members.iter().map(|c| (&**c, inner)));
|
||||
continue;
|
||||
}
|
||||
let Drawn::Bounds(b) = drawn_bounds(n, &symbols) else { continue };
|
||||
let b = clip.map_or(b, |c| c.intersect(b));
|
||||
if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// What [`drawn_bounds`] finds an object draws.
|
||||
enum Drawn {
|
||||
/// Nothing: it is hidden, a guide, at 0% opacity, or a path that paints nothing.
|
||||
Nothing,
|
||||
/// Art within these bounds.
|
||||
Bounds(vectorcraft_geom::Rect),
|
||||
/// Art whose bounds aren't known, which is not measured: brush art paints past the visual
|
||||
/// bounds by an amount they don't give, an opacity mask hides part of what they hold, and area
|
||||
/// type and type on a path are bounded by their frame or path.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Whether path or compound path `n` paints: one of its fills and strokes is visible, has a paint
|
||||
/// and an opacity above 0 and, a stroke, a width above 0. Other objects count as painting.
|
||||
fn paints(n: &Node) -> bool {
|
||||
!matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
|| n.appearance.items.iter().any(|i| {
|
||||
i.visible() && i.opacity() > 0.0 && !i.paint().is_none() && !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
|
||||
})
|
||||
}
|
||||
|
||||
/// What `n` draws on a page, by its visual bounds (strokes included): a group without a clipping
|
||||
/// path by the members that draw, and a clip group by the part of them inside its clipping path
|
||||
/// together with what the clipping path paints itself ([`clip_paint_drawn`]).
|
||||
/// Hidden objects, guides, objects at 0% opacity and paths that paint nothing draw nothing. Art
|
||||
/// with a brushed stroke that draws, in `n` or (outside groups) in the objects it holds, art with
|
||||
/// an opacity mask, and area type and type on a path are [`Drawn::Unknown`].
|
||||
fn drawn_bounds(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn {
|
||||
if !n.visible || n.is_guide() || n.opacity <= 0.0 || !paints(n) {
|
||||
return Drawn::Nothing;
|
||||
}
|
||||
// An opacity mask decides what shows of the object, and the bounds of area type and type on a
|
||||
// path are its frame or path, not its glyphs.
|
||||
let frame_bounds = matches!(&n.kind, NodeKind::Text(t) if !matches!(t.kind, vectorcraft_doc::TextKind::Point));
|
||||
if vectorcraft_brush::reach(n) > 0.0 || n.extras().mask.is_some() || frame_bounds {
|
||||
return Drawn::Unknown;
|
||||
}
|
||||
let members = |children: &[Arc<Node>]| {
|
||||
let mut out = Some(None);
|
||||
for c in children {
|
||||
out = match (out, drawn_bounds(c, symbols)) {
|
||||
(None, _) | (_, Drawn::Unknown) => None,
|
||||
(Some(acc), Drawn::Bounds(b)) => Some(vectorcraft_geom::union_opt(acc, Some(b))),
|
||||
(keep, Drawn::Nothing) => keep,
|
||||
};
|
||||
}
|
||||
out
|
||||
};
|
||||
let measured = match &n.kind {
|
||||
NodeKind::Group { clip: false, .. } => match members(n.editing_children()) {
|
||||
Some(art) => art.and_then(|_| n.visual_of_members(std::iter::once(art))),
|
||||
None => return Drawn::Unknown,
|
||||
},
|
||||
NodeKind::Group { clip: true, children } => {
|
||||
let Some(region) = clip_region(children, symbols) else { return Drawn::Nothing };
|
||||
let Some(art) = members(children.get(1..).unwrap_or_default()) else { return Drawn::Unknown };
|
||||
let art = art.map(|a| region.intersect(a)).filter(|b| b.area() > 0.0);
|
||||
match children.first().map_or(Drawn::Nothing, |first| clip_paint_drawn(first, region, symbols)) {
|
||||
Drawn::Unknown => return Drawn::Unknown,
|
||||
Drawn::Bounds(b) => vectorcraft_geom::union_opt(art, Some(b)),
|
||||
Drawn::Nothing => art,
|
||||
}
|
||||
}
|
||||
_ if vectorcraft_brush::reach_within(n) > 0.0 => return Drawn::Unknown,
|
||||
_ => n.visual_bounds_with(symbols),
|
||||
};
|
||||
measured.map_or(Drawn::Nothing, Drawn::Bounds)
|
||||
}
|
||||
|
||||
/// The region the clipping path of a clip group or clipping layer with `children` clips to: its
|
||||
/// geometric bounds, without its strokes.
|
||||
fn clip_region(children: &[Arc<Node>], symbols: &vectorcraft_doc::SymbolBoxes) -> Option<vectorcraft_geom::Rect> {
|
||||
children.first()?.geometric_bounds_with(symbols)
|
||||
}
|
||||
|
||||
/// What clipping path `clip` paints itself ([`Node::clip_paint`]): its fills inside `region`, the
|
||||
/// region it clips to, and its strokes over the clipped art, unclipped.
|
||||
fn clip_paint_drawn(clip: &Node, region: vectorcraft_geom::Rect, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn {
|
||||
let paint = clip.clip_paint();
|
||||
let mut out = None;
|
||||
for (part, clipped) in [(paint.fill, true), (paint.stroke, false)] {
|
||||
let Some(part) = part else { continue };
|
||||
match drawn_bounds(&part, symbols) {
|
||||
Drawn::Unknown => return Drawn::Unknown,
|
||||
Drawn::Nothing => {}
|
||||
Drawn::Bounds(b) => {
|
||||
let b = if clipped { region.intersect(b) } else { b };
|
||||
out = vectorcraft_geom::union_opt(out, Some(b).filter(|b| b.area() > 0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.map_or(Drawn::Nothing, Drawn::Bounds)
|
||||
}
|
||||
|
||||
/// Whether bounds `b` reach the trim edge `t` (within [`EDGE_TOLERANCE`] on either side of it) on a
|
||||
/// side where `bleed` (`[top, bottom, left, right]`) is above 0 and end before the bleed edge there.
|
||||
/// Document space has y down.
|
||||
fn stops_short(b: vectorcraft_geom::Rect, t: vectorcraft_geom::Rect, [top, bottom, left, right]: [f64; 4]) -> bool {
|
||||
let tol = EDGE_TOLERANCE;
|
||||
let across = b.x0 < t.x1 && b.x1 > t.x0;
|
||||
let down = b.y0 < t.y1 && b.y1 > t.y0;
|
||||
let reaches = |near: f64, far: f64, edge: f64| near <= edge + tol && far >= edge - tol;
|
||||
(across && top > 0.0 && reaches(b.y0, b.y1, t.y0) && b.y0 > t.y0 - top + tol)
|
||||
|| (across && bottom > 0.0 && reaches(-b.y1, -b.y0, -t.y1) && b.y1 < t.y1 + bottom - tol)
|
||||
|| (down && left > 0.0 && reaches(b.x0, b.x1, t.x0) && b.x0 > t.x0 - left + tol)
|
||||
|| (down && right > 0.0 && reaches(-b.x1, -b.x0, -t.x1) && b.x1 < t.x1 + right - tol)
|
||||
}
|
||||
|
||||
/// The warning for `n` objects that [`short_of_bleed`] finds; `None` for none.
|
||||
pub fn short_of_bleed_warning(n: usize) -> Option<String> {
|
||||
match n {
|
||||
0 => None,
|
||||
1 => Some(format!("1 object {SHORT_OF_BLEED_ONE}")),
|
||||
_ => Some(format!("{n} objects {SHORT_OF_BLEED_OTHER}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of [`short_of_bleed_warning`] for one object and for more.
|
||||
const SHORT_OF_BLEED_ONE: &str = "reaches the trim edge but stops short of the bleed";
|
||||
const SHORT_OF_BLEED_OTHER: &str = "reach the trim edge but stop short of the bleed";
|
||||
|
||||
/// Whether `text` is a warning [`short_of_bleed_warning`] gives.
|
||||
pub fn is_short_of_bleed(text: &str) -> bool {
|
||||
text.ends_with(SHORT_OF_BLEED_ONE) || text.ends_with(SHORT_OF_BLEED_OTHER)
|
||||
}
|
||||
|
||||
/// The end of the writer's warning for a page longer than 14,400 pt written with a `UserUnit`
|
||||
/// above 1.
|
||||
const SHOWN_SMALLER: &str = "so apps that ignore UserUnit show it that many times smaller";
|
||||
@@ -340,7 +527,7 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i
|
||||
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
|
||||
// The editing data leaves out an Export for Screens folder outside the read roots.
|
||||
let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false));
|
||||
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?;
|
||||
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, true, native, || Ok(None))?;
|
||||
notes.extend(drawn);
|
||||
if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None {
|
||||
for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) {
|
||||
@@ -364,7 +551,8 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result<Option<Strin
|
||||
|
||||
/// [`encode`] the pages of `doc`, carrying `native()` as the editing data (a `.ai` file: the
|
||||
/// native document with its save options, whose pages may be left blank), and `private()`, the
|
||||
/// editing copy of the art for other apps with what it couldn't hold, on every page.
|
||||
/// editing copy of the art for other apps with what it couldn't hold, on every page. It doesn't
|
||||
/// warn about art that stops short of the bleed ([`short_of_bleed`]), which PDF export does.
|
||||
pub(super) fn encode_carrying(
|
||||
cmd: &str,
|
||||
doc: &Document,
|
||||
@@ -372,20 +560,26 @@ pub(super) fn encode_carrying(
|
||||
native: impl FnOnce() -> Result<Vec<u8>>,
|
||||
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
|
||||
) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
encode_carrying_at(cmd, doc, p, None, native, private)
|
||||
encode_carrying_at(cmd, doc, p, None, false, native, private)
|
||||
}
|
||||
|
||||
/// [`encode_carrying`] modified at `modified` (Unix seconds) when given, instead of the time of
|
||||
/// writing.
|
||||
/// writing, warning about art that stops short of the bleed when `bleed_check` is true.
|
||||
fn encode_carrying_at(
|
||||
cmd: &str,
|
||||
doc: &Document,
|
||||
p: &Value,
|
||||
modified: Option<i64>,
|
||||
bleed_check: bool,
|
||||
native: impl FnOnce() -> Result<Vec<u8>>,
|
||||
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
|
||||
) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?;
|
||||
// Measured before the pages' background colors join the art. Only art that prints counts:
|
||||
// createLayers writes non-printing layers with /PrintState /OFF, so they count only with
|
||||
// includeNonPrinting, which writes them as printing art.
|
||||
let set = &opts.settings;
|
||||
let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
|
||||
// The pages' background colors, behind the art (the editing data keeps them as colors).
|
||||
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
|
||||
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
|
||||
@@ -401,6 +595,8 @@ fn encode_carrying_at(
|
||||
if opts.settings.leaves_out_bleed(doc) {
|
||||
notes.push(Note::loss(BLEED_LEFT_OUT));
|
||||
}
|
||||
// Art that reaches the trim edge but leaves part of the page's bleed empty.
|
||||
notes.extend(short_of_bleed_warning(short).map(Note::loss));
|
||||
if opts.settings.preserve_editing {
|
||||
if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) {
|
||||
opts.native = Some(native()?);
|
||||
|
||||
@@ -629,6 +629,24 @@ impl<W: std::io::Write> std::io::Write for Counted<W> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A writer that fails once the work running on this thread is canceled
|
||||
/// ([`crate::cancel::is_cancelled`]), so a streamed save stops writing into its temporary file.
|
||||
/// It sits under the stream's buffer: it is checked once per buffer written, not per write.
|
||||
struct StopsWhenCancelled<W>(W);
|
||||
|
||||
impl<W: std::io::Write> std::io::Write for StopsWhenCancelled<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
if crate::cancel::is_cancelled() {
|
||||
return Err(std::io::Error::other(crate::cancel::Cancelled));
|
||||
}
|
||||
self.0.write(buf)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.0.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// The artboards a native or `.ai` save also writes to files of their own: with
|
||||
/// `separateArtboards`, those `range` names (default all).
|
||||
fn separate_boards(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Vec<usize>> {
|
||||
@@ -1026,10 +1044,15 @@ impl SaveJob {
|
||||
}
|
||||
|
||||
/// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in
|
||||
/// order: when `stop` returns a value, nothing is written and that value is returned.
|
||||
/// order: when `stop` returns a value, nothing is written and that value is returned. Work
|
||||
/// canceled ([`crate::cancel`]) before the first file is written returns
|
||||
/// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the
|
||||
/// others are written too.
|
||||
pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let (plan, doc) = (&self.plan, &*self.doc);
|
||||
crate::cancel::check()?;
|
||||
let enc = self.encode()?;
|
||||
crate::cancel::check()?;
|
||||
let extra = json!({ "format": plan.format.id, "warnings": enc.notes() });
|
||||
let Some(path) = &plan.path else {
|
||||
let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?;
|
||||
@@ -1046,8 +1069,13 @@ impl SaveJob {
|
||||
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
|
||||
return Ok(stopped);
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
write(p, bytes)?;
|
||||
for (i, (p, bytes)) in files.iter().enumerate() {
|
||||
if i == 0 {
|
||||
write(p, bytes)?;
|
||||
} else {
|
||||
// Once a file is in place, a Cancel no longer stops the save: the set is written whole.
|
||||
crate::cancel::scope(&crate::cancel::CancelToken::new(), None, || write(p, bytes))?;
|
||||
}
|
||||
}
|
||||
let bytes = files.first().map_or(0, |f| f.1.len());
|
||||
let mut out = super::merge(json!({ "path": path, "bytes": bytes }), extra);
|
||||
@@ -1070,11 +1098,15 @@ impl SaveJob {
|
||||
/// [`SaveJob::write`] through `stream`, which writes the file at a path with what the filler
|
||||
/// it is given writes (atomically, as [`vectorcraft_format::write_atomic_with`]). A native
|
||||
/// file goes into it as it is encoded ([`SaveJob::streams`]), never held whole in memory;
|
||||
/// other files are encoded first, then written into it.
|
||||
/// other files are encoded first, then written into it. Work canceled ([`crate::cancel`])
|
||||
/// while the native file is encoded, or before its filler returns, returns
|
||||
/// [`crate::EngineError::Cancelled`]: the filler fails, so `stream` keeps the file as it was
|
||||
/// (the atomic writer checks once more before it puts the file in place).
|
||||
pub fn write_streamed(&self, stream: StreamWrite) -> Result<Value> {
|
||||
let (Some(path), true) = (&self.plan.path, self.streams()) else {
|
||||
return self.write(|p, b| stream(p, &mut |w| w.write_all(b)));
|
||||
};
|
||||
crate::cancel::check()?;
|
||||
let (cmd, f) = (self.plan.mode.command(), self.plan.format);
|
||||
let doc = self.doc.without_edit_modes();
|
||||
let doc = match f.id {
|
||||
@@ -1091,16 +1123,22 @@ impl SaveJob {
|
||||
let mut failed = None;
|
||||
let mut written = 0u64;
|
||||
let mut fill = |w: &mut dyn std::io::Write| {
|
||||
let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, w), n: 0 };
|
||||
let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, StopsWhenCancelled(w)), n: 0 };
|
||||
let r = super::native::encode_to(cmd, f, &doc, &self.params, &mut out);
|
||||
written = out.n;
|
||||
match r {
|
||||
let r = match r {
|
||||
Ok(()) => out.inner.flush(),
|
||||
Err(e) => {
|
||||
failed = Some(e);
|
||||
Err(std::io::Error::other("the file couldn't be encoded"))
|
||||
}
|
||||
};
|
||||
// The last check before the file is replaced: a canceled save leaves it as it was.
|
||||
if crate::cancel::is_cancelled() {
|
||||
failed = Some(crate::EngineError::Cancelled);
|
||||
return Err(std::io::Error::other(crate::cancel::Cancelled));
|
||||
}
|
||||
r
|
||||
};
|
||||
let r = stream(path, &mut fill);
|
||||
r.map_err(|e| failed.take().unwrap_or(e))?;
|
||||
|
||||
@@ -1349,10 +1349,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
}
|
||||
// The document a PDF row writes: with Include Bleed, the artboards as they are.
|
||||
let pdf_doc = ungrown.as_deref();
|
||||
// A PDF page of an artboard has the artboard as its trim, with or without Include Bleed. A
|
||||
// page of its art's bounds has every object at its edge: it doesn't say whether art stops
|
||||
// short of the bleed.
|
||||
let artboard_page = o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
|
||||
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
|
||||
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
|
||||
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
|
||||
for n in given {
|
||||
for n in given.into_iter().filter(|n| artboard_page || !super::pdf::is_short_of_bleed(&n.text)) {
|
||||
add_note(&mut notes, n);
|
||||
}
|
||||
Ok(bytes)
|
||||
|
||||
@@ -935,6 +935,109 @@ fn a_save_that_fails_while_streaming_leaves_the_file_as_it_was() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save canceled (Background Save's Cancel) before it starts, while a native file streams into
|
||||
/// its temporary file, or after the last byte went into it, fails with `Cancelled` and leaves the
|
||||
/// file as it was, with no temporary file behind. A file encoded first is never written.
|
||||
#[test]
|
||||
fn a_canceled_save_leaves_the_file_as_it_was() {
|
||||
/// Passes every write on, and cancels the save after the first one.
|
||||
struct CancelAfterFirst<'a> {
|
||||
inner: &'a mut dyn std::io::Write,
|
||||
token: crate::cancel::CancelToken,
|
||||
}
|
||||
impl std::io::Write for CancelAfterFirst<'_> {
|
||||
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.write(b)?;
|
||||
self.token.cancel();
|
||||
Ok(n)
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
let d = tmp_dir("stream-cancel");
|
||||
// A small document's file goes in one piece; a large one's in several.
|
||||
for count in [1, 1500] {
|
||||
let mut s = session(2000.0, 2000.0, 1);
|
||||
for i in 0..count {
|
||||
s.execute("shape.rectangle", &json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10})).unwrap();
|
||||
}
|
||||
let path = d.join("a.vectorcraft").to_string_lossy().to_string();
|
||||
s.execute("file.saveCopy", &json!({"path": path})).unwrap();
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap();
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
assert!(job.streams());
|
||||
let token = crate::cancel::CancelToken::new();
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write_streamed(&mut |p, fill| super::write_file_with(p, &mut |w| fill(&mut CancelAfterFirst { inner: w, token: token.clone() })))
|
||||
});
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{count}: {r:?}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before, "{count} objects");
|
||||
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "no temporary file is left");
|
||||
// Canceled before it starts: the file isn't opened.
|
||||
let mut opened = false;
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write_streamed(&mut |_, _| {
|
||||
opened = true;
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)) && !opened, "{r:?}");
|
||||
}
|
||||
// A file encoded first (SVG): nothing reaches the writer.
|
||||
let mut s = session(200.0, 100.0, 1);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": d.join("a.svg").to_string_lossy()})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let token = crate::cancel::CancelToken::new();
|
||||
token.cancel();
|
||||
let mut writes = 0;
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write_streamed(&mut |_, _| {
|
||||
writes += 1;
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write(|_, _| {
|
||||
writes += 1;
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)) && writes == 0, "{r:?}");
|
||||
assert!(!d.join("a.svg").exists());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save that writes several files (EPS with Use Artboards) and is canceled once its first file is
|
||||
/// in place writes the others too and succeeds: the set is never left half written.
|
||||
#[test]
|
||||
fn a_save_canceled_after_its_first_file_writes_them_all() {
|
||||
let d = tmp_dir("cancel-files");
|
||||
let mut s = session(100.0, 100.0, 2);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
let path = d.join("logo.eps").to_string_lossy().to_string();
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let token = crate::cancel::CancelToken::new();
|
||||
let mut written = vec![];
|
||||
let r = crate::cancel::scope(&token, None, || {
|
||||
job.write(|p, b| {
|
||||
super::write_save_file(p, b)?;
|
||||
written.push(p.to_string());
|
||||
token.cancel();
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(r.is_ok(), "{r:?}");
|
||||
assert_eq!(written.len(), 3, "{written:?}");
|
||||
assert!(written.iter().all(|p| std::path::Path::new(p).is_file()), "{written:?}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them.
|
||||
#[test]
|
||||
fn a_failed_save_does_not_stamp_the_documents_dates() {
|
||||
|
||||
@@ -171,6 +171,226 @@ fn a_pdfx_file_that_leaves_out_the_document_bleed_warns() {
|
||||
assert!(!left_out(&warnings), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// A 200 × 100 pt document with no art, bleed `bleed` (pt).
|
||||
fn bleed_session(bleed: Value) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("document.setup", &json!({ "bleed": bleed })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// A rectangle from (x0, y0) to (x1, y1) without a stroke, on the current layer.
|
||||
fn plain_rect(s: &mut Session, [x0, y0, x1, y1]: [f64; 4]) -> Value {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0})).unwrap()["id"].clone();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// The warnings of a PDF that carries the document's bleed that say art stops short of it.
|
||||
fn short_of_bleed(s: &mut Session) -> Vec<String> {
|
||||
let (_, warnings) = pdf(s, json!({"bleed": {"useDocument": true}}));
|
||||
warnings.into_iter().filter(|w| super::pdf::is_short_of_bleed(w)).collect()
|
||||
}
|
||||
|
||||
const MM: f64 = 72.0 / 25.4;
|
||||
|
||||
/// A bleed raised from 2 mm to 5 mm leaves a background that filled the old bleed, and a band
|
||||
/// placed against the trim edge, short of the new one: the export warns once, counting both.
|
||||
#[test]
|
||||
fn art_that_reaches_the_trim_edge_but_stops_short_of_the_bleed_warns() {
|
||||
let mut s = bleed_session(json!(2.0 * MM));
|
||||
let (b, w, h) = (2.0 * MM, 200.0, 100.0);
|
||||
plain_rect(&mut s, [-b, -b, w + b, h + b]);
|
||||
plain_rect(&mut s, [0.0, 0.0, w, 20.0]);
|
||||
// At 2 mm the background reaches the bleed; the band stops at the trim edge.
|
||||
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
|
||||
s.execute("document.setup", &json!({"bleed": 5.0 * MM})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s), ["2 objects reach the trim edge but stop short of the bleed"]);
|
||||
// The PDF/X presets carry the document's bleed.
|
||||
let (_, warnings) = pdf(&mut s, json!({"preset": "PDF/X-4:2010"}));
|
||||
assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
|
||||
// A PDF/X file with a bleed on the top alone leaves out the rest of the document's bleed, and
|
||||
// the background and the band stop short at the top: the warning comes right after
|
||||
// BLEED_LEFT_OUT.
|
||||
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 9}}));
|
||||
assert_eq!(warnings.first().map(String::as_str), Some(super::pdf::BLEED_LEFT_OUT), "{warnings:?}");
|
||||
assert_eq!(warnings.get(1).map(String::as_str), Some("2 objects reach the trim edge but stop short of the bleed"), "{warnings:?}");
|
||||
// A page without the bleed (the default preset) doesn't warn, and neither does a page of the art's bounds.
|
||||
let (_, warnings) = pdf(&mut s, json!({}));
|
||||
assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
|
||||
let (_, warnings) = pdf(&mut s, json!({"bleed": {"useDocument": true}, "useArtboards": false}));
|
||||
assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
|
||||
// An explicit bleed counts too, and the Summary lists the warning.
|
||||
let (_, warnings) = pdf(&mut s, json!({"bleed": {"top": 9, "bottom": 9, "left": 9, "right": 9}}));
|
||||
assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
|
||||
let v = s.execute("document.pdfSettings", &json!({"bleed": {"useDocument": true}, "includeDocument": true})).unwrap();
|
||||
assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}");
|
||||
// A group counts once, measured by its visible members: a hidden member that fills the bleed
|
||||
// doesn't hide a visible one at the trim edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let fill = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let side = plain_rect(&mut s, [0.0, 40.0, 20.0, 60.0]);
|
||||
s.execute("object.group", &json!({"ids": [fill, band, side]})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [fill]})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
|
||||
// A clip group is measured by the art inside its clipping path, not by a clipping path that
|
||||
// reaches the bleed edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let art = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let clip = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
// A clipping path that paints a fill reaching the trim edge counts, though the art it clips is
|
||||
// inside: in a clip group, and as an object of its own in a clipping layer.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let art = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
|
||||
let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]);
|
||||
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
let mut s = bleed_session(json!(9));
|
||||
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
|
||||
let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]);
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
// A hidden brushed member doesn't keep a group's visible art at the trim edge from counting.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let brushed = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap();
|
||||
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("object.group", &json!({"ids": [brushed, band]})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [brushed]})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
// A clipping layer clips its art to the clipping path's geometry, not to the stroke around it:
|
||||
// the stroke reaches the trim edge, but the art it clips stops 5 pt inside.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
let clip = plain_rect(&mut s, [5.0, 5.0, 195.0, 95.0]);
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [clip], "weight": 10})).unwrap();
|
||||
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
|
||||
}
|
||||
|
||||
/// No warning for art that already fills the bleed, art inside the trim, a document without a
|
||||
/// bleed, art on hidden, non-printing or template layers, a side without a bleed, area type, a
|
||||
/// masked object, or a `.ai` save.
|
||||
#[test]
|
||||
fn art_that_fills_the_bleed_or_stays_inside_does_not_warn() {
|
||||
let mut s = bleed_session(json!(9));
|
||||
plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
|
||||
plain_rect(&mut s, [-20.0, 40.0, 50.0, 60.0]);
|
||||
plain_rect(&mut s, [10.0, 10.0, 190.0, 90.0]);
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A document without a bleed has nothing to fall short of.
|
||||
let mut s = bleed_session(json!(0));
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// Layers that don't print.
|
||||
for props in [json!({"visible": false}), json!({"printable": false}), json!({"template": true})] {
|
||||
let mut s = bleed_session(json!(9));
|
||||
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let mut p = props.clone();
|
||||
p["id"] = layer;
|
||||
s.execute("layer.setProps", &p).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty(), "{props}");
|
||||
}
|
||||
// A hidden object, and a group whose hidden member is the one at the trim edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("object.hide", &json!({"ids": [id]})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
let mut s = bleed_session(json!(9));
|
||||
let edge = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]);
|
||||
s.execute("object.group", &json!({"ids": [edge, inside]})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [edge]})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// Art that lies in the bleed alone, away from the trim edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
plain_rect(&mut s, [20.0, -5.0, 60.0, -3.0]);
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A guide in a group at the trim edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let guide = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]);
|
||||
s.execute("object.group", &json!({"ids": [guide, inside]})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A brushed stroke, whose brush art can paint past its visual bounds, is not measured.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("brush.apply", &json!({"ids": [id], "name": "Charcoal"})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A path with no fill and no stroke paints nothing.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("paint.setFill", &json!({"ids": [id], "none": true})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// An object at 0% opacity draws nothing.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
s.execute("object.setProps", &json!({"ids": [id], "opacity": 0})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A clipping layer whose clipping path lies inside the trim draws none of its art at the edge.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
plain_rect(&mut s, [10.0, 10.0, 60.0, 60.0]);
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A bleed on the top alone: art short at the left doesn't count, art short at the top does.
|
||||
let mut s = bleed_session(json!([9, 0, 0, 0]));
|
||||
plain_rect(&mut s, [0.0, 30.0, 40.0, 60.0]);
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
plain_rect(&mut s, [60.0, 0.0, 100.0, 40.0]);
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
// Area type is bounded by its frame, not its glyphs: a frame at the trim edge is not measured.
|
||||
let mut s = bleed_session(json!(9));
|
||||
s.execute("text.create", &json!({"x": 0, "y": 0, "text": "Title", "size": 12, "area": {"width": 200, "height": 40}})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// An opacity mask decides what shows of the object, so a masked object is not measured.
|
||||
let mut s = bleed_session(json!(9));
|
||||
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let mask = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [band, mask]})).unwrap();
|
||||
assert!(short_of_bleed(&mut s).is_empty());
|
||||
// A `.ai` save with a bleed doesn't warn: the check is PDF export's.
|
||||
let mut s = bleed_session(json!(9));
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
assert_eq!(short_of_bleed(&mut s).len(), 1);
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "bleed": {"useDocument": true}})).unwrap();
|
||||
assert!(!r["warnings"].to_string().contains("short of the bleed"), "{}", r["warnings"]);
|
||||
}
|
||||
|
||||
/// The warning changes neither the art nor the page boxes.
|
||||
#[test]
|
||||
fn the_bleed_warning_changes_no_geometry_and_no_page_box() {
|
||||
let mut s = bleed_session(json!(9));
|
||||
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let v = s.execute("document.exportPdf", &json!({"bleed": {"useDocument": true}})).unwrap();
|
||||
assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
let info = s.execute("document.pdfInfo", &json!({"name": "x.pdf", "dataBase64": v["dataBase64"]})).unwrap();
|
||||
let boxes = &info["pageInfo"][0]["boxes"];
|
||||
let side = |b: &Value| {
|
||||
let n: Vec<f64> = b.as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
|
||||
(((n[2] - n[0]) * 100.0).round() / 100.0, ((n[3] - n[1]) * 100.0).round() / 100.0)
|
||||
};
|
||||
assert_eq!(side(&boxes["trim"]), (200.0, 100.0), "{info}");
|
||||
assert_eq!(side(&boxes["bleed"]), (218.0, 118.0), "{info}");
|
||||
}
|
||||
|
||||
/// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there).
|
||||
fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> {
|
||||
fn visit(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::ImageObject>) {
|
||||
|
||||
@@ -602,6 +602,56 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
|
||||
}
|
||||
|
||||
/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, with a
|
||||
/// path and with a folder, and so do relinking to the written file, placing it and opening it.
|
||||
#[test]
|
||||
fn unembed_keeps_the_clipping_path_of_an_embedded_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip");
|
||||
// An RGB file is kept as a PNG, a CMYK one as a TIFF.
|
||||
let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]]));
|
||||
let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)];
|
||||
for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) {
|
||||
let data = vectorcraft_format::base64_encode(file);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
let before = clip_group(&s.doc().unwrap().doc, group);
|
||||
// Without an extension the image is written in the format it is stored in.
|
||||
let path = if folder {
|
||||
let out = dir.join(format!("folder-{kind}"));
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap();
|
||||
r["unembedded"][0]["path"].as_str().unwrap().to_string()
|
||||
} else {
|
||||
let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap();
|
||||
r["path"].as_str().unwrap().to_string()
|
||||
};
|
||||
let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() };
|
||||
assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}");
|
||||
for step in ["unembed", "relink"] {
|
||||
if step == "relink" {
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
|
||||
assert!(im.link.is_some(), "linked to the file written");
|
||||
assert_eq!(clip_group(d, group), before, "{kind}, {step}, folder: {folder}");
|
||||
}
|
||||
// Placing the written file gives the same clip group as placing the PSD file did.
|
||||
let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap();
|
||||
let placed = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed);
|
||||
assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, place");
|
||||
// Opening it gives a document of the image in that clip group.
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object");
|
||||
let (anchors, even_odd, _) = clip_group(d, top);
|
||||
assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, open");
|
||||
}
|
||||
}
|
||||
|
||||
/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a
|
||||
/// text chunk within the size limit that reads as a path gives one back.
|
||||
#[test]
|
||||
|
||||
@@ -610,6 +610,35 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
|
||||
}
|
||||
|
||||
/// A PDF row with a bleed warns about art that reaches an artboard's edge and stops short of the
|
||||
/// bleed, with or without Include Bleed: the page's trim is the artboard either way. It doesn't
|
||||
/// warn about art that reaches the bleed, or on a page of a selection's bounds.
|
||||
#[test]
|
||||
fn pdf_rows_warn_about_art_short_of_the_bleed_on_artboard_pages_only() {
|
||||
let warned = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap()));
|
||||
let row = json!([{"format": "pdf", "bleed": {"useDocument": true}}]);
|
||||
let mut s = session(1);
|
||||
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
|
||||
// Against the artboard's top edge.
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap();
|
||||
assert!(warned(&export(&mut s, json!({"formats": row}))));
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": [{"format": "pdf"}]}))), "the row takes the document's bleed");
|
||||
assert!(!warned(&export(&mut s, json!({"selection": "one", "formats": row}))));
|
||||
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
|
||||
// Out to the bleed edge on the top, left and right.
|
||||
let mut s = session(1);
|
||||
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": -6, "y": -6, "width": 52, "height": 16})).unwrap();
|
||||
assert!(!warned(&export(&mut s, json!({"formats": row}))));
|
||||
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
|
||||
// Without a document bleed, a row's own bleed warns.
|
||||
let mut s = session(1);
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap();
|
||||
let row = json!([{"format": "pdf", "bleed": {"top": 6, "bottom": 6, "left": 6, "right": 6}}]);
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
|
||||
}
|
||||
|
||||
/// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read
|
||||
/// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries).
|
||||
fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> {
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Flares (the Flare tool): `shape.flare` draws a group of radial-gradient paths that keeps the
|
||||
//! settings it was drawn with ([`FlareSpec`]), and `shape.editFlare` draws it again from them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::flare::{DEFAULT_SEED, FlareSpec, json_close, part_node, parts};
|
||||
use vectorcraft_doc::{Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::{EngineError, Result, Session, bad, check_numbers, f64_or, f64_req, given_objects, number_or};
|
||||
|
||||
const C: &str = "shape.editFlare";
|
||||
|
||||
/// `shape.flare`'s settings besides the center, the rings' end point, the counts and the seed:
|
||||
/// (key, default).
|
||||
const SETTINGS: [(&str, f64); 9] = [
|
||||
("diameter", 100.0),
|
||||
("opacity", 50.0),
|
||||
("brightness", 30.0),
|
||||
("growth", 20.0),
|
||||
("fuzziness", 50.0),
|
||||
("longest", 300.0),
|
||||
("rayFuzziness", 100.0),
|
||||
("rotation", 0.0),
|
||||
("largest", 50.0),
|
||||
];
|
||||
|
||||
/// The whole number of 0 or more `p` gives for `key`, or `default`.
|
||||
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
let n = number_or(p, key, default as f64, cmd)?;
|
||||
if n.is_finite() && n >= 0.0 && n.fract() == 0.0 {
|
||||
Ok(n as u64)
|
||||
} else {
|
||||
Err(bad(cmd, format!("`{key}` must be a whole number of at least 0, not {n}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// `end`, the rings' end point, or an error naming `x2` or `y2` when that coordinate is not a
|
||||
/// finite number (a `pathLength` so large that the end point overflows).
|
||||
fn finite_end(end: Point, cmd: &str) -> Result<Point> {
|
||||
match [("x2", end.x), ("y2", end.y)].into_iter().find(|(_, v)| !v.is_finite()) {
|
||||
None => Ok(end),
|
||||
Some((key, _)) => Err(bad(cmd, format!("{key} must be a finite coordinate"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `shape.flare`'s params `p` with every setting given: the defaults filled in, the counts at most
|
||||
/// 50 and the rings' end point as `x2`, `y2` (from `pathLength` and `direction` when `p` gives no
|
||||
/// end point), with `ringSeed` when `p` gives one.
|
||||
fn settings_of(p: &Value, cmd: &str) -> Result<Value> {
|
||||
let c = Point::new(f64_req(p, "cx", cmd)?, f64_req(p, "cy", cmd)?);
|
||||
let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect();
|
||||
numbers.extend(["x2", "y2", "direction", "pathLength", "seed", "ringSeed"]);
|
||||
check_numbers(p, &numbers, cmd)?;
|
||||
let seed_of = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
let seed = seed_of("seed")?.unwrap_or(DEFAULT_SEED);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) places the rings anew.
|
||||
let ring_seed = match seed_of("ringSeed")? {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad(cmd, format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let rays = count_or(p, "rays", 15, cmd)?.min(50);
|
||||
let rings = count_or(p, "rings", 10, cmd)?.min(50);
|
||||
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
|
||||
(Some(x), Some(y)) => Point::new(x, y),
|
||||
_ => {
|
||||
let a = f64_or(p, "direction", 45.0).to_radians();
|
||||
finite_end(c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0), cmd)?
|
||||
}
|
||||
};
|
||||
let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed });
|
||||
if let Some(r) = ring_seed {
|
||||
v["ringSeed"] = json!(r);
|
||||
}
|
||||
for (key, default) in SETTINGS {
|
||||
v[key] = json!(f64_or(p, key, default));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The objects of a flare drawn with the settings `v`, transformed by `xf`. A new flare's parts
|
||||
/// (`old` None) get new ids and take the document's Align New Objects to Pixel Grid. A flare drawn
|
||||
/// again from its parts `old` keeps, for each part, the id and pixel-aligned property of the old
|
||||
/// part it replaces (the same kind of part, counted in order: the second ring replaces the second
|
||||
/// ring); a part that replaces none gets a new id and the first old part's property.
|
||||
fn part_nodes(d: &mut Document, v: &Value, xf: Affine, old: Option<&[Arc<Node>]>) -> Vec<Arc<Node>> {
|
||||
let mut seen: Vec<&str> = vec![];
|
||||
parts(v)
|
||||
.into_iter()
|
||||
.map(|part| {
|
||||
let name = part.0;
|
||||
let nth = seen.iter().filter(|n| **n == name).count();
|
||||
seen.push(name);
|
||||
let replaced = old.and_then(|old| old.iter().filter(|c| c.name.as_deref() == Some(name)).nth(nth));
|
||||
let id = replaced.map_or_else(|| d.alloc_id(), |c| c.id);
|
||||
let mut n = part_node(id, part, Affine::IDENTITY, false);
|
||||
match old {
|
||||
None => super::object::align_new_object(d, &mut n),
|
||||
Some(old) => n.extras_mut().pixel_aligned = replaced.or(old.first()).is_some_and(|c| c.extras().pixel_aligned),
|
||||
}
|
||||
if xf != Affine::IDENTITY {
|
||||
n.transform(xf, false);
|
||||
}
|
||||
Arc::new(n)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `shape.flare`: a flare group that keeps its settings.
|
||||
pub(super) fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let v = settings_of(p, "shape.flare")?;
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Flare", |d, sel| {
|
||||
let children = part_nodes(d, &v, Affine::IDENTITY, None);
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = Some("Flare".into());
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec::new(v)));
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The settings of flare `id`: a group drawn by the Flare tool whose parts are still the ones its
|
||||
/// settings draw, in place ([`FlareSpec::draws`]). A flare whose parts were edited, distorted,
|
||||
/// removed or added to, or whose art was flattened to a line, is no longer one.
|
||||
pub fn flare_settings(d: &Document, id: NodeId) -> Option<FlareSpec> {
|
||||
let n = d.node(id)?;
|
||||
let spec = n.extras().flare.as_deref()?;
|
||||
// Settings a file holds are read as `shape.flare` reads them.
|
||||
let spec = FlareSpec { params: settings_of(&spec.params, "shape.flare").ok()?, transform: spec.transform };
|
||||
spec.draws(n).then_some(spec)
|
||||
}
|
||||
|
||||
/// The flares `shape.editFlare` changes: those `p` names, else the selected flares. Each must be a
|
||||
/// flare that can be edited.
|
||||
fn flares_to_edit(s: &Session, p: &Value) -> Result<Vec<(NodeId, FlareSpec)>> {
|
||||
let given = given_objects(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let flare = |id: NodeId| flare_settings(d, id).filter(|_| d.is_editable(id)).map(|spec| (id, spec));
|
||||
let flares: Vec<(NodeId, FlareSpec)> = match &given {
|
||||
Some(ids) => ids.iter().map(|id| flare(*id)).collect::<Option<Vec<_>>>().unwrap_or_default(),
|
||||
None => s.doc()?.selection.objects.iter().filter_map(|id| flare(*id)).collect(),
|
||||
};
|
||||
if flares.is_empty() {
|
||||
return Err(EngineError::Other("select a flare".into()));
|
||||
}
|
||||
Ok(flares)
|
||||
}
|
||||
|
||||
/// The settings `old` changed as `p` asks (`shape.editFlare`'s params). The center and the end
|
||||
/// point `p` gives are in the document, where the flare is now drawn, which `xf` maps from where
|
||||
/// it was drawn.
|
||||
fn edited(old: &Value, p: &Value, xf: Affine) -> Result<Value> {
|
||||
let mut v = old.clone();
|
||||
let inv = xf.inverse();
|
||||
let point = |kx: &str, ky: &str| -> Result<Option<Point>> {
|
||||
if p.get(kx).is_none_or(Value::is_null) && p.get(ky).is_none_or(Value::is_null) {
|
||||
return Ok(None);
|
||||
}
|
||||
// A point that leaves the finite range where the flare was drawn is refused, not stored.
|
||||
let q = inv * Point::new(f64_req(p, kx, C)?, f64_req(p, ky, C)?);
|
||||
match [(kx, q.x), (ky, q.y)].into_iter().find(|(_, v)| !v.is_finite()) {
|
||||
None => Ok(Some(q)),
|
||||
Some((key, _)) => Err(bad(C, format!("{key} must be a finite coordinate"))),
|
||||
}
|
||||
};
|
||||
let c = point("cx", "cy")?;
|
||||
let end = point("x2", "y2")?;
|
||||
if let Some(c) = c {
|
||||
v["cx"] = json!(c.x);
|
||||
v["cy"] = json!(c.y);
|
||||
}
|
||||
let centre = Point::new(f64_or(&v, "cx", 0.0), f64_or(&v, "cy", 0.0));
|
||||
let old_end = Point::new(f64_or(&v, "x2", centre.x), f64_or(&v, "y2", centre.y));
|
||||
let end = match end {
|
||||
Some(e) => e,
|
||||
None if p.get("pathLength").is_some_and(|l| !l.is_null()) || p.get("direction").is_some_and(|a| !a.is_null()) => {
|
||||
// The path length and the direction are where the flare is drawn now; the direction is
|
||||
// measured counter-clockwise from 3 o'clock, as `shape.flare` takes it.
|
||||
let (c, e) = (xf * centre, xf * old_end);
|
||||
let d = e - c;
|
||||
let a = number_or(p, "direction", (-d.y).atan2(d.x).to_degrees(), C)?.to_radians();
|
||||
finite_end(inv * (c + Vec2::new(a.cos(), -a.sin()) * number_or(p, "pathLength", d.hypot(), C)?), C)?
|
||||
}
|
||||
// Moving the center leaves the rings' end point where it is.
|
||||
None => old_end,
|
||||
};
|
||||
v["x2"] = json!(end.x);
|
||||
v["y2"] = json!(end.y);
|
||||
for (key, _) in SETTINGS {
|
||||
if p.get(key).is_some_and(|x| !x.is_null()) {
|
||||
v[key] = json!(number_or(p, key, 0.0, C)?);
|
||||
}
|
||||
}
|
||||
for key in ["rays", "rings"] {
|
||||
if p.get(key).is_some_and(|x| !x.is_null()) {
|
||||
v[key] = json!(count_or(p, key, 0, C)?.min(50));
|
||||
}
|
||||
}
|
||||
settings_of(&v, C)
|
||||
}
|
||||
|
||||
/// `shape.editFlare`: draw the flares again with the settings `p` changes, each in its place and
|
||||
/// transformed as it has been since it was drawn, as one undo step.
|
||||
pub(super) fn edit_flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect();
|
||||
numbers.extend(["cx", "cy", "x2", "y2", "pathLength", "direction", "rays", "rings"]);
|
||||
check_numbers(p, &numbers, C)?;
|
||||
let flares = flares_to_edit(s, p)?;
|
||||
let mut changed: Vec<(NodeId, FlareSpec)> = vec![];
|
||||
for (id, spec) in &flares {
|
||||
let v = edited(&spec.params, p, spec.transform)?;
|
||||
if !json_close(&v, &spec.params, 1e-9) {
|
||||
changed.push((*id, FlareSpec { params: v, transform: spec.transform }));
|
||||
}
|
||||
}
|
||||
let ids: Vec<u64> = flares.iter().map(|(id, _)| id.0).collect();
|
||||
// Nothing changes: no undo step.
|
||||
if changed.is_empty() {
|
||||
return Ok(json!({ "ids": ids }));
|
||||
}
|
||||
let edited_ids: Vec<NodeId> = changed.iter().map(|(id, _)| *id).collect();
|
||||
s.edit("Edit Flare", |d, _| {
|
||||
for (id, spec) in changed {
|
||||
let old: Vec<Arc<Node>> = d.node(id).and_then(Node::children).cloned().unwrap_or_default();
|
||||
let children = part_nodes(d, &spec.params, spec.transform, Some(&old));
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
n.extras_mut().flare = Some(Box::new(spec));
|
||||
}
|
||||
if !crate::sanity::objects_in_range(d, &edited_ids) {
|
||||
return Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids }))
|
||||
}
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unembed",
|
||||
[],
|
||||
None,
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds; written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
has_doc,
|
||||
unembed
|
||||
),
|
||||
@@ -634,7 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) ->
|
||||
|
||||
/// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a
|
||||
/// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels
|
||||
/// can't be read ([`readable`]).
|
||||
/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image
|
||||
/// is read with the clipping path it keeps ([`fileio::raster_image`]).
|
||||
fn linked_image(bytes: &[u8], path: Option<&str>) -> Result<RasterImage> {
|
||||
let mut img = super::place::dcs::raster(bytes, path)?;
|
||||
img.blob = readable(img.blob, kept_unread(bytes), true)?;
|
||||
|
||||
@@ -214,6 +214,25 @@ fn spine_points_param(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(wrong)).collect()
|
||||
}
|
||||
|
||||
/// Whether linking handle `out` of spine point `index` at `q` would leave the blend's spine as it
|
||||
/// is (false when the blend or the point is not there, for the edit to report it).
|
||||
fn spine_link_unchanged(s: &Session, p: &Value, cmd: &str, index: usize, out: bool, q: Point) -> Result<bool> {
|
||||
let id = match crate::cmd::object_param(p, "id", cmd)? {
|
||||
Some(id) => Some(id),
|
||||
None => selected_of(s, is_blend).first().copied(),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let Some(NodeKind::Blend { children, spec }) = id.and_then(|id| d.node(id)).map(|n| &n.kind) else { return Ok(false) };
|
||||
let Some((path, _)) = live::pin_spine(children, spec) else { return Ok(false) };
|
||||
Ok(path.subpaths.first().is_some_and(|sp| {
|
||||
sp.anchors.get(index).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, q, sp.has_segment(index, !out));
|
||||
linked == *a
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.spine.moveAnchor";
|
||||
let index = index_param(p, "anchor", C)?;
|
||||
@@ -225,15 +244,33 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) => return Err(bad(C, "handle must be in or out")),
|
||||
};
|
||||
let independent = switch_or(p, "independent", false, C)?;
|
||||
let link = switch_or(p, "link", false, C)?;
|
||||
let with = spine_points_param(p, C)?;
|
||||
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
|
||||
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "`with` moves points, not a handle"));
|
||||
}
|
||||
if link && independent {
|
||||
return Err(bad(C, "`link` and `independent` cannot both be true"));
|
||||
}
|
||||
if link && handle.is_none() {
|
||||
return Err(bad(C, "`link` places a handle: give `handle`"));
|
||||
}
|
||||
if link && let Some(out) = handle {
|
||||
// A spine point the linked handles would leave as it is records no undo step.
|
||||
if spine_link_unchanged(s, p, C, index, out, q)? {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
|
||||
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
|
||||
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
|
||||
if let Some(out) = handle {
|
||||
a.set_handle(out, q, independent);
|
||||
if link {
|
||||
a.link_handle(out, q, pull_out);
|
||||
} else {
|
||||
a.set_handle(out, q, independent);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let delta = q - a.p;
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Spine Point",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
has_doc,
|
||||
spine_move_anchor
|
||||
),
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Attributes",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, item?, target?: \"object\"|\"contents\"} → {ids, overprintFill, overprintStroke, showCenter, imageMap: \"none\"|\"rectangle\"|\"polygon\", url, note, fillRule: \"nonZero\"|\"evenOdd\" (of the paths and compound paths in them), reversed (their subpaths run counter-clockwise on screen: Reverse Path Direction On), recentUrls: [newest first]} the Attributes panel's values for `ids` or the selection, overprint aimed as object.setOverprint aims; a value is null where they differ (or nothing has a fill, stroke or path)",
|
||||
"{ids?|id?, item?, target?: \"object\"|\"contents\"} → {ids, overprintFill, overprintStroke, showCenter, imageMap: \"none\"|\"rectangle\"|\"polygon\", url, note, fillRule: \"nonZero\"|\"evenOdd\" (of the paths and compound paths in them), reversed (their subpaths run counter-clockwise on screen: Reverse Path Direction On), recentUrls: [newest first, at most 30]} the Attributes panel's values for `ids` or the selection, overprint aimed as object.setOverprint aims; a value is null where they differ (or nothing has a fill, stroke or path)",
|
||||
has_doc,
|
||||
|s, p| Ok(attributes(s, p)?.to_json())
|
||||
),
|
||||
|
||||
@@ -382,6 +382,7 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
|
||||
("addon.pathtools.cornerSet", "items", "ids"),
|
||||
("addon.pathtools.cornerRemove", "items", "ids"),
|
||||
("addon.pathtools.bridge", "radius", "gap"),
|
||||
("links.unembed", "id", "ids"),
|
||||
("links.unembed", "path", "folder"),
|
||||
];
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool}",
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false",
|
||||
has_doc,
|
||||
set_handle
|
||||
),
|
||||
@@ -457,6 +457,9 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ai = index_opt(p, "anchor", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing anchor"))?;
|
||||
let out = str_param(p, "which") != Some("in");
|
||||
let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?);
|
||||
if switch_or(p, "link", false, "path.setHandle")? {
|
||||
return link_handle(s, p, id, si, ai, out, pos);
|
||||
}
|
||||
let independent = switch_or(p, "independent", false, "path.setHandle")?;
|
||||
// A handle already there, on an anchor already of the kind it would get, changes nothing and
|
||||
// records no undo step. The handle is compared directly: `set_handle` would recompute the
|
||||
@@ -476,6 +479,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `path.setHandle` with `link` (the Anchor Point tool's Alt-drag on a handle): the handle goes to
|
||||
/// (x, y) and the anchor becomes smooth, its other handle turned in line at its own length. A
|
||||
/// retracted other handle is pulled out to the moved handle's length when a segment leaves the
|
||||
/// anchor on its side, and stays retracted at an open end. An anchor the edit would leave as it
|
||||
/// is records no undo step.
|
||||
fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out: bool, pos: Point) -> Result<Value> {
|
||||
const C: &str = "path.setHandle";
|
||||
if switch_or(p, "independent", false, C)? {
|
||||
return Err(bad(C, "`link` and `independent` cannot both be true"));
|
||||
}
|
||||
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| {
|
||||
sp.anchors.get(ai).is_some_and(|a| {
|
||||
let mut linked = *a;
|
||||
linked.link_handle(out, pos, sp.has_segment(ai, !out));
|
||||
linked == *a
|
||||
})
|
||||
});
|
||||
if unchanged {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Reshape", |d, _| {
|
||||
let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
let pull_out = sp.has_segment(ai, !out);
|
||||
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
a.link_handle(out, pos, pull_out);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point
|
||||
/// tool's Shift-drag).
|
||||
fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -557,6 +557,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.update",
|
||||
"shape.arc",
|
||||
"shape.circleThroughPoints",
|
||||
"shape.editFlare",
|
||||
"shape.ellipse",
|
||||
"shape.flare",
|
||||
"shape.line",
|
||||
|
||||
@@ -157,6 +157,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool),
|
||||
p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool),
|
||||
p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool),
|
||||
p!("holdShortcuts", "General", "Options", "Hold Shortcuts", bool),
|
||||
p!("keyHoldDelay", "General", "Options", "Hold Shortcut Delay", num(0.2, 1.0, "s")),
|
||||
p!("boundingBoxWhileMovingAndDrawing", "General", "Options", "Show Bounding Box While Moving and Drawing", bool),
|
||||
// Selection & Anchor Display
|
||||
p!("selectionTolerance", "Selection & Anchor Display", "Selection", "Tolerance", num(1.0, 8.0, "px")),
|
||||
|
||||
@@ -29,6 +29,7 @@ use vectorcraft_tools::{PaintDefaults, Tool};
|
||||
pub use cmd::clipboard::{Clipboard, SourceLayer};
|
||||
pub use cmd::create::constrain_click;
|
||||
pub use cmd::distortcmds::{perspective_click, width_point_pair};
|
||||
pub use cmd::flare::flare_settings;
|
||||
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
|
||||
pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::auto_simplify_level;
|
||||
@@ -198,7 +199,8 @@ pub struct Session {
|
||||
/// `plugin.install` takes `grant` and `allowHeavy` from any request
|
||||
/// ([`Session::allow_plugin_grants_from_requests`]).
|
||||
plugin_grants_from_requests: bool,
|
||||
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved.
|
||||
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first, at most
|
||||
/// [`cmd::RECENT_URLS`]; not saved.
|
||||
pub recent_urls: Vec<String>,
|
||||
/// The saved tracing presets' revision and latest changes ([`Session::trace_presets_revision`]).
|
||||
pub(crate) trace_preset_changes: cmd::TracePresetChanges,
|
||||
@@ -417,7 +419,7 @@ use history::history_budget_for;
|
||||
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
|
||||
pub(crate) use interaction::PreviewCopies;
|
||||
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
|
||||
pub use prefs::{DrawMode, PluginBudget, Prefs};
|
||||
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs};
|
||||
pub use sanity::TOO_DEEP;
|
||||
pub(crate) use sanity::{deselect_hidden, is_guide_path};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -97,6 +97,13 @@ pub struct Prefs {
|
||||
/// A single-key tool shortcut held down chooses its tool until the key is let go, and then the
|
||||
/// tool active before comes back; a quick press chooses the tool for good.
|
||||
pub hold_tool_keys: bool,
|
||||
/// Hold shortcuts act (Edit › Keyboard Shortcuts › Hold Shortcuts, off by default): a key with a
|
||||
/// hold shortcut runs it when held for [`Self::key_hold_delay`], and its own shortcut when let go
|
||||
/// sooner. Off, every key runs on its press and the dialog shows no Hold column.
|
||||
pub hold_shortcuts: bool,
|
||||
/// Seconds a key with a hold shortcut must stay down before the hold shortcut runs (Hold
|
||||
/// Shortcut Delay, 0.2 to 1.0). VectorCraft's own default, 0.35.
|
||||
pub key_hold_delay: f64,
|
||||
/// With View › Show Bounding Box on, the bounding box stays visible while a drag moves the
|
||||
/// selection, and the shape tools that show it draw it around the shape being drawn. Off (the
|
||||
/// default), it hides during a move and while a shape is drawn, except that a Selection tool
|
||||
@@ -420,6 +427,21 @@ pub struct Prefs {
|
||||
pub import_matches: Vec<cmd::importmatches::ImportMatch>,
|
||||
}
|
||||
|
||||
/// The default Hold Shortcut Delay, in seconds (VectorCraft's own value).
|
||||
pub const KEY_HOLD_DELAY: f64 = 0.35;
|
||||
/// The range of the Hold Shortcut Delay, in seconds.
|
||||
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
|
||||
|
||||
impl Prefs {
|
||||
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
|
||||
/// checked against the range, so a value outside it is brought inside, and one that is not a
|
||||
/// number gives the default.
|
||||
pub fn key_hold_delay(&self) -> f64 {
|
||||
let (min, max) = KEY_HOLD_DELAY_RANGE;
|
||||
if self.key_hold_delay.is_finite() { self.key_hold_delay.clamp(min, max) } else { KEY_HOLD_DELAY }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Prefs {
|
||||
fn default() -> Self {
|
||||
let s = |v: &str| v.to_string();
|
||||
@@ -451,6 +473,8 @@ impl Default for Prefs {
|
||||
scrub_numeric_fields: true,
|
||||
trackpad_rotate_view: true,
|
||||
hold_tool_keys: true,
|
||||
hold_shortcuts: false,
|
||||
key_hold_delay: KEY_HOLD_DELAY,
|
||||
bounding_box_while_moving_and_drawing: false,
|
||||
paste_offset: 10.0,
|
||||
selection_tolerance: 3.0,
|
||||
|
||||
@@ -3393,6 +3393,149 @@ fn flare_rotation_turns_only_the_rays() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A flare keeps its settings: `shape.editFlare` draws it again with the settings changed, in its
|
||||
/// place and transformed as it has been since, as one undo step (none when nothing changes). A
|
||||
/// flare with a changed part, a locked one and an expanded one are not edited.
|
||||
#[test]
|
||||
fn edit_flare_draws_a_transformed_flare_again_in_its_place_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let p = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 9, "rings": 4, "x2": 400, "y2": 200, "seed": 3});
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
// Reflected twice, sheared and back, turned a quarter and moved: it stays a flare.
|
||||
for (c, p) in [
|
||||
("object.reflect", json!({"axis": "vertical"})),
|
||||
("object.reflect", json!({"axis": "horizontal"})),
|
||||
("object.shear", json!({"angle": 30})),
|
||||
("object.shear", json!({"angle": -30})),
|
||||
("object.rotate", json!({"angle": 90})),
|
||||
("object.move", json!({"dx": 50, "dy": 10})),
|
||||
] {
|
||||
s.execute(c, &p).unwrap();
|
||||
}
|
||||
let spec = |s: &Session| flare_settings(&s.doc().unwrap().doc, id).expect("still a flare");
|
||||
let part = |s: &Session, name: &str| {
|
||||
let g = s.doc().unwrap().doc.node(id).unwrap();
|
||||
g.children().unwrap().iter().filter(|c| c.name.as_deref() == Some(name)).map(|c| c.geometric_bounds().unwrap()).collect::<Vec<_>>()
|
||||
};
|
||||
let (c, e) = (spec(&s).center().unwrap(), spec(&s).end().unwrap());
|
||||
// The quarter turn made the rings run vertically, 200 points from the center.
|
||||
assert!((c.distance(e) - 200.0).abs() < 1e-6 && (c.x - e.x).abs() < 1e-6, "{c:?} {e:?}");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("shape.editFlare", &json!({"diameter": 100, "rings": 6, "rays": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
let centre = part(&s, "Center")[0];
|
||||
assert!(centre.center().distance(c) < 1e-6 && (centre.width() - 100.0).abs() < 1e-6, "{centre:?}");
|
||||
assert_eq!((part(&s, "Ring").len(), part(&s, "Rays").len()), (6, 0));
|
||||
assert!(spec(&s).end().unwrap().distance(e) < 1e-6, "the end point stays");
|
||||
// Each ring lies on the line from the center to the end point.
|
||||
assert!(part(&s, "Ring").iter().all(|r| (r.center().x - c.x).abs() < 1e-6), "{:?}", part(&s, "Ring"));
|
||||
// The center handle, where it is drawn now: the end point stays where it is.
|
||||
s.execute("shape.editFlare", &json!({"ids": [id.0], "cx": c.x + 20.0, "cy": c.y})).unwrap();
|
||||
assert!(spec(&s).center().unwrap().distance(Point::new(c.x + 20.0, c.y)) < 1e-6);
|
||||
assert!(spec(&s).end().unwrap().distance(e) < 1e-6);
|
||||
assert!(part(&s, "Center")[0].center().distance(Point::new(c.x + 20.0, c.y)) < 1e-6);
|
||||
// The end handle, then the path length and direction.
|
||||
s.execute("shape.editFlare", &json!({"x2": c.x + 20.0, "y2": c.y + 80.0})).unwrap();
|
||||
assert!(spec(&s).end().unwrap().distance(Point::new(c.x + 20.0, c.y + 80.0)) < 1e-6);
|
||||
// The path length and direction are where the flare is drawn now, though it was turned.
|
||||
s.execute("shape.editFlare", &json!({"direction": 0, "pathLength": 50})).unwrap();
|
||||
assert!(spec(&s).end().unwrap().distance(Point::new(c.x + 70.0, c.y)) < 1e-6, "{:?}", spec(&s).end());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Nothing changes: no undo step.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("shape.editFlare", &json!({"diameter": 100})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
// Bad values are refused.
|
||||
for bad in [json!({"rings": 2.5}), json!({"diameter": "big"}), json!({"cx": 10}), json!({"diameter": 1e20})] {
|
||||
assert!(s.execute("shape.editFlare", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(spec(&s).end().unwrap().distance(e) < 1e-6, "undo puts the end point back");
|
||||
// A changed part: no longer a flare.
|
||||
s.edit("Opacity", |d, _| {
|
||||
let ring = d.node(id).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Center")).unwrap().id;
|
||||
d.node_mut(ring).unwrap().opacity = 0.25;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(s.execute("shape.editFlare", &json!({"rings": 3})).unwrap_err().to_string(), "select a flare");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// A locked flare.
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(s.execute("shape.editFlare", &json!({"ids": [id.0], "rings": 3})).is_err());
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
// Object › Expand: a plain group that is no longer a flare.
|
||||
s.execute("object.expand", &json!({"object": true, "fill": false, "stroke": false})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().flare.is_none());
|
||||
assert!(s.execute("shape.editFlare", &json!({"rings": 3})).is_err());
|
||||
}
|
||||
|
||||
/// `shape.flare` reads whole-number counts written as floats, and refuses fractions.
|
||||
#[test]
|
||||
fn flare_counts_are_whole_numbers() {
|
||||
let mut s = session();
|
||||
let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 4.0, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
let g = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let rays = g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Rays")).unwrap();
|
||||
assert_eq!(rays.path_data().unwrap().subpaths.len(), 4);
|
||||
assert!(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 2.5})).is_err());
|
||||
}
|
||||
|
||||
/// `shape.editFlare` on a flare scaled far down: a `pathLength`, an end point or a center that,
|
||||
/// taken back to where the flare was drawn, is not a finite number is an error, and the flare keeps
|
||||
/// its settings.
|
||||
#[test]
|
||||
fn edit_flare_end_points_that_are_not_finite_are_errors() {
|
||||
let mut s = session();
|
||||
let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.scale", &json!({"sx": 1e-4, "sy": 1e-4})).unwrap();
|
||||
let before = flare_settings(&s.doc().unwrap().doc, id).expect("a flare");
|
||||
for (p, key) in [
|
||||
(json!({"pathLength": 1e305}), "x2"),
|
||||
(json!({"x2": 1e305, "y2": 0}), "x2"),
|
||||
(json!({"x2": 0, "y2": -1e305}), "y2"),
|
||||
(json!({"cx": 1e305, "cy": 0}), "cx"),
|
||||
] {
|
||||
let err = s.execute("shape.editFlare", &p).unwrap_err().to_string();
|
||||
assert!(err.ends_with(&format!("{key} must be a finite coordinate")), "{p}: {err}");
|
||||
assert_eq!(flare_settings(&s.doc().unwrap().doc, id).expect("still a flare"), before, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A flare drawn again keeps its parts' pixel-aligned property, whatever the document's Align New
|
||||
/// Objects to Pixel Grid is now, and a pixel-aligned flare that was moved is still a flare.
|
||||
#[test]
|
||||
fn edit_flare_keeps_its_parts_pixel_alignment() {
|
||||
let mut s = session();
|
||||
let aligned = |s: &Session, id: NodeId| -> Vec<bool> {
|
||||
s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|c| c.extras().pixel_aligned).collect()
|
||||
};
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
let on = NodeId(s.execute("shape.flare", &json!({"cx": 100.3, "cy": 200.6, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.move", &json!({"dx": 10.25, "dy": 3.5})).unwrap();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap();
|
||||
let part = |s: &Session, id: NodeId, name: &str| -> NodeId {
|
||||
s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).unwrap().id
|
||||
};
|
||||
let centre = part(&s, on, "Center");
|
||||
s.execute("shape.editFlare", &json!({"rings": 4})).unwrap();
|
||||
assert!(aligned(&s, on).len() > 4 && aligned(&s, on).iter().all(|a| *a));
|
||||
// Each part drawn again keeps its id and its own property: without the rays, the center does
|
||||
// not take theirs.
|
||||
assert_eq!(part(&s, on, "Center"), centre);
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [centre.0], "on": false})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [on.0]})).unwrap();
|
||||
s.execute("shape.editFlare", &json!({"rays": 0})).unwrap();
|
||||
let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned;
|
||||
assert!(!node(&s, centre) && node(&s, part(&s, on, "Halo")));
|
||||
let off = NodeId(s.execute("shape.flare", &json!({"cx": 300.3, "cy": 200.6, "rings": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
s.execute("shape.editFlare", &json!({"rings": 4})).unwrap();
|
||||
assert!(aligned(&s, off).iter().all(|a| !*a));
|
||||
}
|
||||
|
||||
/// `shape.flare`'s `ringSeed` places the rings along the path anew and keeps their count and
|
||||
/// sizes and the other parts; the same `ringSeed` draws the same flare, neighboring ones differ,
|
||||
/// and a seed that is not a whole number of at least 0 (for `ringSeed`, below 2^53) is refused.
|
||||
@@ -3453,6 +3596,38 @@ fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() {
|
||||
assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}");
|
||||
}
|
||||
|
||||
/// A flare drawn with a small `ringSeed` and then drawn again by `shape.editFlare` keeps its first
|
||||
/// ring where `shape.flare` put it: the SplitMix64-initialized Xorshift64 stream's first value
|
||||
/// along the path, for each seed.
|
||||
#[test]
|
||||
fn edit_flare_draws_the_first_ring_of_a_small_ring_seed_where_it_was() {
|
||||
let first_t = |seed: u64| {
|
||||
let mut z = seed.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
let mut state = z ^ (z >> 31);
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
};
|
||||
let ring_x = |s: &Session, id: NodeId| {
|
||||
let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") };
|
||||
children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap().geometric_bounds().unwrap().center().x
|
||||
};
|
||||
let mut s = session();
|
||||
for seed in [0, 1, 2, 5, 11] {
|
||||
let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed});
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let expected = 20.0 + 1000.0 * first_t(seed);
|
||||
assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: drawn at {}, expected {expected}", ring_x(&s, id));
|
||||
s.execute("shape.editFlare", &json!({"ids": [id.0], "opacity": 80})).unwrap();
|
||||
assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: drawn again at {}, expected {expected}", ring_x(&s, id));
|
||||
s.execute("shape.editFlare", &json!({"ids": [id.0], "opacity": 40})).unwrap();
|
||||
assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: a second edit keeps the ring");
|
||||
}
|
||||
}
|
||||
|
||||
/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew.
|
||||
#[test]
|
||||
fn ellipse_with_four_anchors_is_the_live_ellipse() {
|
||||
|
||||
@@ -176,3 +176,61 @@ fn a_handle_already_in_place_on_a_smooth_anchor_records_no_undo_step() {
|
||||
.unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
}
|
||||
|
||||
/// `path.setHandle` with `link` makes a corner smooth: the other handle turns in line at its own
|
||||
/// length, a retracted one is pulled out to the moved handle's length where a segment leaves the
|
||||
/// anchor on its side and stays retracted at an open end. A handle already in place on a corner
|
||||
/// still links; a request that changes nothing records no undo step; `link` that is not a boolean
|
||||
/// or goes with `independent` is refused.
|
||||
#[test]
|
||||
fn a_linked_handle_makes_the_anchor_smooth() {
|
||||
let (mut s, id) = long_path(100);
|
||||
let p = anchor(&s, id, 5).p;
|
||||
let corner = Anchor { p, h_in: p + Vec2::new(-6.0, 8.0), h_out: p + Vec2::new(3.0, 0.0), kind: AnchorKind::Corner };
|
||||
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
|
||||
path.subpaths[0].anchors[5] = corner;
|
||||
let link = |x: f64, y: f64, ai: usize| json!({"id": id.0, "anchor": ai, "which": "out", "x": x, "y": y, "link": true});
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
|
||||
// The out handle stays where it is; the corner becomes smooth, the in handle turned opposite it.
|
||||
s.execute("path.setHandle", &link(corner.h_out.x, corner.h_out.y, 5)).unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
let a = anchor(&s, id, 5);
|
||||
assert_eq!((a.kind, a.h_out), (AnchorKind::Smooth, corner.h_out));
|
||||
assert!(near(a.h_in, p + Vec2::new(-10.0, 0.0)), "{a:?}");
|
||||
// Moved: the in handle keeps its length of 10.
|
||||
let to = p + Vec2::new(4.0, 3.0);
|
||||
s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap();
|
||||
assert_eq!(undo_steps(&s), 2);
|
||||
let a = anchor(&s, id, 5);
|
||||
assert!(a.kind == AnchorKind::Smooth && a.h_out == to && near(a.h_in, p + Vec2::new(-8.0, -6.0)), "{a:?}");
|
||||
// The same request again changes nothing.
|
||||
s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap();
|
||||
assert_eq!(undo_steps(&s), 2);
|
||||
|
||||
// A retracted in handle on an inner anchor is pulled out; at the open start it stays retracted.
|
||||
let q = anchor(&s, id, 7).p;
|
||||
s.execute("path.setHandle", &link(q.x, q.y + 5.0, 7)).unwrap();
|
||||
let a = anchor(&s, id, 7);
|
||||
assert!(a.kind == AnchorKind::Smooth && near(a.h_in, q + Vec2::new(0.0, -5.0)), "{a:?}");
|
||||
let q = anchor(&s, id, 0).p;
|
||||
s.execute("path.setHandle", &link(q.x, q.y + 5.0, 0)).unwrap();
|
||||
let a = anchor(&s, id, 0);
|
||||
assert!(a.kind == AnchorKind::Smooth && a.h_in == q && a.h_out == q + Vec2::new(0.0, 5.0), "{a:?}");
|
||||
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = undo_steps(&s);
|
||||
for bad in [
|
||||
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": "yes"}),
|
||||
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}),
|
||||
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}),
|
||||
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}),
|
||||
json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}),
|
||||
json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}),
|
||||
json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}),
|
||||
] {
|
||||
assert!(s.execute("path.setHandle", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before, "a refused request changed the document");
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
}
|
||||
@@ -90,6 +90,23 @@ fn values_that_differ_read_null_and_recent_urls_keep_the_newest_first() {
|
||||
assert_eq!(info(&mut s, json!({"ids": [p.0, a.0]}))["showCenter"], Value::Null);
|
||||
}
|
||||
|
||||
/// The recent URLs keep the 30 newest distinct URLs, the most the panel's URL menu can list, and
|
||||
/// a URL given again moves to the front without taking a second place.
|
||||
#[test]
|
||||
fn recent_urls_keep_the_thirty_newest() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0);
|
||||
for i in 0..35 {
|
||||
run(&mut s, "attributes.set", json!({"url": format!("https://example.com/{i}")}));
|
||||
}
|
||||
let want: Vec<String> = (5..35).rev().map(|i| format!("https://example.com/{i}")).collect();
|
||||
assert_eq!(info(&mut s, json!({}))["recentUrls"], json!(want));
|
||||
run(&mut s, "attributes.set", json!({"url": "https://example.com/20"}));
|
||||
let urls = info(&mut s, json!({}))["recentUrls"].as_array().unwrap().clone();
|
||||
assert_eq!((urls.len(), urls[0].as_str(), urls[1].as_str()), (30, Some("https://example.com/20"), Some("https://example.com/34")));
|
||||
assert_eq!(urls.iter().filter(|u| *u == "https://example.com/20").count(), 1);
|
||||
}
|
||||
|
||||
/// A five-pointed star drawn as one self-intersecting path (its centre is wound twice).
|
||||
fn star(s: &mut Session) -> NodeId {
|
||||
let (c, r) = (50.0f64, 45.0f64);
|
||||
|
||||
@@ -431,3 +431,35 @@ fn a_spine_segment_bends_with_perpendicular_handles() {
|
||||
use vectorcraft_geom::kurbo::ParamCurve;
|
||||
assert!(sp.segment(0).eval(0.5).distance(Point::new(55.0, 45.0)) < 1e-9, "{sp:?}");
|
||||
}
|
||||
|
||||
/// `link` with `handle` makes a spine point smooth, the other handle in line opposite the moved
|
||||
/// one, without moving the keys; the same request again records no undo step, and `link` that is
|
||||
/// not a boolean, goes with `independent` or comes without `handle` is refused.
|
||||
#[test]
|
||||
fn a_linked_spine_handle_makes_the_point_smooth() {
|
||||
let mut s = session();
|
||||
let (_, _, g) = blend(&mut s);
|
||||
s.execute("object.blend.spine.addAnchor", &json!({"x": 55, "y": 5})).unwrap();
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let link = json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true});
|
||||
s.execute("object.blend.spine.moveAnchor", &link).unwrap();
|
||||
let a = spec(&s, g).spine.unwrap().subpaths[0].anchors[1];
|
||||
assert_eq!((a.kind, a.h_out), (vectorcraft_geom::AnchorKind::Smooth, Point::new(75.0, 25.0)));
|
||||
let (din, dout) = (a.h_in - a.p, a.h_out - a.p);
|
||||
assert!(din.hypot() > 1e-6 && (din.normalize() + dout.normalize()).hypot() < 1e-9, "{a:?}");
|
||||
let st = steps(&s, g);
|
||||
assert_eq!((center(&st[0]), center(&st[2])), (Point::new(5.0, 5.0), Point::new(105.0, 5.0)), "the keys stay put");
|
||||
let done = undo(&s);
|
||||
s.execute("object.blend.spine.moveAnchor", &link).unwrap();
|
||||
assert_eq!(undo(&s), done, "an unchanged spine recorded an undo step");
|
||||
let before = spec(&s, g);
|
||||
for bad in [
|
||||
json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}),
|
||||
json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}),
|
||||
json!({"anchor": 1, "x": 75, "y": 25, "link": true}),
|
||||
] {
|
||||
assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(spec(&s, g), before);
|
||||
assert_eq!(undo(&s), done);
|
||||
}
|
||||
@@ -117,7 +117,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"game-trails",
|
||||
"energy-beams",
|
||||
"dry-media",
|
||||
"tech-circuit"
|
||||
"tech-circuit",
|
||||
"arrows"
|
||||
]
|
||||
);
|
||||
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
|
||||
@@ -145,6 +146,12 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
|
||||
);
|
||||
assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"}));
|
||||
assert_eq!(
|
||||
arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
|
||||
[("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")]
|
||||
);
|
||||
assert_eq!((libs[11]["name"].as_str(), libs[11]["count"].as_u64()), (Some("Arrows"), Some(5)));
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
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]}));
|
||||
@@ -162,6 +169,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
("game-trails", "art"),
|
||||
("energy-beams", "art"),
|
||||
("dry-media", "art"),
|
||||
("arrows", "art"),
|
||||
] {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.len() >= 4, "{id}");
|
||||
@@ -220,6 +228,78 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer {
|
||||
vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_library_lists_renders_and_applies_original_brushes() {
|
||||
let mut s = session();
|
||||
let listed = run(&mut s, "brush.libraries", json!({}));
|
||||
let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "arrows").unwrap();
|
||||
assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Arrows"), Some("builtIn"), Some(5)));
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
|
||||
assert_eq!(
|
||||
lib.brushes.iter().map(|b| (b.name.as_str(), b.kind.type_id())).collect::<Vec<_>>(),
|
||||
[("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")]
|
||||
);
|
||||
for b in &lib.brushes {
|
||||
for length in [2.0, 200.0] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
|
||||
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name);
|
||||
}
|
||||
}
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap();
|
||||
let before = undo_len(&s);
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Double Arrow", "apply": true, "ids": [path]}));
|
||||
assert_eq!(strs(&added["added"]), ["Double Arrow"]);
|
||||
assert_eq!(added["applied"], json!([path]));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some("Double Arrow"));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(vectorcraft_brush::find(doc(&s), "Double Arrow").is_none());
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(brush(&s, "Double Arrow"), lib.brushes[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_chevron_arrows_second_chevron_keeps_its_length_on_a_long_path() {
|
||||
let s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
|
||||
let b = lib.brush("Chevron Arrow").unwrap();
|
||||
let widths = |length: f64| {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
|
||||
let children = pieces[0].children().unwrap();
|
||||
assert_eq!(children.len(), 3, "shaft, head and second chevron");
|
||||
children[1..].iter().map(|n| n.geometric_bounds().unwrap().width()).collect::<Vec<_>>()
|
||||
};
|
||||
let short = widths(100.0);
|
||||
for (long, short) in widths(400.0).into_iter().zip(short) {
|
||||
assert!((long - short).abs() < 1e-6, "the heads keep their length: {long} on 400 pt, {short} on 100 pt");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashed_arrow_keeps_separate_dashes_and_survives_library_save() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap();
|
||||
let b = lib.brush("Dashed Arrow").unwrap();
|
||||
let mut curve = line_to(40.0);
|
||||
curve.curve_to((60.0, -40.0), (140.0, 40.0), (200.0, 0.0));
|
||||
for path in [line_to(2.0), line_to(200.0), curve] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke());
|
||||
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
|
||||
}
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(200.0), &black_stroke());
|
||||
let children = pieces[0].children().unwrap();
|
||||
assert_eq!(children.len(), 6, "five separate dashes and one head");
|
||||
let bounds: Vec<_> = children.iter().map(|n| n.geometric_bounds().unwrap()).collect();
|
||||
assert!(bounds.windows(2).all(|p| p[0].x1 < p[1].x0), "the dashes and head remain separated");
|
||||
run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Dashed Arrow"}));
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Dashed Arrow"]}));
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let reopened = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(vectorcraft_brush::find(&reopened, "Dashed Arrow").unwrap(), *b);
|
||||
}
|
||||
|
||||
/// Original circuit art and repeat tiles survive adding, applying and saving a library.
|
||||
#[test]
|
||||
fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
|
||||
|
||||
@@ -326,9 +326,11 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() {
|
||||
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap()
|
||||
};
|
||||
// Reopened existing links use native separators; missing links keep their stored path.
|
||||
let red = dir.0.join("art").join("red.png").to_string_lossy().into_owned();
|
||||
let person = report(&run(&mut s, "file.package", json!({})));
|
||||
assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}");
|
||||
assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}");
|
||||
assert!(person.contains(&format!("{red} → Links/red.png")), "{person}");
|
||||
assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}");
|
||||
|
||||
let in_root = dir.0.join("in");
|
||||
@@ -339,16 +341,19 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() {
|
||||
assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}");
|
||||
let base = dir.0.to_string_lossy().into_owned();
|
||||
assert!(!text.contains(&base), "{text}");
|
||||
// Compare serialized JSON with the path encoded the same way, without its outer quotes.
|
||||
let json_base = serde_json::to_string(&base).unwrap();
|
||||
let json_base = &json_base[1..json_base.len() - 1];
|
||||
for key in ["missingLinks", "warnings", "files"] {
|
||||
assert!(!client[key].to_string().contains(&base), "{key}: {client}");
|
||||
assert!(!client[key].to_string().contains(json_base), "{key}: {client}");
|
||||
}
|
||||
// Document Info, whose report the package holds, gives no link either.
|
||||
for p in [json!({}), json!({"format": "text"})] {
|
||||
let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone()));
|
||||
assert!(!info.to_string().contains(&base), "{p}: {info}");
|
||||
assert!(!info.to_string().contains(json_base), "{p}: {info}");
|
||||
}
|
||||
let info = run(&mut s, "document.info", json!({"format": "text"}));
|
||||
assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}");
|
||||
assert!(info["text"].as_str().unwrap().contains(&red), "the person's: {info}");
|
||||
}
|
||||
|
||||
/// A confined request packages no document that links, or places a native document or a PDF with
|
||||
|
||||
@@ -1121,6 +1121,10 @@ fn path_commands_refuse_a_param_of_the_wrong_type() {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.1 in", "joins": "Bevel"})).unwrap());
|
||||
assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0]));
|
||||
// A product with a unit, which the offset used to refuse: 0.05x2 in is 0.1 in.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.05x2 in", "joins": "Bevel"})).unwrap());
|
||||
assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0]));
|
||||
// Null switches keep Clean Up's defaults, which remove the stray point.
|
||||
let r = s.execute("object.path.cleanUp", &json!({"strayPoints": null, "unpaintedObjects": null, "emptyTextPaths": null})).unwrap();
|
||||
assert_eq!(r["removed"], 1);
|
||||
|
||||
@@ -176,3 +176,24 @@ fn a_file_over_the_limit_is_refused_before_it_is_parsed() {
|
||||
assert!(s.execute("prefs.import", &json!({"path": missing.to_string_lossy()})).is_err());
|
||||
assert_eq!(s.prefs.to_json().to_string(), before);
|
||||
}
|
||||
|
||||
/// Hold Shortcuts is off by default. The Hold Shortcut Delay takes 0.2 to 1.0 s and refuses other
|
||||
/// values; a value from a settings file outside the range is brought inside it.
|
||||
#[test]
|
||||
fn hold_shortcut_preferences() {
|
||||
let mut s = Session::new();
|
||||
assert!(!s.prefs.hold_shortcuts);
|
||||
assert_eq!(s.prefs.key_hold_delay(), 0.35);
|
||||
for ok in [0.2, 1.0] {
|
||||
s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": ok})).unwrap();
|
||||
assert_eq!(s.prefs.key_hold_delay(), ok);
|
||||
}
|
||||
for bad in [0.1, 1.5] {
|
||||
assert!(is_bad_params(s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": bad}))), "{bad}");
|
||||
}
|
||||
s.execute("prefs.set", &json!({"key": "holdShortcuts", "value": true})).unwrap();
|
||||
assert!(s.prefs.hold_shortcuts);
|
||||
let restored: Prefs = serde_json::from_value(json!({"keyHoldDelay": 5.0})).unwrap();
|
||||
assert_eq!(restored.key_hold_delay(), 1.0);
|
||||
assert!(!restored.hold_shortcuts);
|
||||
}
|
||||
@@ -1012,6 +1012,8 @@ fn structured_junk() {
|
||||
("addon.pathtools.bridge", json!({"radius": 1e-308, "keepOriginals": "x"})),
|
||||
("addon.pathtools.bridge", json!({"radius": 1000, "keepOriginals": true, "ids": [0, 1, 2, 3, u64::MAX]})),
|
||||
("addon.pathtools.bridge", json!({"radius": f64::MAX, "ids": [1, 1], "junk": [0]})),
|
||||
("addon.pathtools.bridge", json!({"gap": -1e308, "reach": f64::MAX, "ids": [0, 1, 2]})),
|
||||
("addon.pathtools.bridge", json!({"gap": 1000, "reach": 10000, "radius": null, "keepOriginals": true})),
|
||||
// Refused before anything is written: no format of that name, a time that is no time.
|
||||
("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})),
|
||||
("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})),
|
||||
|
||||
@@ -123,11 +123,13 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
// A group holding only clipping paths (`q … u <path> W n U … Q`) doesn't clip on its own: `u`/`U` don't save
|
||||
// the graphics state as `q`/`Q` do, so its paths clip the clipping group around it, as the file's PDF part draws it.
|
||||
// In a compound path (`*u u <path> W n … U *U`, possibly nested in other groups) they are the compound
|
||||
// path's subpaths, as its other grouped paths are: the compound clipping path, their union.
|
||||
if matches!(kind, Kind::Group)
|
||||
&& unread.is_empty()
|
||||
&& !clips.is_empty()
|
||||
&& clips.len() == kids.len()
|
||||
&& matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. }))
|
||||
&& (matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) || self.in_compound())
|
||||
{
|
||||
for kid in kids {
|
||||
if let Some(parent) = self.frames.last_mut() {
|
||||
@@ -212,6 +214,18 @@ impl<'a> Reader<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Is the innermost open frame a compound path (`*u`), or a group in one with only groups between them?
|
||||
fn in_compound(&self) -> bool {
|
||||
for f in self.frames.iter().rev() {
|
||||
match f.kind {
|
||||
Kind::Group => {}
|
||||
Kind::Compound => return true,
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The compound path of `kids`, painted and made transparent as its subpaths say.
|
||||
fn compound(&mut self, mut kids: Vec<Node>, gs: &GState) -> Option<Node> {
|
||||
// The compound path's paint is its last path's (a gradient's instance wraps only
|
||||
|
||||
@@ -1734,6 +1734,42 @@ fn a_clipping_path_alone_in_a_group_clips_its_clipping_group() {
|
||||
assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
}
|
||||
|
||||
/// Clipping paths grouped in a compound path (`*u u <path> W n … U *U`, possibly nested in other groups) are
|
||||
/// the compound path's subpaths, as its other grouped paths are: the compound clipping path, their union, clips its
|
||||
/// clipping group, however many there are and wherever in the group it is written.
|
||||
#[test]
|
||||
fn clipping_paths_grouped_in_a_compound_path_are_its_subpaths() {
|
||||
let square = rect_path(0.0, 0.0, 80.0, 80.0);
|
||||
let (a, b, c) = (rect_path(0.0, 0.0, 10.0, 10.0), rect_path(30.0, 0.0, 40.0, 10.0), rect_path(60.0, 0.0, 70.0, 10.0));
|
||||
let clip = |p: &str| format!("{p}h\nW\nn\n");
|
||||
let bodies = [
|
||||
// One group of them, after the art.
|
||||
format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}{}{}U\n*U\nQ\n", clip(&a), clip(&b), clip(&c)),
|
||||
// Groups in a group, and one path straight in the compound path, before the art.
|
||||
format!("0 Ae\nq\n*u\n0 Ae\nu\n0 Ae\nu\n{}{}U\n0 Ae\nu\n{}U\nU\n*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)),
|
||||
format!("0 Ae\nq\n*u\n0 Ae\nu\n{}{}U\n{}*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)),
|
||||
];
|
||||
for body in &bodies {
|
||||
let doc = read_ok(&layer(body)).doc;
|
||||
let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{body}: {:?}", art(&doc)[0].kind) };
|
||||
assert_eq!(children.len(), 2, "{body}: {children:?}");
|
||||
let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{body}: {:?}", children[0].kind) };
|
||||
assert_eq!(subpaths.len(), 3, "{body}: {subpaths:?}");
|
||||
assert!(subpaths.iter().all(|p| matches!(p.kind, NodeKind::Path { clipping: true, .. })), "{body}: {subpaths:?}");
|
||||
assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "{body}");
|
||||
}
|
||||
// Hundreds of them, one union: not clipping groups nested past the document's depth limit.
|
||||
let many = format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}U\n*U\nQ\n", clip(&a).repeat(300));
|
||||
let doc = read_ok(&layer(&many)).doc;
|
||||
let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) };
|
||||
let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) };
|
||||
assert_eq!(subpaths.len(), 300);
|
||||
// A group of clipping paths outside a compound path or a clipping group is read as before: a clipping group.
|
||||
let alone = format!("0 Ae\nu\n{}{}U\n{RED}{square}f\n", clip(&a), clip(&b));
|
||||
let doc = read_ok(&layer(&alone)).doc;
|
||||
assert!(matches!(art(&doc)[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", art(&doc)[0].kind);
|
||||
}
|
||||
|
||||
/// #1410: a compound path shows its last path's paint, and paths grouped in it stay its paths.
|
||||
#[test]
|
||||
fn compound_path_takes_its_last_paths_paint() {
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
//! are on disk, and the error names them. Where that copy of the old file can't be made, the file
|
||||
//! is left as it was and the save fails.
|
||||
//!
|
||||
//! Work canceled ([`vectorcraft_doc::cancel`]) by the time the temporary file is written and flushed
|
||||
//! puts nothing in place: the temporary file is removed, the file stays as it was (or absent), and
|
||||
//! the error wraps [`vectorcraft_doc::cancel::Cancelled`].
|
||||
//!
|
||||
//! On macOS `File::sync_all` is a full flush (`F_FULLFSYNC`), which SMB shares refuse with
|
||||
//! `ENOTSUP` and virtiofs shares (folders shared into a macOS VM) with `ENOTTY`, while a plain
|
||||
//! `fsync` works: [`sync_file`] falls back to the plain one there (#1620).
|
||||
@@ -43,7 +47,8 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// Write `path` atomically with `fill`, which writes the content into the temporary file. When
|
||||
/// `fill` or flushing fails the temporary file is removed and `path` is left untouched. When the
|
||||
/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the
|
||||
/// temporary file is removed and `path` is left untouched. When the
|
||||
/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see
|
||||
/// the module docs).
|
||||
pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
|
||||
@@ -79,7 +84,7 @@ fn write_atomic_stepping(
|
||||
(tmp, f, Some(e))
|
||||
}
|
||||
};
|
||||
let filled = fill(&mut f).and_then(|()| sync_file(&f));
|
||||
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
|
||||
drop(f);
|
||||
if let Err(e) = filled {
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
@@ -176,7 +181,7 @@ fn write_new_linking(
|
||||
) -> io::Result<()> {
|
||||
let tmp = temp_path(path)?;
|
||||
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
let filled = fill(&mut f).and_then(|()| sync_file(&f));
|
||||
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
|
||||
drop(f);
|
||||
let placed = filled.and_then(|()| match link(&tmp, path) {
|
||||
Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(&tmp, path),
|
||||
@@ -187,6 +192,12 @@ fn write_new_linking(
|
||||
placed
|
||||
}
|
||||
|
||||
/// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has
|
||||
/// been canceled: the last check before a written temporary file is put in place.
|
||||
fn not_cancelled() -> io::Result<()> {
|
||||
vectorcraft_doc::cancel::check().map_err(io::Error::other)
|
||||
}
|
||||
|
||||
/// Create `path` (never replacing anything) with the content of the file `from`; a failed copy
|
||||
/// removes it again.
|
||||
fn copy_new(from: &Path, path: &Path) -> io::Result<()> {
|
||||
@@ -408,6 +419,39 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// Work canceled by the time the temporary file is written and flushed puts nothing in place:
|
||||
/// the old file stays as it was, also where the folder refuses the rename (no copy over it), a
|
||||
/// new file is not created, and no temporary file is left.
|
||||
#[test]
|
||||
fn canceled_work_puts_nothing_in_place() {
|
||||
use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope};
|
||||
fn cancelled(e: &io::Error) -> bool {
|
||||
e.get_ref().is_some_and(|e| e.is::<Cancelled>())
|
||||
}
|
||||
let d = dir("cancel");
|
||||
let path = d.join("doc.vectorcraft");
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
let token = CancelToken::new();
|
||||
let r = scope(&token, None, || {
|
||||
write_atomic_with(&path, |f| {
|
||||
f.write_all(b"new")?;
|
||||
token.cancel();
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(r.as_ref().is_err_and(cancelled), "{r:?}");
|
||||
let refused = |_: &Path, _: &Path| -> io::Result<()> { Err(io::Error::from(io::ErrorKind::PermissionDenied)) };
|
||||
let r = scope(&token, None, || write_atomic_stepping(&path, |f| f.write_all(b"new"), create_new, refused));
|
||||
assert!(r.as_ref().is_err_and(cancelled), "{r:?}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
let new = d.join("new.vectorcraft");
|
||||
let r = scope(&token, None, || write_new_with(&new, |f| f.write_all(b"new")));
|
||||
assert!(r.as_ref().is_err_and(cancelled), "{r:?}");
|
||||
assert!(!new.exists());
|
||||
assert!(leftovers(&d, "doc.vectorcraft").is_empty(), "{:?}", leftovers(&d, "doc.vectorcraft"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_original_file_survives_a_failed_write() {
|
||||
let d = dir("fail");
|
||||
|
||||
+121
-1
@@ -158,10 +158,56 @@ impl Anchor {
|
||||
let dir = p - pos;
|
||||
let l = dir.hypot();
|
||||
if l > 1e-9 {
|
||||
*other = p + dir * (len / l);
|
||||
let turned = p + dir * (len / l);
|
||||
if turned.is_finite() {
|
||||
*other = turned;
|
||||
} else {
|
||||
// Long handles overflow the squares above: measure with `f64::hypot` and scale
|
||||
// the unit direction, leaving the handle where it is if that is not finite.
|
||||
let (v, l) = (*other - p, dir.x.hypot(dir.y));
|
||||
let turned = p + (dir / l) * v.x.hypot(v.y);
|
||||
if turned.is_finite() {
|
||||
*other = turned;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Place the end of the outgoing (`out`) or incoming handle at `pos` and make the anchor smooth:
|
||||
/// the other handle turns to lie in line with it on the far side of the anchor, at its own
|
||||
/// length. A retracted other handle is pulled out to the moved handle's length when `pull_out`
|
||||
/// and stays retracted otherwise. A handle placed on the anchor, or where the turned handle's
|
||||
/// end would not be a finite point, gives no direction: it is placed, and the other handle and
|
||||
/// the anchor's kind stay as they are.
|
||||
pub fn link_handle(&mut self, out: bool, pos: Point, pull_out: bool) {
|
||||
let p = self.p;
|
||||
let (moved, other) = if out { (&mut self.h_out, &mut self.h_in) } else { (&mut self.h_in, &mut self.h_out) };
|
||||
*moved = pos;
|
||||
// `f64::hypot` keeps long handles from overflowing the square of their length.
|
||||
let dir = p - pos;
|
||||
let l = dir.x.hypot(dir.y);
|
||||
if !(l > EPS && l.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let v = *other - p;
|
||||
let len = v.x.hypot(v.y);
|
||||
let len = if len > EPS {
|
||||
len
|
||||
} else if pull_out {
|
||||
l
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if len > 0.0 {
|
||||
// The unit direction first, so a short handle does not overflow the scale factor.
|
||||
let turned = p + (dir / l) * len;
|
||||
if !turned.is_finite() {
|
||||
return;
|
||||
}
|
||||
*other = turned;
|
||||
}
|
||||
self.kind = AnchorKind::Smooth;
|
||||
}
|
||||
/// Swap handles (used when reversing path direction).
|
||||
pub fn reversed(&self) -> Self {
|
||||
Self { p: self.p, h_in: self.h_out, h_out: self.h_in, kind: self.kind }
|
||||
@@ -280,6 +326,11 @@ impl SubPath {
|
||||
pub fn polyline(points: &[Point], closed: bool) -> Self {
|
||||
Self { anchors: points.iter().map(|&p| Anchor::corner(p)).collect(), closed }
|
||||
}
|
||||
/// Whether anchor `ai` has a segment on its outgoing (`out`) or incoming side.
|
||||
pub fn has_segment(&self, ai: usize, out: bool) -> bool {
|
||||
let n = self.anchors.len();
|
||||
ai < n && n > 1 && (self.closed || if out { ai + 1 < n } else { ai > 0 })
|
||||
}
|
||||
/// Number of segments (a closed path has one more, back to the start).
|
||||
pub fn segment_count(&self) -> usize {
|
||||
let n = self.anchors.len();
|
||||
@@ -1103,4 +1154,73 @@ mod tests {
|
||||
let back: PathData = serde_json::from_str(&s).unwrap();
|
||||
assert_eq!(p, back);
|
||||
}
|
||||
|
||||
/// `link_handle` makes a corner smooth: the other handle turns onto the far side of the anchor
|
||||
/// at its own length; a retracted one is pulled out to the moved handle's length only when
|
||||
/// asked, and a handle placed on the anchor changes nothing else.
|
||||
#[test]
|
||||
fn link_handle_makes_a_corner_smooth_keeping_the_other_length() {
|
||||
let p = Point::new(10.0, 10.0);
|
||||
let mut a = Anchor { p, h_in: Point::new(10.0, 0.0), h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner };
|
||||
a.link_handle(true, Point::new(14.0, 13.0), false);
|
||||
assert_eq!(a.kind, AnchorKind::Smooth);
|
||||
assert_eq!(a.h_out, Point::new(14.0, 13.0));
|
||||
// The in handle keeps its length of 10, opposite the out handle's direction (4, 3) / 5.
|
||||
assert!(a.h_in.distance(Point::new(2.0, 4.0)) < 1e-9, "{:?}", a.h_in);
|
||||
|
||||
let retracted = Anchor { p, h_in: p, h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner };
|
||||
let mut pulled = retracted;
|
||||
pulled.link_handle(true, Point::new(13.0, 14.0), true);
|
||||
assert_eq!((pulled.kind, pulled.h_in), (AnchorKind::Smooth, Point::new(7.0, 6.0)));
|
||||
let mut kept = retracted;
|
||||
kept.link_handle(true, Point::new(13.0, 14.0), false);
|
||||
assert_eq!((kept.kind, kept.h_in), (AnchorKind::Smooth, p));
|
||||
|
||||
let mut on_anchor = Anchor { p, h_in: Point::new(10.0, 0.0), h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner };
|
||||
on_anchor.link_handle(false, p, true);
|
||||
assert_eq!(on_anchor, Anchor { p, h_in: p, h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner });
|
||||
|
||||
// A handle so far away that its distance overflows leaves the other handle finite.
|
||||
let far = Point::new(1.7e308, 1.7e308);
|
||||
let mut overflow = retracted;
|
||||
overflow.link_handle(true, far, true);
|
||||
assert_eq!(overflow, Anchor { p, h_in: p, h_out: far, kind: AnchorKind::Corner });
|
||||
// A very long other handle turned by a very short one stays finite, at its own length.
|
||||
let mut long = Anchor { p: Point::ZERO, h_in: Point::new(1e308, 0.0), h_out: Point::ZERO, kind: AnchorKind::Corner };
|
||||
long.link_handle(true, Point::new(0.0, 1e-8), false);
|
||||
assert_eq!((long.kind, long.h_in), (AnchorKind::Smooth, Point::new(0.0, -1e308)));
|
||||
// One whose turned end would leave the finite range is left where it is.
|
||||
let edge = Point::new(-1.5e308, 0.0);
|
||||
let mut beyond = Anchor { p: edge, h_in: Point::new(1.5e308, 0.0), h_out: edge, kind: AnchorKind::Corner };
|
||||
beyond.link_handle(true, Point::new(-1.5e308 + 1e300, 0.0), false);
|
||||
assert_eq!((beyond.kind, beyond.h_in), (AnchorKind::Corner, Point::new(1.5e308, 0.0)));
|
||||
}
|
||||
|
||||
/// `set_handle` on a smooth anchor turns a very long other handle without overflowing, and
|
||||
/// leaves it where it is when its turned end would not be a finite point.
|
||||
#[test]
|
||||
fn set_handle_on_a_smooth_anchor_keeps_long_handles_finite() {
|
||||
let mut long = Anchor { p: Point::ZERO, h_in: Point::new(-1e308, 0.0), h_out: Point::new(1.0, 0.0), kind: AnchorKind::Smooth };
|
||||
long.set_handle(true, Point::new(0.0, 1e-8), false);
|
||||
assert_eq!(long.h_in, Point::new(0.0, -1e308));
|
||||
let edge = Point::new(-1.5e308, 0.0);
|
||||
let mut beyond = Anchor { p: edge, h_in: Point::new(-1.6e308, 0.0), h_out: Point::new(1.5e308, 0.0), kind: AnchorKind::Smooth };
|
||||
beyond.set_handle(false, Point::new(-1.5e308 + 1e300, 0.0), false);
|
||||
assert_eq!(beyond.h_out, Point::new(1.5e308, 0.0));
|
||||
}
|
||||
|
||||
/// `has_segment` sees a segment on each side of an inner anchor, none past an open path's ends,
|
||||
/// and both sides on a closed path of two anchors or more.
|
||||
#[test]
|
||||
fn has_segment_follows_the_open_ends() {
|
||||
let pts = [Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)];
|
||||
let open = SubPath::polyline(&pts, false);
|
||||
assert!(!open.has_segment(0, false) && open.has_segment(0, true));
|
||||
assert!(open.has_segment(1, false) && open.has_segment(1, true));
|
||||
assert!(open.has_segment(2, false) && !open.has_segment(2, true));
|
||||
assert!(!open.has_segment(3, false));
|
||||
let closed = SubPath::polyline(&pts, true);
|
||||
assert!(closed.has_segment(0, false) && closed.has_segment(2, true));
|
||||
assert!(!SubPath::polyline(&pts[..1], true).has_segment(0, true));
|
||||
}
|
||||
}
|
||||
@@ -323,6 +323,7 @@ fn headless_command_list_includes_ui_commands() {
|
||||
"app.quit",
|
||||
"window.arrange.tile",
|
||||
"align.horizontalLeft",
|
||||
"align.toKeyObject",
|
||||
"ui.action.play",
|
||||
];
|
||||
for (n, id) in want.iter().enumerate() {
|
||||
|
||||
@@ -190,8 +190,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"Cmd+I",
|
||||
"{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options",
|
||||
),
|
||||
("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:<id>, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"),
|
||||
("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"),
|
||||
(
|
||||
"shortcuts.set",
|
||||
"Set Keyboard Shortcut",
|
||||
"",
|
||||
"{id: command id or tool:<id>, shortcut?: \"Cmd+Shift+K\" | \"\" (none) | null (default), hold?: a character key alone or with Shift (\"X\", \"Shift+X\", \".\") | \"\" | null (none), force?} → {id, shortcut, hold, removedFrom}; `hold` alone leaves the shortcut as it is; a command listed only with a shortcut takes a hold only with one and loses it with the shortcut; a hold shortcut acts while the holdShortcuts preference is on",
|
||||
),
|
||||
("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, hold, default, overridden}]"),
|
||||
("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"),
|
||||
("shortcuts.reset", "Reset Keyboard Shortcuts", "", "{}"),
|
||||
(
|
||||
@@ -205,7 +210,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"shortcuts.exportText",
|
||||
"Export Keyboard Shortcuts as Text…",
|
||||
"",
|
||||
"{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `name<TAB>shortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error",
|
||||
"{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `name<TAB>shortcut` line per row, empty after the tab when it has none, and while the holdShortcuts preference is on a third `Hold <key>` column on a row with a hold shortcut. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error",
|
||||
),
|
||||
("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"),
|
||||
(
|
||||
@@ -380,6 +385,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"",
|
||||
),
|
||||
(
|
||||
"align.toSelection",
|
||||
"Align to Selection",
|
||||
"",
|
||||
"{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected, since one object aligns to the artboard}; with the Artboard tool chosen the selected objects keep their key",
|
||||
),
|
||||
(
|
||||
"align.toKeyObject",
|
||||
"Align to Key Object",
|
||||
"",
|
||||
"{} the Align panel's Align to Key Object button: with no key, the topmost of two or more selected objects becomes the key object, or a ruler guide selected with one object the key guide; the stored Selection or Artboard choice stays → {alignTo: \"key\"}; an error (\"no key object\") when there is no key and nothing to make one of, which includes a topmost selected object inside another selected object; an error (\"Align to Key Object isn't available with the Artboard tool\") with the Artboard tool chosen",
|
||||
),
|
||||
(
|
||||
"align.toArtboard",
|
||||
"Align to Artboard",
|
||||
"",
|
||||
"{} the Align panel's Align to Artboard button: Align To becomes Artboard (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: \"artboard\"}; with the Artboard tool chosen the selected objects keep their key",
|
||||
),
|
||||
(
|
||||
"type.bold",
|
||||
"Bold",
|
||||
@@ -422,6 +445,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"Cmd+Shift+U",
|
||||
"{} the Character panel's Underline button: underline the selected type (or the Type tool's selection), or remove the underline when the text the Character panel shows is underlined (text.setFormat {underline}) → underlined",
|
||||
),
|
||||
(
|
||||
"type.superscript",
|
||||
"Superscript",
|
||||
"Cmd+Shift+=",
|
||||
"{} the Character panel's Superscript button: the selected type (or the Type tool's selection, all of its text at a caret) becomes superscript, or Normal when all of it is superscript already (text.setFormat {position}). Without selected type the keys zoom in, as Cmd+= does → \"superscript\" | \"normal\"",
|
||||
),
|
||||
(
|
||||
"type.subscript",
|
||||
"Subscript",
|
||||
"Cmd+Alt+Shift+=",
|
||||
"{} the Character panel's Subscript button: the selected type (or the Type tool's selection, all of its text at a caret) becomes subscript, or Normal when all of it is subscript already (text.setFormat {position}) → \"subscript\" | \"normal\"",
|
||||
),
|
||||
(
|
||||
"type.lineComposer",
|
||||
"Toggle Line Composer",
|
||||
@@ -1043,7 +1078,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"tool.options",
|
||||
"Tool Options…",
|
||||
"",
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, v
Line truncated
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
@@ -1163,6 +1198,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
|
||||
),
|
||||
(
|
||||
"ui.attributesPanelOptions",
|
||||
"Panel Options…",
|
||||
"",
|
||||
"{count?: 1–30 (10 by default)} set how many of the recent URLs (attributes.info › recentUrls, which keeps 30) the Attributes panel's URL menu lists, newest first (kept with the UI state) → {count}; without count, open its Panel Options (dialog `attributesPanelOptions`, field count; OK sets it); an error for a count that is not a whole number from 1 to 30, which changes nothing",
|
||||
),
|
||||
(
|
||||
"ui.layersExpand",
|
||||
"Expand Layers Panel Rows",
|
||||
@@ -1531,6 +1572,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{} close the export progress dialog; the exports go on, shown in the status bar → {hidden: n}",
|
||||
),
|
||||
(
|
||||
"file.cancelSave",
|
||||
"Cancel Save",
|
||||
"",
|
||||
"{} stop every save running in the background (Background Save) before it replaces its file: the file stays as it was and the document keeps its file and stays modified; a save whose file was already being replaced finishes and is reported as saved → {cancelled: n}",
|
||||
),
|
||||
(
|
||||
"file.saveInBackground",
|
||||
"Continue in Background",
|
||||
"",
|
||||
"{} close the save progress window; the saves go on, shown in the status bar → {hidden: n}",
|
||||
),
|
||||
(
|
||||
"file.cancelOpen",
|
||||
"Cancel Opening",
|
||||
@@ -1735,6 +1788,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
|
||||
),
|
||||
(
|
||||
"ui.actionSet.clear",
|
||||
"Clear Actions",
|
||||
"",
|
||||
"{ids?: [id]} Clear Actions: delete every set in the Actions panel with its actions, the built-in Default Actions set included, so no set is current or selected; the panel's selected action and step and its expanded actions are cleared, and an open Set Options, New Action, Batch or step dialog that names a set closes. ids holds the panel's own set ids in panel order, which the menu's question passes: when the sets are no longer exactly those, nothing is deleted. With no sets, nothing changes and cleared is 0. Omitted params count as {}. Params of another type, another key, ids that is not a list of ids, or a clear while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Clear Actions (disabled with no sets and while an action records or plays) asks first, and OK runs this → {cleared: the number of sets deleted}",
|
||||
),
|
||||
("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"),
|
||||
(
|
||||
"docInfo.save",
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
//! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places
|
||||
//! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along
|
||||
//! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes
|
||||
//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]), the common
|
||||
//! tangents of two convex outlines ([`common_tangents`]), the
|
||||
//! Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch two or three shapes
|
||||
//! ([`tangent_circles`]).
|
||||
//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]) or many circles
|
||||
//! joined to their neighbors ([`bridge_many`]), the common tangents of two convex outlines
|
||||
//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch
|
||||
//! two or three shapes ([`tangent_circles`]).
|
||||
|
||||
mod bridge;
|
||||
mod crossings;
|
||||
@@ -27,7 +27,9 @@ use std::collections::BTreeSet;
|
||||
use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
|
||||
|
||||
pub use bridge::{BridgeError, circle_of, smooth_bridge};
|
||||
pub use bridge::{
|
||||
ArcRadius, BridgeError, Bridged, Joined, MAX_BRIDGED_CIRCLES, MAX_BRIDGES, ManyError, bridge_many, bridges_any, circle_of, smooth_bridge,
|
||||
};
|
||||
pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at};
|
||||
pub use dashes::{DashSpec, Piece, divide_dashes};
|
||||
pub use extend::{ExtendMode, extend_length_to, extend_open};
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
//! Smooth Bridge: two circles joined into one outline by two concave arcs, each touching both
|
||||
//! circles from outside, so the outline runs on smoothly from each circle into the bridge.
|
||||
//! circles from outside, so the outline runs on smoothly from each circle into the bridge; and
|
||||
//! many circles joined at once, each to the others within reach ([`bridge_many`]).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::f64::consts::{FRAC_PI_2, PI, SQRT_2, TAU};
|
||||
|
||||
use kurbo::{CubicBez, ParamCurve, Point, Shape, Vec2};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, FillRule, PathData, SubPath, shapes};
|
||||
|
||||
use crate::boolean::{DEFAULT_PRECISION, try_unite_all_with};
|
||||
|
||||
use super::Circle;
|
||||
|
||||
@@ -58,6 +62,64 @@ pub fn circle_of(path: &PathData) -> Option<Circle> {
|
||||
/// a tangent there. Overlapping and touching circles are joined too. A larger radius makes a wider,
|
||||
/// gentler bridge; farther apart circles make a narrower one, until the arcs would cross.
|
||||
pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result<SubPath, BridgeError> {
|
||||
let t = touches(a, b, radius)?;
|
||||
let mut segs = vec![];
|
||||
arc(&mut segs, a.center, a.radius, t.a1, t.a2, Some(-t.u));
|
||||
arc(&mut segs, t.p2, radius, t.a2, t.b2, None);
|
||||
arc(&mut segs, b.center, b.radius, t.b2, t.b1, Some(t.u));
|
||||
arc(&mut segs, t.p1, radius, t.b1, t.a1, None);
|
||||
closed(&segs, AnchorKind::Smooth)
|
||||
}
|
||||
|
||||
/// The part of [`smooth_bridge`]'s outline between the circles: the two arcs, joined across each
|
||||
/// circle by a straight line between the arc ends on it. Each line lies inside its circle, so the
|
||||
/// two circles and this shape unite into the outline, with each circle drawn once however many
|
||||
/// bridges it has.
|
||||
fn neck(a: Circle, b: Circle, radius: f64) -> Result<SubPath, BridgeError> {
|
||||
let t = touches(a, b, radius)?;
|
||||
let line = |p: Point, q: Point| CubicBez::new(p, p, q, q);
|
||||
let mut segs = vec![];
|
||||
arc(&mut segs, t.p2, radius, t.a2, t.b2, None);
|
||||
segs.push(line(t.b2, t.b1));
|
||||
arc(&mut segs, t.p1, radius, t.b1, t.a1, None);
|
||||
segs.push(line(t.a1, t.a2));
|
||||
closed(&segs, AnchorKind::Corner)
|
||||
}
|
||||
|
||||
/// A closed subpath through the cubics `segs`, each starting where the one before it ends, with
|
||||
/// anchors of `kind`; [`BridgeError::Bad`] when a point does not fit in `f64`.
|
||||
fn closed(segs: &[CubicBez], kind: AnchorKind) -> Result<SubPath, BridgeError> {
|
||||
let count = segs.len();
|
||||
let anchors: Vec<Anchor> = (0..count)
|
||||
.filter_map(|i| {
|
||||
let (prev, seg) = (segs.get((i + count - 1) % count)?, segs.get(i)?);
|
||||
Some(Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind })
|
||||
})
|
||||
.collect();
|
||||
let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) {
|
||||
return Err(BridgeError::Bad);
|
||||
}
|
||||
Ok(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// Where the arcs of radius `radius` that bridge circles `a` and `b` lie: the unit vector from
|
||||
/// `a`'s center to `b`'s, and on each side the arc's center (`p1`, `p2`) and where it touches `a`
|
||||
/// and `b`; and the neck's width where the arcs come nearest each other between the circles
|
||||
/// (infinite when that is at the circles).
|
||||
struct Touches {
|
||||
waist: f64,
|
||||
u: Vec2,
|
||||
p1: Point,
|
||||
a1: Point,
|
||||
b1: Point,
|
||||
p2: Point,
|
||||
a2: Point,
|
||||
b2: Point,
|
||||
}
|
||||
|
||||
/// The arcs of [`smooth_bridge`], or why there are none.
|
||||
fn touches(a: Circle, b: Circle, radius: f64) -> Result<Touches, BridgeError> {
|
||||
let finite = |x: f64| x.is_finite() && x > 0.0;
|
||||
let points = [a.center, b.center].iter().all(|c| c.x.is_finite() && c.y.is_finite());
|
||||
if !finite(radius) || !finite(a.radius) || !finite(b.radius) || !points {
|
||||
@@ -95,29 +157,237 @@ pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result<SubPath, Bridg
|
||||
}
|
||||
let u = axis / d;
|
||||
let n = Vec2::new(-u.y, u.x);
|
||||
let mut segs = vec![];
|
||||
// Each side's arc center and where its arc touches `a` and `b`.
|
||||
let side = |s: f64| {
|
||||
let p = a.center + u * along + n * (s * across);
|
||||
(p, a.center + (p - a.center) * (a.radius / ra), b.center + (p - b.center) * (b.radius / rb))
|
||||
};
|
||||
let ((p1, a1, b1), (p2, a2, b2)) = (side(1.0), side(-1.0));
|
||||
arc(&mut segs, a.center, a.radius, a1, a2, Some(-u));
|
||||
arc(&mut segs, p2, radius, a2, b2, None);
|
||||
arc(&mut segs, b.center, b.radius, b2, b1, Some(u));
|
||||
arc(&mut segs, p1, radius, b1, a1, None);
|
||||
let count = segs.len();
|
||||
let anchors: Vec<Anchor> = (0..count)
|
||||
.map(|i| {
|
||||
let (prev, seg) = (segs[(i + count - 1) % count], segs[i]);
|
||||
Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind: AnchorKind::Smooth }
|
||||
})
|
||||
.collect();
|
||||
let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) {
|
||||
return Err(BridgeError::Bad);
|
||||
let waist = if along > 0.0 && along < d { 2.0 * (across - radius) } else { f64::INFINITY };
|
||||
Ok(Touches { waist, u, p1, a1, b1, p2, a2, b2 })
|
||||
}
|
||||
|
||||
/// The most circles [`bridge_many`] takes.
|
||||
pub const MAX_BRIDGED_CIRCLES: usize = 2000;
|
||||
/// The most bridges [`bridge_many`] makes.
|
||||
pub const MAX_BRIDGES: usize = 8000;
|
||||
/// Holes [`bridge_many`] fills: those smaller than this share of the area of the smallest circle
|
||||
/// they join.
|
||||
const SPECK: f64 = 0.01;
|
||||
|
||||
/// The radius of the arcs that bridge two circles.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ArcRadius {
|
||||
/// This share of the smaller circle's radius (1 is the same radius).
|
||||
Share(f64),
|
||||
/// The smaller circle's radius plus this gap (pt). Each arc is then this gap outside a circle
|
||||
/// of the smaller circle's radius about the arc's center: for equal circles that gap apart,
|
||||
/// the place of a third circle that gap from both, as in a triangular grid.
|
||||
Gap(f64),
|
||||
}
|
||||
|
||||
impl ArcRadius {
|
||||
/// The arcs' radius (pt) for circles `a` and `b`.
|
||||
pub fn between(self, a: Circle, b: Circle) -> f64 {
|
||||
let r = a.radius.min(b.radius);
|
||||
match self {
|
||||
ArcRadius::Share(share) => r * share,
|
||||
ArcRadius::Gap(gap) => r + gap,
|
||||
}
|
||||
}
|
||||
Ok(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// Circles that bridges join into one shape: their indices, ascending, and the shape's outline.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Joined {
|
||||
pub members: Vec<usize>,
|
||||
pub outline: PathData,
|
||||
}
|
||||
|
||||
/// What [`bridge_many`] makes: the joined shapes, in the order of their first member, and the
|
||||
/// indices of the circles left alone, ascending.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Bridged {
|
||||
pub joined: Vec<Joined>,
|
||||
pub alone: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Why [`bridge_many`] makes nothing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ManyError {
|
||||
/// More than [`MAX_BRIDGED_CIRCLES`] circles.
|
||||
TooManyCircles,
|
||||
/// More than [`MAX_BRIDGES`] pairs of circles within reach that the arcs can bridge.
|
||||
TooManyBridges,
|
||||
/// No two circles are within reach of each other.
|
||||
NoneInReach,
|
||||
/// The circles at these indices are within reach but [`smooth_bridge`] can't join them: one is
|
||||
/// inside the other, or no pair within reach is near enough for the arcs (the first such pair).
|
||||
Pair(usize, usize, BridgeError),
|
||||
/// A reach that is not a finite size of 0 or more, or a circle that is not a finite size above 0.
|
||||
Bad,
|
||||
/// A joined shape too complex to unite.
|
||||
TooComplex,
|
||||
}
|
||||
|
||||
/// Every pair of `circles` whose outlines are at most `reach` (pt) apart, overlapping ones
|
||||
/// included, joined by a [`smooth_bridge`] with arcs of radius `arc`, and the bridges that connect
|
||||
/// united into one shape each, without holes smaller than 1% of the smallest circle's area. A pair
|
||||
/// too far apart for the arcs gets no bridge; a circle bridged to no other is left alone. One
|
||||
/// circle inside another is an error, and so is no pair that the arcs can join.
|
||||
pub fn bridge_many(circles: &[Circle], arc: ArcRadius, reach: f64) -> Result<Bridged, ManyError> {
|
||||
let (pairs, too_far, roots, precision) = bridgeable(circles, arc, reach)?;
|
||||
match (pairs.is_empty(), too_far) {
|
||||
(true, Some((i, j))) => return Err(ManyError::Pair(i, j, BridgeError::TooFar)),
|
||||
(true, None) => return Err(ManyError::NoneInReach),
|
||||
(false, _) => {}
|
||||
}
|
||||
let mut necks = Vec::with_capacity(pairs.len());
|
||||
for &((i, j), _) in &pairs {
|
||||
let (a, b) = (circles[i], circles[j]);
|
||||
let sp = neck(a, b, arc.between(a, b)).map_err(|e| ManyError::Pair(i, j, e))?;
|
||||
necks.push(((i, j), PathData::single(sp)));
|
||||
}
|
||||
let mut sets: BTreeMap<usize, (Vec<usize>, Vec<&PathData>)> = BTreeMap::new();
|
||||
for &((i, j), ref neck) in &necks {
|
||||
let (members, parts) = sets.entry(roots[i]).or_default();
|
||||
members.extend([i, j]);
|
||||
parts.push(neck);
|
||||
}
|
||||
let mut out = Bridged::default();
|
||||
for (set, (mut members, parts)) in sets {
|
||||
members.sort_unstable();
|
||||
members.dedup();
|
||||
// Each circle once, and the necks between them.
|
||||
let rounds: Vec<PathData> = members
|
||||
.iter()
|
||||
.filter_map(|&i| circles.get(i))
|
||||
.map(|c| shapes::ellipse(kurbo::Rect::from_center_size(c.center, (2.0 * c.radius, 2.0 * c.radius))))
|
||||
.collect();
|
||||
let fills: Vec<(&PathData, FillRule)> = rounds.iter().chain(parts).map(|p| (p, FillRule::NonZero)).collect();
|
||||
let smallest = members.iter().filter_map(|&i| circles.get(i)).map(|c| c.radius).fold(f64::INFINITY, f64::min);
|
||||
let mut outline = try_unite_all_with(&fills, precision[set]).map_err(|_| ManyError::TooComplex)?;
|
||||
// Where three bridges' arcs nearly meet, the union leaves a speck of a hole; a contour that
|
||||
// encloses a circle is far larger than this.
|
||||
let speck = SPECK * PI * smallest * smallest;
|
||||
outline.subpaths.retain(|sp| PathData::single(sp.clone()).to_bezpath().area().abs() >= speck);
|
||||
out.joined.push(Joined { members, outline });
|
||||
}
|
||||
let joined: HashSet<usize> = necks.iter().flat_map(|&((i, j), _)| [i, j]).collect();
|
||||
out.alone = (0..circles.len()).filter(|i| !joined.contains(i)).collect();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether [`bridge_many`] would bridge at least one pair of `circles` with arcs of `arc` and
|
||||
/// `reach`, under the same rules (a neck too thin for its shape's precision included), without
|
||||
/// making the bridges or uniting them.
|
||||
pub fn bridges_any(circles: &[Circle], arc: ArcRadius, reach: f64) -> bool {
|
||||
bridgeable(circles, arc, reach).is_ok_and(|(pairs, ..)| !pairs.is_empty())
|
||||
}
|
||||
|
||||
/// What [`bridgeable`] finds: the pairs [`bridge_many`] bridges with their necks' widths, the
|
||||
/// lowest pair within reach that it can't bridge, each circle's set (its lowest index) and each
|
||||
/// set's precision, under its lowest index.
|
||||
type Bridgeable = (Vec<(Pair, f64)>, Option<Pair>, Vec<usize>, Vec<f64>);
|
||||
|
||||
/// The pairs of `circles` that [`bridge_many`] bridges, and how it sorts them into sets.
|
||||
fn bridgeable(circles: &[Circle], arc: ArcRadius, reach: f64) -> Result<Bridgeable, ManyError> {
|
||||
if circles.len() > MAX_BRIDGED_CIRCLES {
|
||||
return Err(ManyError::TooManyCircles);
|
||||
}
|
||||
let fine = |c: &Circle| c.center.x.is_finite() && c.center.y.is_finite() && c.radius.is_finite() && c.radius > 0.0;
|
||||
if !(reach.is_finite() && reach >= 0.0) || !circles.iter().all(fine) {
|
||||
return Err(ManyError::Bad);
|
||||
}
|
||||
let (mut pairs, mut too_far) = pairs_within(circles, reach, arc)?;
|
||||
// Each set of connected circles, under its lowest index, is united at a precision fine enough
|
||||
// for its smallest circle. A neck narrower than twice that would not survive the union, so its
|
||||
// pair gets no bridge; that can split a set and make its precision coarser, so the sets are
|
||||
// found again until no neck is dropped.
|
||||
let (roots, precision) = loop {
|
||||
let mut parent: Vec<usize> = (0..circles.len()).collect();
|
||||
for &((i, j), _) in &pairs {
|
||||
let (ri, rj) = (root(&mut parent, i), root(&mut parent, j));
|
||||
parent[ri.max(rj)] = ri.min(rj);
|
||||
}
|
||||
let roots: Vec<usize> = (0..circles.len()).map(|i| root(&mut parent, i)).collect();
|
||||
let mut precision = vec![DEFAULT_PRECISION; circles.len()];
|
||||
for (&r, c) in roots.iter().zip(circles) {
|
||||
precision[r] = precision[r].min(c.radius * 1e-3);
|
||||
}
|
||||
let thin = |&((i, _), waist): &(Pair, f64)| waist < 2.0 * precision[roots[i]];
|
||||
if !pairs.iter().any(thin) {
|
||||
break (roots, precision);
|
||||
}
|
||||
for &(pair, _) in pairs.iter().filter(|&p| thin(p)) {
|
||||
too_far = Some(too_far.map_or(pair, |t| t.min(pair)));
|
||||
}
|
||||
pairs.retain(|p| !thin(p));
|
||||
};
|
||||
Ok((pairs, too_far, roots, precision))
|
||||
}
|
||||
|
||||
/// Two circles' indices, the lower first.
|
||||
type Pair = (usize, usize);
|
||||
/// What [`pairs_within`] finds: the pairs the arcs can bridge, each with its neck's width, and the
|
||||
/// lowest pair too far apart for them.
|
||||
type Within = (Vec<(Pair, f64)>, Option<Pair>);
|
||||
|
||||
/// The set `i` is in: the lowest index in it, with the path to it shortened on the way.
|
||||
fn root(parent: &mut [usize], mut i: usize) -> usize {
|
||||
while parent[i] != i {
|
||||
parent[i] = parent[parent[i]];
|
||||
i = parent[i];
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// Every pair of indices `(i, j)`, `i < j`, ascending, of `circles` whose outlines are at most
|
||||
/// `reach` apart and that arcs of `arc` can bridge, with the width of the neck between them, and
|
||||
/// the lowest pair within reach that they can't because it is too far apart for them. Circles go
|
||||
/// into a grid of cells as wide as the farthest two centers within reach can be, so each circle is
|
||||
/// compared only with those in its own cell and the eight around it.
|
||||
fn pairs_within(circles: &[Circle], reach: f64, arc: ArcRadius) -> Result<Within, ManyError> {
|
||||
let biggest = circles.iter().map(|c| c.radius).fold(0.0, f64::max);
|
||||
let cell = 2.0 * biggest + reach;
|
||||
if !(cell.is_finite() && cell > 0.0) {
|
||||
return Err(ManyError::Bad);
|
||||
}
|
||||
// Saturating casts: a cell beyond i64 shares the last one, which only adds comparisons.
|
||||
let key = |p: Point| ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64);
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
|
||||
for (i, c) in circles.iter().enumerate() {
|
||||
grid.entry(key(c.center)).or_default().push(i);
|
||||
}
|
||||
let (mut pairs, mut too_far) = (vec![], None::<Pair>);
|
||||
for (i, &c) in circles.iter().enumerate() {
|
||||
let (x, y) = key(c.center);
|
||||
for (dx, dy) in (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (dx, dy))) {
|
||||
let Some(near) = grid.get(&(x.saturating_add(dx), y.saturating_add(dy))) else { continue };
|
||||
for &j in near.iter().filter(|&&j| j > i) {
|
||||
let o = circles[j];
|
||||
if c.center.distance(o.center) - c.radius - o.radius > reach {
|
||||
continue;
|
||||
}
|
||||
// Only the arcs' ends are worked out here; the bridge itself is made later.
|
||||
match touches(c, o, arc.between(c, o)) {
|
||||
Ok(t) => pairs.push(((i, j), t.waist)),
|
||||
Err(BridgeError::TooFar) => too_far = Some(too_far.map_or((i, j), |t| t.min((i, j)))),
|
||||
Err(e) => return Err(ManyError::Pair(i, j, e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
// Saturated cells can list a pair twice, so the count is checked again after `dedup`.
|
||||
if pairs.len() > 9 * MAX_BRIDGES {
|
||||
return Err(ManyError::TooManyBridges);
|
||||
}
|
||||
}
|
||||
pairs.sort_unstable_by_key(|&(pair, _)| pair);
|
||||
pairs.dedup_by_key(|&mut (pair, _)| pair);
|
||||
if pairs.len() > MAX_BRIDGES {
|
||||
return Err(ManyError::TooManyBridges);
|
||||
}
|
||||
Ok((pairs, too_far))
|
||||
}
|
||||
|
||||
/// Append to `out` the arc of the circle about `center` with radius `r` from `from` to `to` (both
|
||||
@@ -331,6 +601,198 @@ mod tests {
|
||||
assert_eq!(smooth_bridge(circle(f64::INFINITY, 0.0, 10.0), b, 10.0), Err(BridgeError::Bad));
|
||||
}
|
||||
|
||||
/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), top-left at the origin.
|
||||
fn grid() -> Vec<Circle> {
|
||||
(0..9).map(|k| circle(24.0 * (k % 3) as f64, 24.0 * (k / 3) as f64, 10.0)).collect()
|
||||
}
|
||||
|
||||
fn area(path: &PathData) -> f64 {
|
||||
crate::area(path, FillRule::NonZero)
|
||||
}
|
||||
|
||||
fn inside(path: &PathData, x: f64, y: f64) -> bool {
|
||||
path.to_bezpath().winding(Point::new(x, y)) != 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_joins_each_circle_to_its_neighbors_within_reach() {
|
||||
// Reach 5: the side neighbors (4 apart) are joined, the diagonal ones (about 13.9 apart) not.
|
||||
let b = bridge_many(&grid(), ArcRadius::Gap(4.0), 5.0).unwrap();
|
||||
assert_eq!(b.alone, Vec::<usize>::new());
|
||||
let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) };
|
||||
assert_eq!(one.members, (0..9).collect::<Vec<_>>());
|
||||
for (x, y) in [(12.0, 0.0), (0.0, 12.0), (36.0, 48.0), (48.0, 36.0), (24.0, 24.0)] {
|
||||
assert!(inside(&one.outline, x, y), "bridged at ({x}, {y})");
|
||||
}
|
||||
// Between four circles the side bridges' arcs leave a hole: no diagonal bridge fills it.
|
||||
for (x, y) in [(12.0, 12.0), (36.0, 36.0)] {
|
||||
assert!(!inside(&one.outline, x, y), "a hole at ({x}, {y})");
|
||||
}
|
||||
let hull = PathData::single(SubPath::polyline(
|
||||
&[Point::new(-10.0, -10.0), Point::new(58.0, -10.0), Point::new(58.0, 58.0), Point::new(-10.0, 58.0)],
|
||||
true,
|
||||
));
|
||||
assert!(area(&one.outline) < area(&hull));
|
||||
assert_eq!(one.outline.subpaths.len(), 5, "the outline and a hole in each square");
|
||||
// Reach 15 takes in the diagonal neighbors too, and their bridges fill the middle of each
|
||||
// square. The specks of holes (about 0.1 pt²) where side and diagonal arcs nearly meet are
|
||||
// filled.
|
||||
let b = bridge_many(&grid(), ArcRadius::Gap(4.0), 15.0).unwrap();
|
||||
let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) };
|
||||
assert!(inside(&one.outline, 12.0, 12.0) && inside(&one.outline, 36.0, 36.0));
|
||||
assert_eq!(one.outline.subpaths.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_with_no_neighbor_in_reach_is_left_alone() {
|
||||
let mut circles = grid();
|
||||
circles.truncate(2);
|
||||
circles.push(circle(200.0, 0.0, 10.0));
|
||||
circles.push(circle(224.0, 0.0, 10.0));
|
||||
circles.push(circle(100.0, 100.0, 10.0));
|
||||
let b = bridge_many(&circles, ArcRadius::Share(1.0), 5.0).unwrap();
|
||||
assert_eq!(b.joined.iter().map(|j| j.members.clone()).collect::<Vec<_>>(), [vec![0, 1], vec![2, 3]]);
|
||||
assert_eq!(b.alone, [4]);
|
||||
// Each pair alone is the two-circle bridge.
|
||||
let two = smooth_bridge(circles[0], circles[1], 10.0).unwrap();
|
||||
let (got, want) = (area(&b.joined[0].outline), area(&PathData::single(two)));
|
||||
assert!((got - want).abs() < 1e-3 * want, "{got} {want}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ring_around_an_empty_place_leaves_a_round_hole_the_gap_wider_than_a_circle() {
|
||||
// Six circles of radius 10 around an empty place at the origin, each 4 from its two
|
||||
// neighbors and from where a seventh circle would be (centers 24 from the origin).
|
||||
let ring: Vec<Circle> = (0..6).map(|k| f64::from(k) * PI / 3.0).map(|t| circle(24.0 * t.cos(), 24.0 * t.sin(), 10.0)).collect();
|
||||
let b = bridge_many(&ring, ArcRadius::Gap(4.0), 5.0).unwrap();
|
||||
let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) };
|
||||
assert_eq!(one.members, (0..6).collect::<Vec<_>>());
|
||||
assert_eq!(one.outline.subpaths.len(), 2, "the outline and the hole");
|
||||
// The hole's edge is 14 from the origin all the way round: a circle of radius 10 there
|
||||
// would be 4 from the shape everywhere, the same as from each of the six.
|
||||
let hole = one.outline.subpaths.iter().min_by(|p, q| {
|
||||
let size = |sp: &SubPath| PathData::single(sp.clone()).to_bezpath().area().abs();
|
||||
size(p).total_cmp(&size(q))
|
||||
});
|
||||
let edge = outline(hole.unwrap());
|
||||
let (near, far) = edge.iter().map(|p| p.distance(Point::ZERO)).fold((f64::INFINITY, 0.0f64), |(n, f), d| (n.min(d), f.max(d)));
|
||||
assert!((near - 14.0).abs() < 1e-2 && (far - 14.0).abs() < 1e-2, "{near} to {far}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_circles_make_the_two_circle_outline_for_each_pair() {
|
||||
// Overlapping, touching, unequal and unequal overlapping pairs, each with a far circle.
|
||||
for (a, b, share) in [
|
||||
(circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 20.0), 0.5),
|
||||
(circle(0.0, 0.0, 20.0), circle(40.0, 0.0, 20.0), 0.5),
|
||||
(circle(0.0, 0.0, 30.0), circle(70.0, 0.0, 10.0), 4.0),
|
||||
(circle(0.0, 0.0, 10.0), circle(25.0, 0.0, 30.0), 10.0),
|
||||
// Circles far smaller than the union's usual precision (0.01 pt).
|
||||
(circle(0.0, 0.0, 0.004), circle(0.01, 0.0, 0.004), 1.0),
|
||||
] {
|
||||
let made = bridge_many(&[a, b, circle(1000.0, 0.0, 5.0)], ArcRadius::Share(share), 40.0).unwrap();
|
||||
assert_eq!(made.alone, [2]);
|
||||
let two = smooth_bridge(a, b, share * a.radius.min(b.radius)).unwrap();
|
||||
let (got, want) = (area(&made.joined[0].outline), area(&PathData::single(two)));
|
||||
assert!((got - want).abs() < 1e-3 * want, "{a:?}: {got} {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pair_too_far_apart_for_the_arcs_gets_no_bridge() {
|
||||
// b and c are within reach (6 apart) but arcs of radius 3 close before they reach both.
|
||||
let (a, b, c) = (circle(0.0, 0.0, 3.0), circle(8.0, 0.0, 3.0), circle(20.0, 0.0, 3.0));
|
||||
assert_eq!(smooth_bridge(b, c, 3.0), Err(BridgeError::TooFar));
|
||||
let made = bridge_many(&[a, b, c], ArcRadius::Share(1.0), 10.0).unwrap();
|
||||
assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::<Vec<_>>(), [vec![0, 1]]);
|
||||
assert_eq!(made.alone, [2]);
|
||||
// Arcs of radius 10 between circles of radius 10 just under 20√3 apart leave a neck about
|
||||
// 0.00003 pt wide, too thin for the union: that pair is left unbridged too.
|
||||
let (a, b, c) = (circle(0.0, 0.0, 10.0), circle(34.6409, 0.0, 10.0), circle(58.6409, 0.0, 10.0));
|
||||
assert!(smooth_bridge(a, b, 10.0).is_ok(), "two circles alone are bridged");
|
||||
let made = bridge_many(&[a, b, c], ArcRadius::Share(1.0), 20.0).unwrap();
|
||||
assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::<Vec<_>>(), [vec![1, 2]]);
|
||||
assert_eq!(made.alone, [0]);
|
||||
// Two tiny circles far off are united at a finer precision, which does not change that.
|
||||
let tiny = [circle(500.0, 0.0, 0.01), circle(500.025, 0.0, 0.01)];
|
||||
let made = bridge_many(&[a, b, c, tiny[0], tiny[1]], ArcRadius::Share(1.0), 20.0).unwrap();
|
||||
assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::<Vec<_>>(), [vec![1, 2], vec![3, 4]]);
|
||||
assert_eq!(made.alone, [0]);
|
||||
// 260 touching circles in a row with a wide reach: 33,670 pairs within reach, far more than
|
||||
// the bridge limit, but only the 259 touching pairs are near enough for the arcs.
|
||||
let row: Vec<Circle> = (0..260).map(|i| circle(f64::from(i) * 20.0, 0.0, 10.0)).collect();
|
||||
let made = bridge_many(&row, ArcRadius::Share(1.0), 6000.0).unwrap();
|
||||
let [one] = made.joined.as_slice() else { panic!("{} shapes", made.joined.len()) };
|
||||
assert_eq!(one.members.len(), 260);
|
||||
assert!(made.alone.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gap_form_keeps_the_gap_from_a_circle_at_each_arcs_center() {
|
||||
// Two circles 4 apart; with a gap of 4 each arc's center is 24 from both centers, where a
|
||||
// third circle of the same size is 4 from both (as in a triangular grid).
|
||||
let (a, b) = (circle(0.0, 0.0, 10.0), circle(24.0, 0.0, 10.0));
|
||||
let r = ArcRadius::Gap(4.0).between(a, b);
|
||||
assert_eq!(r, 14.0);
|
||||
let sp = smooth_bridge(a, b, r).unwrap();
|
||||
for third in [circle(12.0, 432f64.sqrt(), 10.0), circle(12.0, -(432f64.sqrt()), 10.0)] {
|
||||
let gaps: Vec<f64> = outline(&sp).iter().map(|p| p.distance(third.center) - third.radius).collect();
|
||||
// No part of the bridge comes nearer than the gap, and a stretch of it is that gap away.
|
||||
assert!(gaps.iter().all(|&g| g > 4.0 - 1e-2), "{:?}", gaps.iter().copied().fold(f64::INFINITY, f64::min));
|
||||
let along = gaps.iter().filter(|&&g| (g - 4.0).abs() < 1e-2).count();
|
||||
assert!(along >= 32, "{along}");
|
||||
}
|
||||
// The same for unequal circles: the gap is kept from a circle of the smaller one's size.
|
||||
let (a, b) = (circle(0.0, 0.0, 15.0), circle(30.0, 5.0, 8.0));
|
||||
let r = ArcRadius::Gap(3.0).between(a, b);
|
||||
let sp = smooth_bridge(a, b, r).unwrap();
|
||||
let d = (b.center - a.center).hypot();
|
||||
let (ra, rb) = (15.0 + r, 8.0 + r);
|
||||
let along = (d * d + ra * ra - rb * rb) / (2.0 * d);
|
||||
let u = (b.center - a.center) / d;
|
||||
let center = a.center + u * along + Vec2::new(-u.y, u.x) * (ra * ra - along * along).sqrt();
|
||||
let gaps: Vec<f64> = outline(&sp).iter().map(|p| p.distance(center) - 8.0).collect();
|
||||
assert!(gaps.iter().all(|&g| g > 3.0 - 1e-2) && gaps.iter().filter(|&&g| (g - 3.0).abs() < 1e-2).count() >= 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gap_form_is_the_percentage_form_of_the_radius_plus_the_gap() {
|
||||
for (a, b, gap) in [(circle(0.0, 0.0, 10.0), circle(24.0, 0.0, 10.0), 4.0), (circle(0.0, 0.0, 20.0), circle(40.0, 30.0, 10.0), 7.5)] {
|
||||
let small = a.radius.min(b.radius);
|
||||
let share = ArcRadius::Share((small + gap) / small);
|
||||
assert!((ArcRadius::Gap(gap).between(a, b) - share.between(a, b)).abs() < 1e-12);
|
||||
let (g, s) = (smooth_bridge(a, b, ArcRadius::Gap(gap).between(a, b)).unwrap(), smooth_bridge(a, b, share.between(a, b)).unwrap());
|
||||
for (p, q) in g.anchors.iter().zip(&s.anchors) {
|
||||
assert!(p.p.distance(q.p) < 1e-9 && p.h_in.distance(q.h_in) < 1e-9 && p.h_out.distance(q.h_out) < 1e-9);
|
||||
}
|
||||
assert_eq!(g.anchors.len(), s.anchors.len());
|
||||
}
|
||||
// Over a grid the two forms make the same shape too.
|
||||
let by_gap = bridge_many(&grid(), ArcRadius::Gap(4.0), 5.0).unwrap();
|
||||
let by_share = bridge_many(&grid(), ArcRadius::Share(1.4), 5.0).unwrap();
|
||||
let (g, s) = (area(&by_gap.joined[0].outline), area(&by_share.joined[0].outline));
|
||||
assert!((g - s).abs() < 1e-6 * g, "{g} {s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_circles_or_bridges_and_bad_pairs_are_refused() {
|
||||
let many = vec![circle(0.0, 0.0, 1.0); MAX_BRIDGED_CIRCLES + 1];
|
||||
assert_eq!(bridge_many(&many, ArcRadius::Share(1.0), 1.0), Err(ManyError::TooManyCircles));
|
||||
// 200 circles in a tight row: 19,900 pairs within reach.
|
||||
let row: Vec<Circle> = (0..200).map(|i| circle(i as f64 * 0.1, 0.0, 10.0)).collect();
|
||||
assert_eq!(bridge_many(&row, ArcRadius::Share(1.0), 1.0), Err(ManyError::TooManyBridges));
|
||||
let spread: Vec<Circle> = (0..3).map(|i| circle(i as f64 * 100.0, 0.0, 10.0)).collect();
|
||||
assert_eq!(bridge_many(&spread, ArcRadius::Share(1.0), 5.0), Err(ManyError::NoneInReach));
|
||||
let nested = [circle(0.0, 0.0, 30.0), circle(5.0, 0.0, 10.0), circle(200.0, 0.0, 10.0)];
|
||||
assert_eq!(bridge_many(&nested, ArcRadius::Share(1.0), 5.0), Err(ManyError::Pair(0, 1, BridgeError::Inside)));
|
||||
// Within reach (40 apart) but too far for arcs of radius 1.
|
||||
let far = [circle(0.0, 0.0, 10.0), circle(60.0, 0.0, 10.0), circle(300.0, 0.0, 10.0)];
|
||||
assert_eq!(bridge_many(&far, ArcRadius::Share(0.1), 50.0), Err(ManyError::Pair(0, 1, BridgeError::TooFar)));
|
||||
assert_eq!(bridge_many(&far, ArcRadius::Share(1.0), f64::NAN), Err(ManyError::Bad));
|
||||
assert_eq!(bridge_many(&far, ArcRadius::Share(1.0), -1.0), Err(ManyError::Bad));
|
||||
assert_eq!(bridge_many(&[circle(f64::INFINITY, 0.0, 1.0), far[0]], ArcRadius::Share(1.0), 1.0), Err(ManyError::Bad));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_circles_bridge_with_finite_anchors_or_are_refused() {
|
||||
// Squaring these lengths overflows f64.
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
use craft_svg::tree::usvg;
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{OnceCell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::ops::{Range, RangeInclusive};
|
||||
@@ -774,6 +774,10 @@ struct Ctx {
|
||||
/// no usable one. The styles of a `<use>` instance share it, so each path is found and parsed
|
||||
/// once however many `<use>` elements show its text.
|
||||
paths: Rc<RefCell<HashMap<roxmltree::NodeId, Option<Rc<FollowedPath>>>>>,
|
||||
/// Each element id in the document and the first element in document order that carries it
|
||||
/// ([`Self::element`]). It is built when the first `<textPath>` names an element, and the
|
||||
/// styles of a `<use>` instance share it.
|
||||
ids: Rc<OnceCell<HashMap<Box<str>, roxmltree::NodeId>>>,
|
||||
}
|
||||
|
||||
/// The path a `<textPath>` follows ([`Ctx::text_path`]).
|
||||
@@ -788,6 +792,11 @@ struct FollowedPath {
|
||||
thread_local! {
|
||||
/// How many times [`Ctx::read_text_path`] has read a `<textPath>`'s path on this thread.
|
||||
static TEXT_PATH_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// How many times [`Ctx::element`] has walked a document's elements on this thread.
|
||||
static ID_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// When set, [`Ctx::element`] walks the document for each id instead of using the map, so
|
||||
/// tests can compare the two.
|
||||
static LINEAR_IDS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
impl Ctx {
|
||||
@@ -802,6 +811,7 @@ impl Ctx {
|
||||
elems: RefCell::default(),
|
||||
strong: RefCell::default(),
|
||||
paths: Rc::default(),
|
||||
ids: Rc::default(),
|
||||
};
|
||||
let root = xml.root_element();
|
||||
let dim = |a: &str| root.attribute(a).and_then(|v| cx.length(v, DEFAULT_FONT_SIZE, 0.0)).filter(|v| *v > 0.0);
|
||||
@@ -824,6 +834,7 @@ impl Ctx {
|
||||
elems: RefCell::default(),
|
||||
strong: RefCell::default(),
|
||||
paths: self.paths.clone(),
|
||||
ids: self.ids.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1219,7 +1230,7 @@ impl Ctx {
|
||||
Some(d) => BezPath::from_svg(d).ok()?,
|
||||
None => {
|
||||
let id = href(tp)?.trim().strip_prefix('#')?;
|
||||
let el = xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id))?;
|
||||
let el = self.element(xml, id)?;
|
||||
let d = match el.tag_name().name() {
|
||||
"path" => el.attribute("d")?.to_string(),
|
||||
_ => self.shape_path(el)?,
|
||||
@@ -1238,6 +1249,32 @@ impl Ctx {
|
||||
usable.then_some(FollowedPath { path: bp, author_length })
|
||||
}
|
||||
|
||||
/// The first element in document order whose `id` is `id`, as the DOM's `getElementById`
|
||||
/// finds it (https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid). The first
|
||||
/// call walks `xml` once to build [`Self::ids`]; later calls look the id up there. `xml` is
|
||||
/// the document [`Self::new`] read.
|
||||
fn element<'a, 'i>(&self, xml: &'a roxmltree::Document<'i>, id: &str) -> Option<XNode<'a, 'i>> {
|
||||
#[cfg(test)]
|
||||
if LINEAR_IDS.get() {
|
||||
ID_WALKS.set(ID_WALKS.get() + 1);
|
||||
return xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id));
|
||||
}
|
||||
let ids = self.ids.get_or_init(|| {
|
||||
#[cfg(test)]
|
||||
ID_WALKS.set(ID_WALKS.get() + 1);
|
||||
let mut ids = HashMap::new();
|
||||
for n in xml.descendants().filter(|n| n.is_element()) {
|
||||
if let Some(id) = n.attribute("id") {
|
||||
ids.entry(Box::from(id)).or_insert(n.id());
|
||||
}
|
||||
}
|
||||
ids
|
||||
});
|
||||
let el = xml.get_node(*ids.get(id)?)?;
|
||||
debug_assert_eq!(el.attribute("id"), Some(id), "the id map was built from another document");
|
||||
Some(el)
|
||||
}
|
||||
|
||||
/// The equivalent path of a basic shape (SVG 2 › Basic Shapes), as path data: what a
|
||||
/// `<textPath>` that points at it follows. Circles and ellipses start at 3 o'clock and rounded
|
||||
/// rects at the end of the top-left corner, all running clockwise; lines and polylines follow
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use vectorcraft_doc::Document;
|
||||
|
||||
/// The texts [`prepare`] builds from `body` and how many times it read a `<textPath>`'s path.
|
||||
fn prepared(body: &str) -> (usize, u64, Vec<String>) {
|
||||
@@ -27,3 +28,134 @@ fn uses_of_a_text_on_a_path_read_the_path_once() {
|
||||
));
|
||||
assert_eq!((texts, reads), (51, 1));
|
||||
}
|
||||
|
||||
/// How many times [`prepare`] walked the document's elements to find the element a
|
||||
/// `<textPath>` names.
|
||||
fn id_walks(body: &str) -> u64 {
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">{body}</svg>"#);
|
||||
let xml = roxmltree::Document::parse(&svg).unwrap();
|
||||
let before = ID_WALKS.get();
|
||||
prepare(&svg, &xml, None, 96.0, &mut vec![]);
|
||||
ID_WALKS.get() - before
|
||||
}
|
||||
|
||||
/// The texts on paths in one file find the elements they name through one walk of the document.
|
||||
#[test]
|
||||
fn text_paths_find_their_elements_in_one_walk() {
|
||||
let paths: String = (0..20).map(|i| format!(r#"<path id="p{i}" d="M0 {i}L150 {i}"/>"#)).collect();
|
||||
let texts: String = (0..20).map(|i| format!(r##"<text id="t{i}"><textPath href="#p{i}">Path</textPath></text>"##)).collect();
|
||||
assert_eq!(id_walks(&format!("<defs>{paths}</defs>{texts}")), 1);
|
||||
// Texts shown only through `<use>` elements share the walk, and a missing id needs no other.
|
||||
let uses: String = (0..20).map(|i| format!(r##"<use href="#t{i}" font-size="20"/>"##)).collect();
|
||||
let missing = r##"<text><textPath xlink:href="#none" xmlns:xlink="http://www.w3.org/1999/xlink">Path</textPath></text>"##;
|
||||
assert_eq!(id_walks(&format!("<defs>{paths}{texts}</defs>{uses}{missing}")), 1);
|
||||
// A file whose texts name no element is not walked.
|
||||
assert_eq!(id_walks(r#"<text>Plain</text><text><textPath path="M0 20L150 20">Inline</textPath></text>"#), 0);
|
||||
assert_eq!(id_walks(r#"<path id="p" d="M0 20L150 20"/><text><textPath href="p">No hash</textPath></text>"#), 0);
|
||||
}
|
||||
|
||||
/// The document and warnings [`crate::import`] gives for `body`, with each `<textPath>`'s
|
||||
/// element found through the map of ids or, with `linear`, by walking the document for each one.
|
||||
fn imported(body: &str, linear: bool) -> (Document, Vec<String>) {
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400">{body}</svg>"#);
|
||||
LINEAR_IDS.set(linear);
|
||||
let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES);
|
||||
LINEAR_IDS.set(false);
|
||||
out.unwrap_or_else(|e| panic!("{e}"))
|
||||
}
|
||||
|
||||
/// The text objects of `d`, in paint order.
|
||||
fn text_objects(d: &Document) -> Vec<TextObject> {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
|
||||
v.push((**t).clone());
|
||||
}
|
||||
});
|
||||
v
|
||||
}
|
||||
|
||||
/// The map of ids finds the element the document walk finds: the first element in document order
|
||||
/// with the id, whatever it is.
|
||||
#[test]
|
||||
fn text_paths_find_the_element_a_document_walk_finds() {
|
||||
let cases = [
|
||||
// Several paths, one of them named twice, and shapes.
|
||||
r##"<defs><path id="a" d="M0 20L150 20"/><path id="b" d="M0 50C50 0 100 100 150 50" pathLength="10"/><path id="a" d="M0 80L150 80"/>
|
||||
<circle id="c" cx="200" cy="200" r="80"/><rect id="r" x="10" y="10" width="200" height="100" rx="5"/></defs>
|
||||
<text font-size="12"><textPath href="#a">First</textPath></text>
|
||||
<text font-size="12"><textPath xlink:href=" #b " startOffset="5">Second</textPath></text>
|
||||
<text font-size="12"><textPath href="#c" side="right">Circle</textPath></text>
|
||||
<text font-size="12"><textPath href="#r" startOffset="50%">Rect</textPath></text>"##,
|
||||
// A missing id, an empty one, and one without a `#`.
|
||||
r##"<path id="p" d="M0 20L150 20"/><text><textPath href="#none">Missing</textPath></text>
|
||||
<text><textPath href="#">Empty</textPath></text><text><textPath href="p">Bare</textPath></text>"##,
|
||||
// The first element with the id has no path; the later path is not used.
|
||||
r##"<g id="p"><path d="M0 20L150 20"/></g><path id="p" d="M0 80L150 80"/><text><textPath href="#p">Group</textPath></text>"##,
|
||||
// Ids on texts and groups, one of them named twice.
|
||||
r##"<g id="g"><text id="t"><textPath href="#t">Self</textPath></text></g><text id="g">Later</text><text><textPath href="#g">Group</textPath></text>"##,
|
||||
// Uses of texts on paths, and an inline path beside an href.
|
||||
r##"<defs><path id="p" d="M0 20L150 20"/><text id="t"><textPath href="#p">Used</textPath></text></defs>
|
||||
<use href="#t" font-size="30"/><use href="#t" y="40"/><text><textPath href="#p" path="M0 90L150 90">Inline</textPath></text>"##,
|
||||
];
|
||||
for body in cases {
|
||||
let map = imported(body, false);
|
||||
assert_eq!(map, imported(body, true), "{body}");
|
||||
assert!(!text_objects(&map.0).is_empty(), "{body}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With two elements of one id, a `<textPath>` follows the first.
|
||||
#[test]
|
||||
fn a_text_path_follows_the_first_element_with_its_id() {
|
||||
let text = r##"<text font-size="12"><textPath href="#p">Path</textPath></text>"##;
|
||||
let first = text_objects(&imported(&format!(r#"<path id="p" d="M0 20L150 20"/><path id="p" d="M0 80L150 80"/>{text}"#), false).0);
|
||||
let only = text_objects(&imported(&format!(r#"<path id="p" d="M0 20L150 20"/><path id="q" d="M0 80L150 80"/>{text}"#), false).0);
|
||||
let second = text_objects(&imported(&format!(r#"<path id="q" d="M0 20L150 20"/><path id="p" d="M0 80L150 80"/>{text}"#), false).0);
|
||||
assert!(matches!(first[0].kind, TextKind::OnPath { .. }), "{:?}", first[0].kind);
|
||||
assert_eq!(first, only);
|
||||
assert_ne!(first, second);
|
||||
// A first element with no path leaves the text without one.
|
||||
let (doc, warnings) = imported(&format!(r#"<g id="p"/><path id="p" d="M0 80L150 80"/>{text}"#), false);
|
||||
assert!(!matches!(text_objects(&doc)[0].kind, TextKind::OnPath { .. }), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// Times importing a file with 20,000 paths and 2,000 texts on paths, finding each `<textPath>`'s
|
||||
/// element through the map of ids and by walking the document for each one, after checking that
|
||||
/// the two give the same document. Run it with
|
||||
/// `cargo test --release -p vectorcraft-svg --lib text_path_lookup_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "timing; run by hand in a release build"]
|
||||
fn text_path_lookup_timing() {
|
||||
let mut body = String::new();
|
||||
for i in 0..20_000 {
|
||||
let _ = write!(body, r#"<path id="p{i}" d="M0 {}L300 {}"/>"#, i % 400, i % 400);
|
||||
if i % 10 == 9 {
|
||||
let k = (i * 7919) % 20_000;
|
||||
let _ = write!(body, r##"<text font-size="8"><textPath href="#p{k}">L{i}</textPath></text>"##);
|
||||
}
|
||||
}
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">{body}</svg>"#);
|
||||
let run = |linear: bool| {
|
||||
LINEAR_IDS.set(linear);
|
||||
let start = std::time::Instant::now();
|
||||
let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES);
|
||||
let took = start.elapsed();
|
||||
LINEAR_IDS.set(false);
|
||||
(out.unwrap_or_else(|e| panic!("{e}")), took)
|
||||
};
|
||||
let (map, _) = run(false);
|
||||
let (walk, _) = run(true);
|
||||
assert_eq!(map, walk);
|
||||
assert_eq!(text_objects(&map.0).len(), 2_000);
|
||||
let (mut maps, mut walks) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
walks.push(run(true).1);
|
||||
maps.push(run(false).1);
|
||||
}
|
||||
println!("walk per textPath: {walks:?}");
|
||||
println!("map of ids: {maps:?}");
|
||||
walks.sort();
|
||||
maps.sort();
|
||||
println!("median: walk {:?}, map {:?}", walks[3], maps[3]);
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
//! Delete: click an anchor to remove it, re-fitting the neighbouring curve (Alt = add).
|
||||
//! Anchor Point: click a smooth anchor → corner; drag an anchor → pull out smooth handles; click a
|
||||
//! handle end → retract that handle only (#2267); drag a handle → move it independently (Shift: at
|
||||
//! 45° steps round its anchor); drag a segment → reshape the curve, a selected blend's spine's too,
|
||||
//! 45° steps round its anchor; Alt: link it with the opposite handle, the anchor made smooth, except
|
||||
//! when the Pen lends the tool); drag a segment → reshape the curve, a selected blend's spine's too,
|
||||
//! straight or curved (#1111; Shift: its handles at right angles to the line between its anchors,
|
||||
//! at one length). Shift held at the press on an anchor moves it instead, handles and all (Shift
|
||||
//! still held: at 45° steps from where it was). Space held during a convert- or handle-drag moves
|
||||
@@ -103,6 +104,9 @@ pub struct AnchorTool {
|
||||
measure: Option<(Point, f64, f64)>,
|
||||
/// While Space is held during a convert/handle drag, the shape gesture to return to.
|
||||
space_resume: Option<SpaceResume>,
|
||||
/// Lent by the Pen for its Alt gestures: Alt-dragging a handle moves it independently, as
|
||||
/// without Alt, instead of linking it with the opposite handle.
|
||||
lent: bool,
|
||||
}
|
||||
|
||||
impl AnchorTool {
|
||||
@@ -113,7 +117,20 @@ impl AnchorTool {
|
||||
"scissors" => "scissors",
|
||||
_ => "addAnchor",
|
||||
};
|
||||
Self { id, state: State::Idle, guides: vec![], snap: HandleSnap::default(), measure: None, space_resume: None }
|
||||
Self { id, state: State::Idle, guides: vec![], snap: HandleSnap::default(), measure: None, space_resume: None, lent: false }
|
||||
}
|
||||
|
||||
/// The Anchor Point tool as the Pen lends it with Alt held: an Alt-drag on a handle moves only
|
||||
/// that handle.
|
||||
pub(crate) fn lent_by_pen() -> Self {
|
||||
Self { lent: true, ..Self::new("anchorPoint") }
|
||||
}
|
||||
|
||||
/// The handle-drag params: Alt held on the chosen Anchor Point tool links the handle with the
|
||||
/// opposite one, making the anchor smooth; otherwise the handle moves independently.
|
||||
fn handle_mode(&self, mut params: serde_json::Value, alt: bool) -> serde_json::Value {
|
||||
params[if alt && !self.lent { "link" } else { "independent" }] = json!(true);
|
||||
params
|
||||
}
|
||||
|
||||
fn anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option<Point> {
|
||||
@@ -458,7 +475,10 @@ impl Tool for AnchorTool {
|
||||
};
|
||||
Action::Preview(
|
||||
"object.blend.spine.moveAnchor".into(),
|
||||
json!({"id": id.0, "anchor": ai, "handle": if out { "out" } else { "in" }, "x": q.x, "y": q.y, "independent": true}),
|
||||
self.handle_mode(
|
||||
json!({"id": id.0, "anchor": ai, "handle": if out { "out" } else { "in" }, "x": q.x, "y": q.y}),
|
||||
ev.mods.alt,
|
||||
),
|
||||
)
|
||||
}
|
||||
State::Handle { id, si, ai, out, .. } => {
|
||||
@@ -466,7 +486,10 @@ impl Tool for AnchorTool {
|
||||
self.guides = guides;
|
||||
Action::Preview(
|
||||
"path.setHandle".into(),
|
||||
json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" }, "x": q.x, "y": q.y, "independent": true}),
|
||||
self.handle_mode(
|
||||
json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" }, "x": q.x, "y": q.y}),
|
||||
ev.mods.alt,
|
||||
),
|
||||
)
|
||||
}
|
||||
State::Reshape { id, seg, t, start, spine: true, .. } => Action::Preview(
|
||||
|
||||
@@ -610,3 +610,88 @@ fn anchor_point_shift_drag_honors_measurement_labels() {
|
||||
assert!(t.overlays(&on).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &want)));
|
||||
assert!(!t.overlays(&off).iter().any(|o| matches!(o, Overlay::Measure { .. })));
|
||||
}
|
||||
|
||||
/// Alt held while dragging a handle links it with the opposite handle (`link`), making the
|
||||
/// anchor smooth; without Alt the handle moves on its own. Shift with Alt keeps the 45° steps, an
|
||||
/// Alt-click still retracts the handle, and Escape cancels the linking drag. The Pen, lending the
|
||||
/// tool for its Alt gestures, keeps moving the handle on its own.
|
||||
#[test]
|
||||
fn anchor_point_alt_drag_links_a_handle_with_the_opposite_one() {
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(300.0, 300.0)], false);
|
||||
// A corner: handles at (240, 320) and (170, 320), not in line.
|
||||
sp.anchors[1] = Anchor::with_handles(Point::new(200.0, 300.0), Point::new(170.0, 320.0), Point::new(240.0, 320.0));
|
||||
let path = vectorcraft_geom::PathData::single(sp);
|
||||
d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.set([id]);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let drag = |t: &mut AnchorTool, mods: Mods, x: f64, y: f64| {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 240.0, 320.0).with_mods(mods));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y).with_mods(mods))
|
||||
};
|
||||
let set = |x: f64, y: f64, key: &str| {
|
||||
let mut params = json!({"id": id.0, "subpath": 0, "anchor": 1, "which": "out", "x": x, "y": y});
|
||||
params[key] = json!(true);
|
||||
Action::Preview("path.setHandle".into(), params)
|
||||
};
|
||||
|
||||
let mut t = AnchorTool::new("anchorPoint");
|
||||
assert_eq!(drag(&mut t, alt, 250.0, 340.0), vec![Action::Begin("Reshape".into()), set(250.0, 340.0, "link")]);
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 340.0).with_mods(alt)), vec![Action::Commit]);
|
||||
// Without Alt the handle moves on its own, as before.
|
||||
assert_eq!(drag(&mut t, Mods::default(), 250.0, 340.0), vec![Action::Begin("Reshape".into()), set(250.0, 340.0, "independent")]);
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 340.0));
|
||||
|
||||
// Shift with Alt: the linked handle stays at 45° steps round its anchor.
|
||||
let shift_alt = Mods { shift: true, alt: true, ..Mods::default() };
|
||||
let a = drag(&mut t, shift_alt, 250.0, 345.0);
|
||||
let Some(Action::Preview(c, args)) = a.get(1) else { panic!("{a:?}") };
|
||||
assert_eq!((c.as_str(), &args["link"], args.get("independent")), ("path.setHandle", &json!(true), None));
|
||||
let (dx, dy) = (args["x"].as_f64().unwrap_or(f64::NAN) - 200.0, args["y"].as_f64().unwrap_or(f64::NAN) - 300.0);
|
||||
assert!(dx > 0.0 && (dx - dy).abs() < 1e-6, "{args}");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 345.0));
|
||||
|
||||
// An Alt-click on the handle retracts it, as a click without Alt does.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 240.0, 320.0).with_mods(alt));
|
||||
assert_eq!(
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 240.0, 320.0).with_mods(alt)),
|
||||
vec![Action::Exec(
|
||||
"path.setHandle".into(),
|
||||
json!({"id": id.0, "subpath": 0, "anchor": 1, "which": "out", "x": 200.0, "y": 300.0, "independent": true})
|
||||
)]
|
||||
);
|
||||
|
||||
// Escape cancels the linking drag; its release does nothing.
|
||||
drag(&mut t, alt, 250.0, 340.0);
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
|
||||
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 340.0).with_mods(alt)).is_empty());
|
||||
|
||||
// Lent by the Pen, Alt-drag moves the handle on its own.
|
||||
let mut lent = AnchorTool::lent_by_pen();
|
||||
assert_eq!(drag(&mut lent, alt, 250.0, 340.0), vec![Action::Begin("Reshape".into()), set(250.0, 340.0, "independent")]);
|
||||
}
|
||||
|
||||
/// Alt-dragging a selected blend's spine handle links it with the opposite one.
|
||||
#[test]
|
||||
fn anchor_point_alt_drag_links_a_blend_spine_handle() {
|
||||
let (d, id, sel) = blend_spine_doc(true);
|
||||
let p = paint();
|
||||
let c = cx(&d, &sel, &p);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let mut tool = AnchorTool::new("anchorPoint");
|
||||
tool.pointer(&c, &PointerEvent::new(PointerKind::Down, 190.0, 330.0).with_mods(alt));
|
||||
let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Drag, 190.0, 350.0).with_mods(alt));
|
||||
assert_eq!(
|
||||
actions.get(1),
|
||||
Some(&Action::Preview(
|
||||
"object.blend.spine.moveAnchor".into(),
|
||||
json!({"id": id.0, "anchor": 1, "handle": "out", "x": 190.0, "y": 350.0, "link": true})
|
||||
))
|
||||
);
|
||||
assert_eq!(tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 190.0, 350.0).with_mods(alt)), vec![Action::Commit]);
|
||||
}
|
||||
+155
-4
@@ -6,7 +6,9 @@
|
||||
//! on macOS) draws a flare there with them at once), then a click sets the
|
||||
//! end point of the rings (↑/↓ add or remove rings and ~ places them anew); Space held during
|
||||
//! either drag moves the flare. The rest comes
|
||||
//! from the tool's options (the Flare Tool Options, which last). Reshape: a click on a selected
|
||||
//! from the tool's options (the Flare Tool Options, which last). With one flare selected, the tool
|
||||
//! shows its center and end handles, and dragging either changes the flare's length and direction
|
||||
//! (`shape.editFlare`). Reshape: a click on a selected
|
||||
//! path sets a focal point (adding an anchor on a segment), Shift-click adds or removes more, and
|
||||
//! a drag from a focal point moves them all; the engine's `path.reshape` stretches the selected
|
||||
//! anchors between them and the anchors that stay.
|
||||
@@ -83,6 +85,40 @@ pub struct FlareTool {
|
||||
/// Whether the flare has rays and rings (the options' Rays and Rings checkboxes).
|
||||
rays_on: bool,
|
||||
rings_on: bool,
|
||||
/// A drag of the selected flare's center or end handle.
|
||||
handle: Option<HandleDrag>,
|
||||
}
|
||||
|
||||
/// A drag of a selected flare's handle: the flare, whether it is the end handle (else the center),
|
||||
/// where the handle was, where it was pressed, whether Alt (Option on macOS) was held at the press
|
||||
/// and whether the drag has begun its undo step.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct HandleDrag {
|
||||
id: vectorcraft_doc::NodeId,
|
||||
end: bool,
|
||||
from: Point,
|
||||
at: Point,
|
||||
alt: bool,
|
||||
began: bool,
|
||||
}
|
||||
|
||||
/// The flare whose handles the Flare tool shows: the one selected object, when it is a flare that
|
||||
/// can be edited, with its center and the rings' end point.
|
||||
fn selected_flare(cx: &ToolContext) -> Option<(vectorcraft_doc::NodeId, Point, Point)> {
|
||||
let [id] = cx.selection.objects.as_slice() else { return None };
|
||||
if !cx.doc.is_editable(*id) {
|
||||
return None;
|
||||
}
|
||||
let node = cx.doc.node(*id)?;
|
||||
let spec = node.extras().flare.as_deref().filter(|spec| spec.draws(node))?;
|
||||
Some((*id, spec.center()?, spec.end()?))
|
||||
}
|
||||
|
||||
/// `shape.editFlare`'s params for handle drag `h` with the pointer at `pointer`: the handle moves
|
||||
/// as far as the pointer has.
|
||||
fn handle_params(h: HandleDrag, pointer: Point) -> Value {
|
||||
let p = h.from + (pointer - h.at);
|
||||
if h.end { json!({ "ids": [h.id.0], "x2": p.x, "y2": p.y }) } else { json!({ "ids": [h.id.0], "cx": p.x, "cy": p.y }) }
|
||||
}
|
||||
|
||||
impl Default for FlareTool {
|
||||
@@ -104,6 +140,7 @@ impl Default for FlareTool {
|
||||
values: FLARE_OPTIONS.map(|(_, default, _, _)| default),
|
||||
rays_on: true,
|
||||
rings_on: true,
|
||||
handle: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -251,7 +288,7 @@ impl Tool for FlareTool {
|
||||
"flare"
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
self.drag.is_some() || self.placed.is_some()
|
||||
self.drag.is_some() || self.placed.is_some() || self.handle.is_some()
|
||||
}
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
self.hover = ev.pos;
|
||||
@@ -261,8 +298,43 @@ impl Tool for FlareTool {
|
||||
if quote_pressed && self.rings_on && self.placed.is_some() && matches!(ev.kind, PointerKind::Drag | PointerKind::Move | PointerKind::Up) {
|
||||
self.ring_seed = Some(next_ring_seed(self.ring_seed, ev.pos));
|
||||
}
|
||||
if let Some(mut h) = self.handle {
|
||||
return match ev.kind {
|
||||
PointerKind::Drag if h.began => vec![Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos))],
|
||||
PointerKind::Drag if ev.pos.distance(h.at) < cx.tol(3.0) => vec![],
|
||||
PointerKind::Drag => {
|
||||
h.began = true;
|
||||
self.handle = Some(h);
|
||||
vec![Action::Begin("Edit Flare".into()), Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos))]
|
||||
}
|
||||
PointerKind::Up => {
|
||||
self.handle = None;
|
||||
if h.began {
|
||||
vec![Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos)), Action::Commit]
|
||||
} else if h.alt {
|
||||
// A click on a handle without a drag is a click with the tool.
|
||||
self.click_flare(cx, h.at)
|
||||
} else {
|
||||
vec![Action::Dialog("flare".into(), json!({ "x": h.at.x, "y": h.at.y }))]
|
||||
}
|
||||
}
|
||||
_ => vec![],
|
||||
};
|
||||
}
|
||||
match ev.kind {
|
||||
PointerKind::Down => {
|
||||
// A press on the selected flare's center or end handle drags that handle.
|
||||
if self.placed.is_none()
|
||||
&& let Some((id, c, e)) = selected_flare(cx)
|
||||
{
|
||||
let tol = cx.tol(4.0);
|
||||
let (dc, de) = (ev.pos.distance(c), ev.pos.distance(e));
|
||||
if dc.min(de) <= tol {
|
||||
let end = de < dc;
|
||||
self.handle = Some(HandleDrag { id, end, from: if end { e } else { c }, at: ev.pos, alt: ev.mods.alt, began: false });
|
||||
return vec![];
|
||||
}
|
||||
}
|
||||
if self.placed.is_none() {
|
||||
self.drag = Some((ev.pos, ev.pos));
|
||||
self.rays = None;
|
||||
@@ -350,6 +422,11 @@ impl Tool for FlareTool {
|
||||
};
|
||||
return vec![Action::Preview("shape.flare".into(), preview)];
|
||||
}
|
||||
if key == ToolKey::Escape
|
||||
&& let Some(h) = self.handle.take()
|
||||
{
|
||||
return if h.began { vec![Action::Cancel] } else { vec![] };
|
||||
}
|
||||
if key == ToolKey::Escape && self.busy() {
|
||||
self.rays = None;
|
||||
self.rings = None;
|
||||
@@ -367,16 +444,27 @@ impl Tool for FlareTool {
|
||||
// Switching away after the centre drag keeps the flare with the rings its options give.
|
||||
self.drag = None;
|
||||
self.held = None;
|
||||
if self.handle.take().is_some_and(|h| h.began) {
|
||||
return vec![Action::Commit];
|
||||
}
|
||||
if self.placed.take().is_some() && std::mem::take(&mut self.began) { vec![Action::Commit] } else { vec![] }
|
||||
}
|
||||
fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
match (self.drag, self.placed) {
|
||||
(Some((c, p)), _) => {
|
||||
let r = self.center_diameter(p.distance(c)) / 2.0;
|
||||
vec![Overlay::Path { path: ellipse_path(c, r, r, 0.0), color: BLUE, width: 1.0, dashed: false }]
|
||||
}
|
||||
(_, Some((c, _))) => vec![Overlay::Line { a: c, b: self.hover, color: BLUE, dashed: true }],
|
||||
_ => vec![],
|
||||
// The selected flare's center and end handles.
|
||||
_ => match selected_flare(cx) {
|
||||
Some((_, c, e)) => vec![
|
||||
Overlay::Line { a: c, b: e, color: BLUE, dashed: true },
|
||||
Overlay::Anchor { p: c, color: BLUE, filled: self.handle.is_some_and(|h| !h.end), size: 7.0 },
|
||||
Overlay::Anchor { p: e, color: BLUE, filled: self.handle.is_some_and(|h| h.end), size: 7.0 },
|
||||
],
|
||||
None => vec![],
|
||||
},
|
||||
}
|
||||
}
|
||||
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
|
||||
@@ -1021,6 +1109,69 @@ mod tests {
|
||||
assert_eq!(t.turn, 10.0);
|
||||
}
|
||||
|
||||
/// With one flare selected, the tool shows its center and end handles where the flare is now
|
||||
/// drawn, and dragging either edits the flare (`shape.editFlare`) as one undo step; a press
|
||||
/// away from them draws a new flare.
|
||||
#[test]
|
||||
fn dragging_a_selected_flares_handles_changes_its_length_and_direction() {
|
||||
use crate::testutil::*;
|
||||
use vectorcraft_doc::flare::{FlareSpec, part_node, parts};
|
||||
use vectorcraft_doc::{Node, Selection};
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let gid = d.alloc_id();
|
||||
let v = json!({ "cx": 100.0, "cy": 100.0, "x2": 300.0, "y2": 100.0, "rays": 3, "rings": 2, "seed": 5, "diameter": 30.0,
|
||||
"opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0,
|
||||
"rotation": 0.0, "largest": 50.0 });
|
||||
let xf = vectorcraft_geom::Affine::translate((10.0, 20.0));
|
||||
let children: Vec<_> = parts(&v).into_iter().map(|part| std::sync::Arc::new(part_node(d.alloc_id(), part, xf, false))).collect();
|
||||
let edited = children[0].id;
|
||||
let mut g = Node::group(gid, children);
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v, transform: xf }));
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, g).unwrap_or_else(|e| panic!("{e}"));
|
||||
let s = Selection { objects: vec![gid], ..Default::default() };
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = FlareTool::default();
|
||||
let ov = t.overlays(&cx);
|
||||
let anchors: Vec<Point> = ov.iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(*p) } else { None }).collect();
|
||||
assert_eq!(anchors, vec![Point::new(110.0, 120.0), Point::new(310.0, 120.0)]);
|
||||
// The end handle, grabbed 2 points off: it moves as far as the pointer.
|
||||
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 312.0, 120.0)).is_empty());
|
||||
assert!(t.busy());
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 312.0, 160.0));
|
||||
assert_eq!(a.first(), Some(&Action::Begin("Edit Flare".into())));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 302.0, 200.0));
|
||||
assert_eq!(a, vec![Action::Preview("shape.editFlare".into(), json!({ "ids": [gid.0], "x2": 300.0, "y2": 200.0 })), Action::Commit]);
|
||||
// The center handle; Escape cancels its drag.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 121.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 121.0));
|
||||
assert_eq!(a.last(), Some(&Action::Preview("shape.editFlare".into(), json!({ "ids": [gid.0], "cx": 150.0, "cy": 120.0 }))));
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
|
||||
assert!(!t.busy());
|
||||
// A click on a handle without a drag is a click with the tool: it opens the dialog, and
|
||||
// with Alt held it draws a flare there with the tool's options.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 120.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 120.0));
|
||||
assert_eq!(a, vec![Action::Dialog("flare".into(), json!({ "x": 110.0, "y": 120.0 }))]);
|
||||
assert!(!t.busy());
|
||||
let alt = Mods { alt: true, ..Default::default() };
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 310.0, 121.0).with_mods(alt));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 310.0, 121.0).with_mods(alt));
|
||||
assert_eq!(a, vec![Action::Exec("shape.flare".into(), flare_params(&t.options(), Point::new(310.0, 121.0)))]);
|
||||
assert!(!t.busy());
|
||||
// Away from the handles a drag draws a new flare.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 300.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 240.0, 300.0));
|
||||
assert_eq!(a.first(), Some(&Action::Begin("Flare".into())));
|
||||
// Without a flare selected, no handles show.
|
||||
let none = Selection::default();
|
||||
assert!(FlareTool::default().overlays(&crate::testutil::cx(&d, &none, &p)).is_empty());
|
||||
// A flare with an edited part is no longer edited as a flare: no handles show.
|
||||
d.node_mut(edited).unwrap_or_else(|| panic!("no part")).opacity = 0.25;
|
||||
assert!(FlareTool::default().overlays(&crate::testutil::cx(&d, &s, &p)).is_empty());
|
||||
}
|
||||
|
||||
/// Space held while dragging out a flare moves it at its current size and turn, in the center
|
||||
/// drag and in the drag that places the rings' end point; let go, the drag goes on from there.
|
||||
#[test]
|
||||
|
||||
@@ -679,6 +679,19 @@ pub(crate) mod testutil {
|
||||
global_edit: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Held for reading by tests that count the layouts the Type tool keeps, and for writing by
|
||||
/// tests that change what layout reads (fonts, hyphenation exceptions): tests run in parallel,
|
||||
/// and a count must not include a refresh another test caused.
|
||||
static LAYOUT_INPUTS: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
pub fn steady_layout_inputs() -> std::sync::RwLockReadGuard<'static, ()> {
|
||||
LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
pub fn changing_layout_inputs() -> std::sync::RwLockWriteGuard<'static, ()> {
|
||||
LAYOUT_INPUTS.write().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -631,7 +631,7 @@ impl PenTool {
|
||||
if !alt_converts(cx, ev.pos, ev.mods) {
|
||||
return None;
|
||||
}
|
||||
let mut t = AnchorTool::new("anchorPoint");
|
||||
let mut t = AnchorTool::lent_by_pen();
|
||||
let acts = t.pointer(cx, ev);
|
||||
if !t.busy() {
|
||||
return None;
|
||||
|
||||
@@ -1412,11 +1412,17 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option<NodeId> {
|
||||
/// object selected whole between it and the art under the pointer, such as members of a group
|
||||
/// picked with Group Selection. A press there keeps the selection and a drag moves it (#8047). A
|
||||
/// member with only some anchors or segments selected does not count: the press selects `top`.
|
||||
/// A member with every anchor selected (as `select.anchors` and `select.key` leave a path) counts.
|
||||
fn selected_under(cx: &ToolContext, h: &Hit, top: NodeId) -> Option<NodeId> {
|
||||
if cx.selection.contains(top) {
|
||||
return Some(top);
|
||||
}
|
||||
let whole = |id: NodeId| cx.selection.contains(id) && cx.selection.partial(id).is_none() && !cx.selection.segments.contains_key(&id);
|
||||
let every_anchor = |id: NodeId| {
|
||||
cx.selection
|
||||
.partial(id)
|
||||
.is_none_or(|picked| cx.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().all(|(s, i, _)| picked.contains(&(s, i)))))
|
||||
};
|
||||
let whole = |id: NodeId| cx.selection.contains(id) && every_anchor(id) && !cx.selection.segments.contains_key(&id);
|
||||
let below = h.ancestry.iter().position(|id| *id == top).map_or(&[][..], |i| h.ancestry.get(i..).unwrap_or_default());
|
||||
below.iter().copied().chain(std::iter::once(h.leaf)).find(|id| whole(*id))
|
||||
}
|
||||
|
||||
@@ -2889,4 +2889,12 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
|
||||
let c = cx(&d, &s, &p);
|
||||
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
|
||||
assert_eq!(down, vec![Action::Exec("select.set".into(), json!({"ids": [outer.0]}))]);
|
||||
// Every anchor of the member picked (as `select.anchors` and `select.key` leave it) selects
|
||||
// it whole: the press moves it.
|
||||
s.anchors.insert(a, [(0, 0), (0, 1), (0, 2), (0, 3)].into_iter().collect());
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "every anchor");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
|
||||
assert!(!is_select(&down), "every anchor: {down:?}");
|
||||
}
|
||||
@@ -1327,6 +1327,7 @@ fn area_type_drag_measure_labels_honor_preference() {
|
||||
|
||||
#[test]
|
||||
fn layout_cache_follows_fonts_added_later() {
|
||||
let _inputs = crate::testutil::changing_layout_inputs();
|
||||
// Other tests can load system fonts; this assertion needs its own process-wide database.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") {
|
||||
@@ -1542,6 +1543,7 @@ fn selected_type_shows_its_ports_in_each_state() {
|
||||
/// Preferences › Hyphenation › Exceptions change, the selected type is laid out again.
|
||||
#[test]
|
||||
fn the_out_port_follows_the_hyphenation_exceptions() {
|
||||
let _inputs = crate::testutil::changing_layout_inputs();
|
||||
struct Clear;
|
||||
impl Drop for Clear {
|
||||
fn drop(&mut self) {
|
||||
@@ -1690,6 +1692,7 @@ const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hund
|
||||
/// overlays as a tool that lays every frame out afresh.
|
||||
#[test]
|
||||
fn type_overlays_keep_the_selected_frames_layouts() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
let (d, ids) = area_frames(&["One", "Two words", "Three words here", OVERFLOWS]);
|
||||
let (mut sel, p) = (Selection::default(), paint());
|
||||
sel.set(ids.iter().copied());
|
||||
@@ -1721,6 +1724,7 @@ fn type_overlays_keep_the_selected_frames_layouts() {
|
||||
/// out again on the next frame.
|
||||
#[test]
|
||||
fn type_overlays_keep_a_selected_storys_layouts() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
let (mut d, ids) = area_frames(&["Story one ", "story two ", "story three ", "story four"]);
|
||||
d.text_threads.push(ids.clone());
|
||||
let (mut sel, p) = (Selection::default(), paint());
|
||||
@@ -1749,6 +1753,7 @@ fn type_overlays_keep_a_selected_storys_layouts() {
|
||||
/// longer drawn is dropped, and choosing another tool drops them all.
|
||||
#[test]
|
||||
fn type_overlays_lay_out_again_only_the_frames_that_changed() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
let (mut d, ids) = area_frames(&["One", "Two", "Three", OVERFLOWS]);
|
||||
let (mut sel, p) = (Selection::default(), paint());
|
||||
sel.set(ids.iter().copied());
|
||||
@@ -1786,6 +1791,7 @@ fn type_overlays_lay_out_again_only_the_frames_that_changed() {
|
||||
/// each call, and draws what laying every frame out afresh draws.
|
||||
#[test]
|
||||
fn type_overlays_keep_at_most_frame_layouts_max() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
let texts = vec!["a "; FRAME_LAYOUTS_MAX + 3];
|
||||
let (mut d, ids) = area_frames(&texts);
|
||||
d.text_threads.push(ids.clone());
|
||||
@@ -1806,6 +1812,7 @@ fn type_overlays_keep_at_most_frame_layouts_max() {
|
||||
|
||||
#[test]
|
||||
fn frame_layouts_follow_fonts_and_hyphenation_exceptions() {
|
||||
let _inputs = crate::testutil::changing_layout_inputs();
|
||||
// Other tests can load system fonts; this assertion needs its own process-wide database.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") {
|
||||
@@ -1848,6 +1855,7 @@ fn frame_layouts_follow_fonts_and_hyphenation_exceptions() {
|
||||
#[test]
|
||||
#[ignore = "timing, run by hand"]
|
||||
fn type_overlays_timing() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
use std::time::Instant;
|
||||
let words = "The quick brown fox jumps over the lazy dog while seven wizards box. ".repeat(6);
|
||||
let texts: Vec<String> = (0..200).map(|i| format!("{i} {words}")).collect();
|
||||
|
||||
@@ -470,6 +470,7 @@ fn the_tool_is_made_by_its_id() {
|
||||
|
||||
#[test]
|
||||
fn touch_type_rtl_middle_character_can_drag_and_nudge_along_its_line() {
|
||||
let _inputs = crate::testutil::changing_layout_inputs();
|
||||
use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font};
|
||||
|
||||
// The process-wide database deduplicates the same synthetic face across tests.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller
|
||||
//! circle's radius, Keep Originals), which previews on the canvas and runs `addon.pathtools.bridge`
|
||||
//! on OK.
|
||||
//! circle's radius, or with Constant Gap that radius plus a gap; the reach, unavailable with two
|
||||
//! circles selected; Keep Originals), which previews on the canvas and runs
|
||||
//! `addon.pathtools.bridge` on OK.
|
||||
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
@@ -16,27 +17,61 @@ pub const KIND: &str = "smoothBridge";
|
||||
/// The radius the command takes (%), and its default.
|
||||
const RADII: std::ops::RangeInclusive<f64> = 1.0..=1000.0;
|
||||
const RADIUS: f64 = 100.0;
|
||||
/// The gap the command takes (pt), and the dialog's first one.
|
||||
const GAPS: std::ops::RangeInclusive<f64> = 0.0..=1000.0;
|
||||
const GAP: f64 = 4.0;
|
||||
/// The reach the command takes (pt), and its default.
|
||||
const REACHES: std::ops::RangeInclusive<f64> = 0.0..=10000.0;
|
||||
const REACH: f64 = 10.0;
|
||||
const LABEL_W: f32 = 60.0;
|
||||
const FIELD_W: f32 = 90.0;
|
||||
|
||||
/// The dialog's fields to start with: the command's defaults.
|
||||
pub(crate) fn fields() -> Value {
|
||||
json!({ "radius": RADIUS, "keepOriginals": false })
|
||||
json!({ "radius": RADIUS, "constantGap": false, "gap": GAP, "reach": REACH, "keepOriginals": false })
|
||||
}
|
||||
|
||||
pub(crate) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Smooth Bridge").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM };
|
||||
|
||||
/// The command's parameters from the dialog's fields.
|
||||
/// The command's parameters from the dialog's fields: the radius, or with Constant Gap the gap.
|
||||
fn params(d: &Dialog) -> Value {
|
||||
json!({ "radius": d.f64("radius", RADIUS), "keepOriginals": d.bool("keepOriginals") })
|
||||
let (reach, keep) = (d.f64("reach", REACH), d.bool("keepOriginals"));
|
||||
if d.bool("constantGap") {
|
||||
json!({ "gap": d.f64("gap", GAP), "reach": reach, "keepOriginals": keep })
|
||||
} else {
|
||||
json!({ "radius": d.f64("radius", RADIUS), "reach": reach, "keepOriginals": keep })
|
||||
}
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| {
|
||||
if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) {
|
||||
d.fields.insert("radius".into(), json!(v));
|
||||
let unit = app.session.general_unit();
|
||||
form::check(ui, d, "constantGap", tl!("Constant Gap"));
|
||||
if d.bool("constantGap") {
|
||||
widgets::label_row(ui, tl!("Gap:"), LABEL_W, |ui| {
|
||||
form::length_within(ui, d, "gap", unit, FIELD_W, Some(GAPS));
|
||||
});
|
||||
} else {
|
||||
widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| {
|
||||
if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) {
|
||||
d.fields.insert("radius".into(), json!(v));
|
||||
}
|
||||
});
|
||||
}
|
||||
// The reach applies to three or more circles; two are bridged at any distance. Counted once,
|
||||
// before a preview replaces the selection with its result.
|
||||
let many = match d.fields.get("many").and_then(Value::as_bool) {
|
||||
Some(many) => many,
|
||||
None => {
|
||||
let many = app.session.doc().map(|doc| doc.selection.objects.len() > 2).unwrap_or(true);
|
||||
d.fields.insert("many".into(), json!(many));
|
||||
many
|
||||
}
|
||||
};
|
||||
ui.add_enabled_ui(many, |ui| {
|
||||
widgets::label_row(ui, tl!("Reach:"), LABEL_W, |ui| {
|
||||
form::length_within(ui, d, "reach", unit, FIELD_W, Some(REACHES));
|
||||
});
|
||||
});
|
||||
form::check(ui, d, "keepOriginals", tl!("Keep Originals"));
|
||||
form::preview(app, ui, d, "Smooth Bridge", COMMAND, params(d));
|
||||
@@ -72,9 +107,11 @@ mod tests {
|
||||
menus::invoke(&mut app, &cmd, p);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND));
|
||||
let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
for s in ["Smooth Bridge", "Radius:", "Keep Originals", "Preview"] {
|
||||
for s in ["Smooth Bridge", "Constant Gap", "Radius:", "Reach:", "Keep Originals", "Preview"] {
|
||||
assert!(shown.contains(s), "{s} in {shown}");
|
||||
}
|
||||
assert!(!shown.contains("Gap:"), "{shown}");
|
||||
assert!(!app.ui.dialog.as_ref().unwrap().bool("many"), "Reach unavailable for two circles");
|
||||
let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
@@ -89,4 +126,30 @@ mod tests {
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1);
|
||||
assert_eq!(count(&app), 3, "the circles and the outline above them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
// Three circles 4 apart in a row and one far off.
|
||||
let ids: Vec<u64> = [100.0, 124.0, 148.0, 300.0].iter().map(|&x| circle(&mut app, x, 10.0)).collect();
|
||||
app.run("select.set", json!({ "ids": ids })).unwrap();
|
||||
menus::invoke(&mut app, super::COMMAND, serde_json::Value::Null);
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("constantGap".into(), json!(true));
|
||||
let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
assert!(shown.contains("Gap:") && !shown.contains("Radius:"), "{shown}");
|
||||
// A preview leaves two objects selected (one shape and the far circle); Reach stays
|
||||
// available for the four circles the command still bridges.
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed");
|
||||
assert!(app.ui.dialog.as_ref().unwrap().bool("many"), "Reach available for four circles");
|
||||
let p = super::params(app.ui.dialog.as_ref().unwrap());
|
||||
assert_eq!(p, json!({"gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius");
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
let top: Vec<u64> = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
|
||||
assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle");
|
||||
}
|
||||
}
|
||||
@@ -198,6 +198,7 @@ impl VectorcraftApp {
|
||||
input_frames: vec![],
|
||||
shortcuts_frames: vec![],
|
||||
held_tool: Vec::new(),
|
||||
hold_keys: Default::default(),
|
||||
synthetic_injected: false,
|
||||
injected_events: vec![],
|
||||
injected_generation: InputGeneration::default(),
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Background Save and Background Export (Preferences → File Handling): a save or an export encodes
|
||||
//! and writes a snapshot of the document on a worker thread while editing goes on. The status bar
|
||||
//! shows what is in progress; the result is applied on the UI thread when it arrives (a save marks
|
||||
//! the document saved as of its snapshot, so edits made meanwhile keep it modified).
|
||||
//! the document saved as of its snapshot, so edits made meanwhile keep it modified). Exports and
|
||||
//! saves show in the progress window ([`crate::export_progress`]) with Cancel and Continue in
|
||||
//! Background.
|
||||
//!
|
||||
//! It needs a thread-safe writer from the host ([`crate::Services::write_shared`], desktop);
|
||||
//! without one (the web, which downloads) the work runs at once, as with the preference off.
|
||||
@@ -44,15 +46,27 @@ struct Task {
|
||||
scope: ScopeHandle,
|
||||
}
|
||||
|
||||
/// What a job that shows in the progress window does: its Cancel and Continue in Background act on
|
||||
/// the jobs of its kind.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// An export (Background Export): `file.cancelExport`, `file.exportInBackground`.
|
||||
Export,
|
||||
/// A save (Background Save): `file.cancelSave`, `file.saveInBackground`.
|
||||
Save,
|
||||
}
|
||||
|
||||
/// A job in progress.
|
||||
pub struct Job {
|
||||
id: u64,
|
||||
/// What the job does, for the progress window and its commands.
|
||||
pub kind: Kind,
|
||||
/// What the status bar and `ui.inspect` show ("Saving Poster.vectorcraft"); empty for work they
|
||||
/// don't show.
|
||||
pub label: String,
|
||||
/// The document the job reads (`DocState::uid`), if any.
|
||||
pub doc: Option<u64>,
|
||||
/// How far an export has got, and its Cancel ([`crate::export_progress`] shows it).
|
||||
/// How far an export or a save has got, and its Cancel ([`crate::export_progress`] shows it).
|
||||
pub progress: Option<Arc<Progress>>,
|
||||
/// Continue in Background: the progress dialog no longer shows this job.
|
||||
pub hidden: bool,
|
||||
@@ -83,6 +97,9 @@ pub struct Background {
|
||||
next_id: u64,
|
||||
/// Work started while this is set runs at once, whatever the preferences ([`in_foreground`]).
|
||||
foreground: bool,
|
||||
/// [`crate::state::UiState::status_sets`] right after Cancel Save set its line, or after a save
|
||||
/// it reached set the line that followed it; `None` before any Cancel Save.
|
||||
pub(crate) save_cancel_line: Option<u64>,
|
||||
}
|
||||
|
||||
impl Background {
|
||||
@@ -119,18 +136,41 @@ impl Background {
|
||||
|
||||
/// Cancel every export in progress → how many there were.
|
||||
pub fn cancel_exports(&mut self) -> usize {
|
||||
self.cancel(Kind::Export)
|
||||
}
|
||||
|
||||
/// Hide the exports in progress from the progress dialog (they go on) → how many there were.
|
||||
pub fn hide_exports(&mut self) -> usize {
|
||||
self.hide(Kind::Export)
|
||||
}
|
||||
|
||||
/// Cancel every save in progress that the progress window can show → how many there were.
|
||||
pub fn cancel_saves(&mut self) -> usize {
|
||||
self.cancel(Kind::Save)
|
||||
}
|
||||
|
||||
/// Hide the saves in progress from the progress window (they go on) → how many there were.
|
||||
pub fn hide_saves(&mut self) -> usize {
|
||||
self.hide(Kind::Save)
|
||||
}
|
||||
|
||||
/// Is a job of `kind` in progress that can still be canceled?
|
||||
pub fn running(&self, kind: Kind) -> bool {
|
||||
self.jobs.iter().any(|j| j.kind == kind && j.progress.is_some() && !j.cancelled())
|
||||
}
|
||||
|
||||
fn cancel(&mut self, kind: Kind) -> usize {
|
||||
let mut n = 0;
|
||||
for p in self.jobs.iter().filter(|j| !j.cancelled()).filter_map(|j| j.progress.as_ref()) {
|
||||
for p in self.jobs.iter().filter(|j| j.kind == kind && !j.cancelled()).filter_map(|j| j.progress.as_ref()) {
|
||||
p.cancel();
|
||||
n += 1;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Hide the exports in progress from the progress dialog (they go on) → how many there were.
|
||||
pub fn hide_exports(&mut self) -> usize {
|
||||
fn hide(&mut self, kind: Kind) -> usize {
|
||||
let mut n = 0;
|
||||
for j in self.jobs.iter_mut().filter(|j| j.progress.is_some() && !j.hidden && !j.cancelled()) {
|
||||
for j in self.jobs.iter_mut().filter(|j| j.kind == kind && j.progress.is_some() && !j.hidden && !j.cancelled()) {
|
||||
j.hidden = true;
|
||||
n += 1;
|
||||
}
|
||||
@@ -163,6 +203,34 @@ pub fn run_with_progress(
|
||||
progress: Option<Arc<Progress>>,
|
||||
work: impl FnOnce(Writer) -> Result<Value, String> + Send + 'static,
|
||||
then: impl FnOnce(&mut VectorcraftApp, Result<Value, String>) -> Result<Value, String> + 'static,
|
||||
) -> Result<Value, String> {
|
||||
start(app, enabled, label, doc, progress, Kind::Export, work, then)
|
||||
}
|
||||
|
||||
/// [`run_with_progress`] for a save of document `doc`: the progress window shows it as a save, and
|
||||
/// its Cancel is `file.cancelSave`.
|
||||
pub fn run_saving(
|
||||
app: &mut VectorcraftApp,
|
||||
enabled: bool,
|
||||
label: String,
|
||||
doc: u64,
|
||||
progress: Arc<Progress>,
|
||||
work: impl FnOnce(Writer) -> Result<Value, String> + Send + 'static,
|
||||
then: impl FnOnce(&mut VectorcraftApp, Result<Value, String>) -> Result<Value, String> + 'static,
|
||||
) -> Result<Value, String> {
|
||||
start(app, enabled, label, Some(doc), Some(progress), Kind::Save, work, then)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn start(
|
||||
app: &mut VectorcraftApp,
|
||||
enabled: bool,
|
||||
label: String,
|
||||
doc: Option<u64>,
|
||||
progress: Option<Arc<Progress>>,
|
||||
kind: Kind,
|
||||
work: impl FnOnce(Writer) -> Result<Value, String> + Send + 'static,
|
||||
then: impl FnOnce(&mut VectorcraftApp, Result<Value, String>) -> Result<Value, String> + 'static,
|
||||
) -> Result<Value, String> {
|
||||
let mut work: Work = Box::new(work);
|
||||
let shared = app.services.write_shared.clone().filter(|_| enabled && !app.background.foreground && app.services.download.is_none());
|
||||
@@ -174,7 +242,8 @@ pub fn run_with_progress(
|
||||
let (sets, status) = (app.ui.status_sets, if label.is_empty() { String::new() } else { format!("{label}…") });
|
||||
let bg = &mut app.background;
|
||||
bg.next_id += 1;
|
||||
bg.jobs.push(Job { id, label: label.clone(), doc, progress, hidden: false, sets, line: status.clone(), then: Box::new(then) });
|
||||
let line = status.clone();
|
||||
bg.jobs.push(Job { id, kind, label: label.clone(), doc, progress, hidden: false, sets, line, then: Box::new(then) });
|
||||
if label.is_empty() {
|
||||
return Ok(json!({ "background": true }));
|
||||
}
|
||||
|
||||
@@ -10,12 +10,12 @@ use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::grid::LineLook;
|
||||
use super::outline::{c32, node_outline, stroke_path, too_many_anchors};
|
||||
use super::outline::{c32, node_outline, to_screen_path, too_many_anchors};
|
||||
use super::view::fit_zoom;
|
||||
use super::{
|
||||
Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key,
|
||||
dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers,
|
||||
shows_artboards, textured_quad, vec2, view_rects,
|
||||
Affine, BezPath, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop,
|
||||
cache_key, dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2,
|
||||
rulers, shows_artboards, textured_quad, vec2, view_rects,
|
||||
};
|
||||
use crate::doc_windows::Win;
|
||||
use crate::thumb_worker::ThumbWorker;
|
||||
@@ -46,6 +46,29 @@ pub struct Panes {
|
||||
/// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and
|
||||
/// center the fit gave.
|
||||
fits: HashMap<Slot, (egui::Vec2, f64, Point)>,
|
||||
/// By slot: the outlines of the selected objects the pane drew last, and what they show.
|
||||
outlines: HashMap<Slot, Outlines>,
|
||||
/// How many times a pane's outlines were made.
|
||||
outlines_made: u64,
|
||||
}
|
||||
|
||||
/// A pane's selected-object outlines as screen shapes, and the document revision, document,
|
||||
/// selection and screen mapping they were made for.
|
||||
struct Outlines {
|
||||
revision: u64,
|
||||
/// A weak reference to the document: while it exists, no other document can take the
|
||||
/// allocation's address.
|
||||
doc: std::sync::Weak<vectorcraft_doc::Document>,
|
||||
selection: Vec<vectorcraft_doc::NodeId>,
|
||||
affine: [f64; 6],
|
||||
shapes: Vec<egui::Shape>,
|
||||
}
|
||||
|
||||
impl Outlines {
|
||||
/// Whether these outlines show `st`'s selection through the screen mapping `affine`.
|
||||
fn shows(&self, st: &vectorcraft_engine::DocState, affine: &[f64; 6]) -> bool {
|
||||
self.revision == st.revision && self.doc.ptr_eq(&Arc::downgrade(&st.doc)) && self.affine == *affine && self.selection == st.selection.objects
|
||||
}
|
||||
}
|
||||
|
||||
impl Panes {
|
||||
@@ -56,6 +79,7 @@ impl Panes {
|
||||
self.last.clear();
|
||||
self.last_slots.clear();
|
||||
self.fits.clear();
|
||||
self.outlines.clear();
|
||||
}
|
||||
|
||||
/// Upload `img`, the render `key` describes, for `slot`.
|
||||
@@ -311,6 +335,9 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
app.canvas.panes.clear();
|
||||
}
|
||||
app.canvas.panes.last.clear();
|
||||
// Only the floating windows draw panes now.
|
||||
let floating = &app.ui.floating;
|
||||
app.canvas.panes.outlines.retain(|(u, n), _| floating.iter().any(|w| w.uid == *u && w.view == *n));
|
||||
app.canvas.panes.last_slots.clear();
|
||||
return false;
|
||||
}
|
||||
@@ -326,6 +353,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
app.canvas.panes.shown.retain(|s, _| live.contains(s));
|
||||
app.canvas.panes.pending.retain(|s, _| live.contains(s));
|
||||
app.canvas.panes.fits.retain(|s, _| live.contains(s));
|
||||
app.canvas.panes.outlines.retain(|s, _| live.contains(s));
|
||||
// A window that moved to another pane fits it, and so does a window whose pane changed place or
|
||||
// size because a window opened, closed, floated or docked, or because the panes came back from
|
||||
// one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its
|
||||
@@ -563,7 +591,9 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
|
||||
guides_of(app, st, (&painter, &xf, &t), rect);
|
||||
}
|
||||
if app.ui.view.edges {
|
||||
selected_objects(st, &painter, &xf);
|
||||
selected_objects(&mut app.canvas.panes, slot, st, &painter, &xf);
|
||||
} else {
|
||||
app.canvas.panes.outlines.remove(&slot);
|
||||
}
|
||||
if app.ui.view.rulers && app.ui.screen_mode < 3 {
|
||||
rulers(ui, full, &xf, None, RulerScale::document(app.session.general_unit(), st.doc.ruler_origin_for(v.artboard)), &t);
|
||||
@@ -581,23 +611,45 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
|
||||
resp.contains_pointer() && ui.input(|inp| inp.pointer.any_pressed())
|
||||
}
|
||||
|
||||
/// The outlines of the objects selected in `st`, in their layers' colors; their bounds when they
|
||||
/// have too many points to outline.
|
||||
fn selected_objects(st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) {
|
||||
/// Draw the outlines of the objects selected in `st` ([`outline_shapes`]) in `slot`'s pane, from
|
||||
/// the outlines `panes` kept for the slot while they show the same revision, document, selection
|
||||
/// and screen mapping, and made again otherwise.
|
||||
fn selected_objects(panes: &mut Panes, slot: Slot, st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) {
|
||||
let affine = xf.affine().as_coeffs();
|
||||
if !panes.outlines.get(&slot).is_some_and(|o| o.shows(st, &affine)) {
|
||||
let shapes = outline_shapes(st, xf);
|
||||
let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: st.selection.objects.clone(), affine, shapes };
|
||||
panes.outlines.insert(slot, kept);
|
||||
panes.outlines_made += 1;
|
||||
}
|
||||
for shape in panes.outlines.get(&slot).map_or(&[][..], |o| &o.shapes) {
|
||||
painter.add(shape.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// The outlines of the objects selected in `st` as lines on the screen through `xf`, in their
|
||||
/// layers' colors; their bounds when they have too many points to outline.
|
||||
fn outline_shapes(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec<egui::Shape> {
|
||||
let mut shapes = vec![];
|
||||
if st.selection.objects.is_empty() {
|
||||
return shapes;
|
||||
}
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> =
|
||||
st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect();
|
||||
let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id)));
|
||||
let mut stroke = |bp: &BezPath, s: Stroke| shapes.extend(to_screen_path(bp, xf).into_iter().map(|line| egui::Shape::line(line, s)));
|
||||
if too_many_anchors(nodes.iter().map(|(_, n)| *n)) {
|
||||
let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b));
|
||||
if let (Some(b), Some((id, _))) = (bounds, nodes.first()) {
|
||||
stroke_path(painter, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, color(*id));
|
||||
stroke(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id));
|
||||
}
|
||||
return;
|
||||
return shapes;
|
||||
}
|
||||
for (id, n) in nodes {
|
||||
stroke_path(painter, &node_outline(n, &symbols), xf, color(id));
|
||||
stroke(&node_outline(n, &symbols), color(id));
|
||||
}
|
||||
shapes
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -875,6 +875,149 @@ fn other_panes_draw_their_guides_and_selected_objects() {
|
||||
assert_ne!(layer, Color32::TRANSPARENT);
|
||||
}
|
||||
|
||||
/// The selected objects' outlines as the panes made them on every frame before they kept them,
|
||||
/// to hold the kept outlines against.
|
||||
fn outlines_made_each_frame(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec<Shape> {
|
||||
let mut shapes = vec![];
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> =
|
||||
st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect();
|
||||
let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id)));
|
||||
let mut stroke_path = |bp: &BezPath, s: Stroke| {
|
||||
for line in to_screen_path(bp, xf) {
|
||||
shapes.push(Shape::line(line, s));
|
||||
}
|
||||
};
|
||||
if too_many_anchors(nodes.iter().map(|(_, n)| *n)) {
|
||||
let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b));
|
||||
if let (Some(b), Some((id, _))) = (bounds, nodes.first()) {
|
||||
stroke_path(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id));
|
||||
}
|
||||
return shapes;
|
||||
}
|
||||
for (id, n) in nodes {
|
||||
stroke_path(&node_outline(n, &symbols), color(id));
|
||||
}
|
||||
shapes
|
||||
}
|
||||
|
||||
/// The first document's pane in a tiled pair: the outlines it keeps, after checking that they
|
||||
/// equal the outlines made afresh through its view and that the frame `drawn` holds them in order.
|
||||
fn kept_outlines<'a>(app: &'a VectorcraftApp, ctx: &egui::Context, drawn: &[Shape]) -> &'a [Shape] {
|
||||
let pane = panes(app).1[0];
|
||||
let xf = Xf::new(view_rects(app, pane, ctx.pixels_per_point()).1, &app.views[0]);
|
||||
let slot = (app.session.documents()[0].uid, 1);
|
||||
let kept = &app.canvas.panes.outlines.get(&slot).expect("the pane keeps its outlines").shapes;
|
||||
assert_eq!(kept, &outlines_made_each_frame(&app.session.documents()[0], &xf), "the kept outlines are the ones made afresh");
|
||||
assert!(kept.is_empty() || drawn.windows(kept.len()).any(|w| w == kept.as_slice()), "the pane draws the kept outlines");
|
||||
kept
|
||||
}
|
||||
|
||||
/// Run `cmd` on the first document of a tiled pair, then make the second current again.
|
||||
fn in_first(app: &mut VectorcraftApp, cmd: &str, args: serde_json::Value) -> serde_json::Value {
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
let out = app.session.execute(cmd, &args).unwrap();
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_outlines_do_not_show_for_a_new_document_that_takes_a_freed_documents_address() {
|
||||
let affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
let st = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None);
|
||||
let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: vec![], affine, shapes: vec![] };
|
||||
assert!(kept.shows(&st, &affine), "the outlines show the document they were made for");
|
||||
let freed = Arc::as_ptr(&st.doc);
|
||||
drop(st);
|
||||
let mut reused = false;
|
||||
for _ in 0..64 {
|
||||
let other = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None);
|
||||
reused |= Arc::as_ptr(&other.doc) == freed;
|
||||
assert!(!kept.shows(&other, &affine), "a different document with the same revision, selection and mapping is not the one shown");
|
||||
}
|
||||
assert!(!reused, "the weak reference keeps the freed document's address from being taken");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes() {
|
||||
let mut app = app_with(2);
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let rect = in_first(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80}))["id"].clone();
|
||||
let ellipse = in_first(&mut app, "shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60}))["id"].clone();
|
||||
in_first(&mut app, "select.set", json!({"ids": [rect, ellipse]}));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let drawn = frame(&mut app, &ctx, vec![]);
|
||||
assert!(kept_outlines(&app, &ctx, &drawn).len() >= 2, "the rectangle and the ellipse are outlined");
|
||||
let made = app.canvas.panes.outlines_made;
|
||||
let drawn = frame(&mut app, &ctx, vec![]);
|
||||
kept_outlines(&app, &ctx, &drawn);
|
||||
assert_eq!(app.canvas.panes.outlines_made, made, "an unchanged frame draws the kept outlines");
|
||||
let changed = |app: &mut VectorcraftApp, what: &str| {
|
||||
let made = app.canvas.panes.outlines_made;
|
||||
let drawn = frame(app, &ctx, vec![]);
|
||||
kept_outlines(app, &ctx, &drawn);
|
||||
assert_eq!(app.canvas.panes.outlines_made, made + 1, "{what} makes the outlines again, once");
|
||||
let drawn = frame(app, &ctx, vec![]);
|
||||
kept_outlines(app, &ctx, &drawn);
|
||||
assert_eq!(app.canvas.panes.outlines_made, made + 1, "the frame after {what} draws the kept outlines");
|
||||
};
|
||||
in_first(&mut app, "select.set", json!({"ids": [ellipse]}));
|
||||
changed(&mut app, "a new selection");
|
||||
in_first(&mut app, "object.move", json!({"dx": 30, "dy": -10}));
|
||||
changed(&mut app, "a move");
|
||||
let layer = app.session.documents()[0].doc.layers[0].id.0;
|
||||
in_first(&mut app, "layer.setProps", json!({"id": layer, "color": "#20a040"}));
|
||||
changed(&mut app, "a new layer color");
|
||||
app.views[0].center.x += 25.0;
|
||||
changed(&mut app, "a pan");
|
||||
app.views[0].zoom *= 1.5;
|
||||
app.views[0].rotation = 20.0;
|
||||
changed(&mut app, "a zoom and a turn");
|
||||
app.ui.view.edges = false;
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.canvas.panes.outlines.is_empty(), "with Edges off no outlines are kept");
|
||||
app.ui.view.edges = true;
|
||||
changed(&mut app, "Edges on again");
|
||||
in_first(&mut app, "select.none", json!({}));
|
||||
changed(&mut app, "an empty selection");
|
||||
let drawn = frame(&mut app, &ctx, vec![]);
|
||||
assert!(kept_outlines(&app, &ctx, &drawn).is_empty());
|
||||
// 30,000 rectangles have more points than the outlines are made for: the pane keeps the bounds.
|
||||
let st = &app.session.documents()[0];
|
||||
let rect = st.doc.node(vectorcraft_doc::NodeId(rect.as_u64().unwrap())).cloned().unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.session
|
||||
.edit("Fill", |d, _| {
|
||||
let layer = d.layers[0].id;
|
||||
for _ in 0..30_000 {
|
||||
let mut n = rect.clone();
|
||||
n.id = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, n)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
changed(&mut app, "selecting more points than are outlined");
|
||||
let drawn = frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(kept_outlines(&app, &ctx, &drawn).len(), 1, "one rectangle around the bounds");
|
||||
app.run("window.arrange.consolidateAllWindows", json!({})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.canvas.panes.outlines.is_empty(), "Consolidate All Windows forgets the outlines");
|
||||
// Panes that stop showing before their render arrives keep no outlines either.
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.canvas.panes.outlines.len(), 1);
|
||||
app.ui.tiled = false;
|
||||
app.canvas.panes.shown.clear();
|
||||
app.canvas.panes.last.clear();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.canvas.panes.outlines.is_empty(), "no pane shows, so no outlines are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() {
|
||||
let mut app = app_with(2);
|
||||
@@ -1209,3 +1352,82 @@ fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_con
|
||||
assert!(differs(want, blend(s, front_paper)), "the front document's paper blends to another color");
|
||||
assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color");
|
||||
}
|
||||
|
||||
fn thread_cpu_ns() -> Option<u128> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Time a pane's selected-object outlines with every object of a document selected: 2,000 and
|
||||
/// 20,000 rectangles, 20,000 ellipses, and 150,000 rectangles (more points than are outlined, so
|
||||
/// the pane draws their bounds). Each frame is a whole egui pass that draws the outlines and the
|
||||
/// tessellation of what it drew, made afresh on every frame ([`outlines_made_each_frame`]) or
|
||||
/// drawn from the kept outlines ([`selected_objects`]). The sides alternate, and the median time
|
||||
/// per frame of 7 runs is printed.
|
||||
/// Run with `cargo test --release -p vectorcraft-ui-egui --lib pane_outlines_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; performance depends on machine load"]
|
||||
fn pane_outlines_timing() {
|
||||
const FRAMES: u32 = 20;
|
||||
let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" };
|
||||
eprintln!("{clock} per frame, median of 7 runs of {FRAMES} frames");
|
||||
for (count, shape) in [(2_000, "shape.rectangle"), (20_000, "shape.rectangle"), (20_000, "shape.ellipse"), (150_000, "shape.rectangle")] {
|
||||
let mut app = app_with(1);
|
||||
let id = app.run(shape, json!({"x": 20, "y": 20, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap();
|
||||
app.session
|
||||
.edit("Fill", |d, _| {
|
||||
let layer = d.layers[0].id;
|
||||
for _ in 1..count {
|
||||
let mut n = node.clone();
|
||||
n.id = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, n)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.selection.objects.len(), count);
|
||||
let ctx = egui::Context::default();
|
||||
let area = egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0));
|
||||
let xf = Xf { rect: area, zoom: 4.0, center: Point::new(50.0, 40.0), rot: 0.0 };
|
||||
let mut kept = Panes::default();
|
||||
let slot = (st.uid, 1);
|
||||
let mut pass = |fresh: bool| {
|
||||
let raw = egui::RawInput { screen_rect: Some(area), ..Default::default() };
|
||||
let out = ctx.run_ui(raw, |ui| {
|
||||
let painter = ui.painter_at(area);
|
||||
if fresh {
|
||||
for s in outlines_made_each_frame(st, &xf) {
|
||||
painter.add(s);
|
||||
}
|
||||
} else {
|
||||
selected_objects(&mut kept, slot, st, &painter, &xf);
|
||||
}
|
||||
});
|
||||
ctx.tessellate(out.shapes, out.pixels_per_point).len()
|
||||
};
|
||||
assert_eq!(pass(true), pass(false), "both sides draw as much");
|
||||
let mut time = |fresh: bool| {
|
||||
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..FRAMES {
|
||||
pass(fresh);
|
||||
}
|
||||
let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a);
|
||||
ns as f64 / f64::from(FRAMES) / 1e6
|
||||
};
|
||||
let (mut fresh, mut cached) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
fresh.push(time(true));
|
||||
cached.push(time(false));
|
||||
}
|
||||
let median = |v: &mut Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
let shapes = kept.outlines.get(&slot).map_or(0, |o| o.shapes.len());
|
||||
eprintln!("{count} x {shape} ({shapes} lines drawn)");
|
||||
eprintln!(" made every frame: {:>9.3} ms {fresh:.3?}", median(&mut fresh));
|
||||
eprintln!(" kept: {:>9.3} ms {cached:.3?}", median(&mut cached));
|
||||
}
|
||||
}
|
||||
@@ -943,7 +943,7 @@ fn german_script_status_preserves_authored_error_and_translates_native_error() {
|
||||
// A change of language while the message stays keeps the script's text.
|
||||
failed(&mut app, "throw new Error('invalid array length')", false);
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered"));
|
||||
assert_eq!(super::status_bar::status_message(&app), "t.js : ligne 1, colonne 1 : Error: invalid array length (levée)");
|
||||
assert_eq!(super::status_bar::status_message(&app), "t.js\u{a0}: ligne 1, colonne 1\u{a0}: Error: invalid array length (levée)");
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
assert_eq!(super::status_bar::status_message(&app), app.ui.status);
|
||||
// After a run that completes, the message is an ordinary one.
|
||||
|
||||
@@ -15,6 +15,7 @@ pub mod action_select_object;
|
||||
pub mod action_set_options;
|
||||
pub mod action_stop;
|
||||
pub mod artboard_options;
|
||||
pub mod attributes_panel_options;
|
||||
pub mod blend_options;
|
||||
mod brush_art_options;
|
||||
pub mod brush_delete;
|
||||
@@ -477,6 +478,7 @@ registry! {
|
||||
LayerOptions: [layer_options::KIND] => layer_options::SPEC,
|
||||
LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC,
|
||||
NavigatorPanelOptions: [navigator_panel_options::KIND] => navigator_panel_options::SPEC,
|
||||
AttributesPanelOptions: [attributes_panel_options::KIND] => attributes_panel_options::SPEC,
|
||||
PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC,
|
||||
PixelSnapOptions: [pixel_snap_options::KIND] => pixel_snap_options::SPEC,
|
||||
RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Attributes panel › Panel Options…: how many recent URLs the panel's URL menu lists.
|
||||
//!
|
||||
//! Field: `count` (1–30). OK runs `ui.attributesPanelOptions` with it (kept with the UI state).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::DialogSpec;
|
||||
use super::swatch_options::{grid, label};
|
||||
use crate::panels::attributes::DEFAULT_RECENT_URLS;
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// The dialog kind of the Attributes Panel Options.
|
||||
pub const KIND: &str = "attributesPanelOptions";
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Attributes Panel Options").into(), body, confirm, min_width: 280.0, ..DialogSpec::FORM };
|
||||
|
||||
/// `ui.attributesPanelOptions` without options: open the dialog on the panel's options.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let count = app.ui.attributes_panel.shown();
|
||||
app.ui.dialog = Some(Dialog::new(KIND, json!({ "count": count })));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
grid(ui, |ui| {
|
||||
label(ui, tl!("Number of Recent URLs:"));
|
||||
let v = d.f64("count", f64::from(DEFAULT_RECENT_URLS));
|
||||
let max = vectorcraft_engine::cmd::RECENT_URLS as f64;
|
||||
if let Some(v) = widgets::range_field(ui, "attributes-recent-urls", v, 1.0..=max, "", 0, 60.0) {
|
||||
d.fields.insert("count".into(), json!(v));
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
false
|
||||
}
|
||||
|
||||
/// OK: set the count; a count that is refused leaves the dialog open.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let params = json!({ "count": d.fields.get("count").cloned().unwrap_or(Value::Null) });
|
||||
let r = app.run("ui.attributesPanelOptions", params)?;
|
||||
app.ui.dialog = None;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
/// The dialog opens on the panel's count (10 by default), OK sets it, kept with the UI state,
|
||||
/// and a count out of range is refused, leaving the dialog open and the count as it was.
|
||||
#[test]
|
||||
fn panel_options_set_the_recent_url_count() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("ui.attributesPanelOptions", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.kind.as_str(), d.f64("count", 0.0)), (KIND, 10.0));
|
||||
// Drawn headlessly in the shared frame.
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let set = |app: &mut VectorcraftApp, count: Value| {
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("count".into(), count);
|
||||
super::super::confirm(app)
|
||||
};
|
||||
assert_eq!(set(&mut app, json!(25.0)).unwrap(), json!({"count": 25}));
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(app.ui.attributes_panel.recent_urls, 25);
|
||||
app.run("ui.attributesPanelOptions", json!({})).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("count", 0.0), 25.0, "opens on the current count");
|
||||
assert!(set(&mut app, json!(31)).is_err());
|
||||
assert!(app.ui.dialog.is_some() && app.ui.attributes_panel.recent_urls == 25, "a refused count changes nothing");
|
||||
// Cancel closes the dialog without applying what was typed.
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("count".into(), json!(3));
|
||||
super::super::cancel(&mut app);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(app.ui.attributes_panel.recent_urls, 25);
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,16 @@
|
||||
//! tab's `colorMode`, `convertColors`, `rgbProfile` and `cmykProfile` (null: the working space).
|
||||
//! OK runs `document.setup` with them: one undo step. When the Color tab changed something, OK runs
|
||||
//! `document.setup`, `edit.assignProfile` and `file.documentColorMode` in one `command.batch`,
|
||||
//! and the document's changes are still one undo step. On an error the dialog stays open.
|
||||
//! and the document's changes are still one undo step. On an error the dialog stays open. When OK
|
||||
//! raises the bleed on a side, the status bar counts the objects that reach an artboard's trim edge
|
||||
//! on a side OK raised but stop short of the new bleed there.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::cms::ProfileKind;
|
||||
use vectorcraft_doc::setup::{GRID_COLOR_PRESETS, LANGUAGES};
|
||||
use vectorcraft_doc::setup::{GRID_COLOR_PRESETS, LANGUAGES, bleed_in_range};
|
||||
use vectorcraft_doc::{ColorMode, GridSize, Quotes, Unit};
|
||||
use vectorcraft_engine::cmd::colormgmt::doc_profiles;
|
||||
use vectorcraft_engine::cmd::fileio::pdf;
|
||||
|
||||
use super::{DialogSpec, form};
|
||||
use crate::state::Dialog;
|
||||
@@ -102,6 +105,7 @@ fn color_commands(app: &VectorcraftApp, d: &Dialog) -> Result<Vec<Value>, String
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let params: Map<String, Value> = d.fields.iter().filter(|(k, _)| !UI_ONLY.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
let color = color_commands(app, d)?;
|
||||
let before = app.session.active().map(|st| st.doc.setup.bleed);
|
||||
let r = if color.is_empty() {
|
||||
app.run("document.setup", Value::Object(params))
|
||||
} else {
|
||||
@@ -110,10 +114,24 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
};
|
||||
if r.is_ok() {
|
||||
app.ui.dialog = None;
|
||||
if let Some(note) = before.and_then(|b| short_of_bleed_note(app, b)) {
|
||||
app.status(note);
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The status note after OK raised the bleed on a side from `before`: how many objects reach an
|
||||
/// artboard's trim edge on a side whose bleed grew but stop short of the new bleed there. `None`
|
||||
/// when no side grew or no object stops short.
|
||||
fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option<String> {
|
||||
let doc = &app.session.active()?.doc;
|
||||
// In the range the PDF pages keep the document's bleed to.
|
||||
let (bleed, before) = (bleed_in_range(doc.setup.bleed), bleed_in_range(before));
|
||||
let raised: [f64; 4] = std::array::from_fn(|i| if bleed[i] > before[i] { bleed[i] } else { 0.0 });
|
||||
pdf::short_of_bleed_warning(pdf::short_of_bleed(doc, raised, None, false))
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let tab = TABS.iter().position(|t| *t == d.str("tab")).unwrap_or(0);
|
||||
if let Some(i) = widgets::tab_bar(ui, &TABS, tab) {
|
||||
@@ -529,6 +547,51 @@ mod tests {
|
||||
assert!(app.ui.dialog.is_some());
|
||||
}
|
||||
|
||||
/// OK with a larger bleed shows how many objects reach the trim edge but stop short of it; a
|
||||
/// smaller bleed, or a larger one that no object falls short of, shows no such note.
|
||||
#[test]
|
||||
fn ok_with_a_larger_bleed_counts_the_art_short_of_it() {
|
||||
let short = |app: &VectorcraftApp| app.ui.status.contains("short of the bleed");
|
||||
let ok_with_sides = |app: &mut VectorcraftApp, bleed: [f64; 4]| {
|
||||
app.status("");
|
||||
app.run("file.documentSetup", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("bleed".into(), json!(bleed));
|
||||
crate::dialogs::confirm(app).unwrap();
|
||||
};
|
||||
let ok_with_bleed = |app: &mut VectorcraftApp, bleed: f64| ok_with_sides(app, [bleed; 4]);
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
// A background that fills a 4 pt bleed on the top, left and right.
|
||||
let id = app.run("shape.rectangle", json!({"x": -4, "y": -4, "width": 208, "height": 50})).unwrap()["id"].clone();
|
||||
app.run("paint.setStroke", json!({"ids": [id], "none": true})).unwrap();
|
||||
ok_with_bleed(&mut app, 4.0);
|
||||
assert!(!short(&app), "{}", app.ui.status);
|
||||
ok_with_bleed(&mut app, 9.0);
|
||||
assert_eq!(app.ui.status, "1 object reaches the trim edge but stops short of the bleed");
|
||||
ok_with_bleed(&mut app, 6.0);
|
||||
assert!(!short(&app), "{}", app.ui.status);
|
||||
// Only the sides whose bleed grows count: the background stops short at the top, left and
|
||||
// right, so a larger bottom bleed alone shows no note, and a larger top bleed does.
|
||||
ok_with_sides(&mut app, [6.0, 12.0, 6.0, 6.0]);
|
||||
assert!(!short(&app), "{}", app.ui.status);
|
||||
ok_with_sides(&mut app, [12.0, 12.0, 6.0, 6.0]);
|
||||
assert!(short(&app), "{}", app.ui.status);
|
||||
// Art inside the trim falls short of no bleed.
|
||||
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();
|
||||
ok_with_bleed(&mut app, 9.0);
|
||||
assert!(!short(&app), "{}", app.ui.status);
|
||||
assert_eq!(app.session.active().unwrap().doc.setup.bleed, [9.0; 4]);
|
||||
// A bleed that isn't a number, as a file can hold, counts as none before OK, as in the PDF.
|
||||
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": 0, "y": 0, "width": 200, "height": 50})).unwrap();
|
||||
std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc).setup.bleed = [f64::NAN; 4];
|
||||
ok_with_bleed(&mut app, 9.0);
|
||||
assert_eq!(app.ui.status, "1 object reaches the trim edge but stops short of the bleed");
|
||||
}
|
||||
|
||||
/// Highlight Substituted Fonts is in Preferences › Type, so the General tab shows only the
|
||||
/// substituted glyphs highlight, and OK still applies.
|
||||
#[test]
|
||||
|
||||
@@ -5,18 +5,22 @@
|
||||
//! grid shows). While Alt (Option on macOS) is held, Cancel reads Reset, which puts every option
|
||||
//! back to the tool's default and leaves the dialog open (`ui.dialogReset`). A click-opened
|
||||
//! dialog previews its settings live; Reset refreshes that preview and Cancel rolls it back.
|
||||
//! Opened from the toolbar with flares selected, it shows the first one's settings, and OK draws
|
||||
//! the selected flares again with the settings changed in the dialog (`shape.editFlare`); the tool
|
||||
//! keeps its options.
|
||||
//!
|
||||
//! Fields: the options (`vectorcraft_tools::extra::FLARE_OPTIONS`): `diameter` and `pathLength`
|
||||
//! (points), `opacity`, `brightness`, `growth`, `fuzziness`, `longest`, `rayFuzziness` and
|
||||
//! `largest` (%), `rays` and `rings` (counts), `direction` (degrees); `raysOn` and `ringsOn`; and
|
||||
//! `x`, `y` where a click opened it, with `preview` on initially for that click.
|
||||
//! `largest` (%), `rays` and `rings` (counts), `direction` (degrees); `raysOn` and `ringsOn`;
|
||||
//! `x`, `y` where a click opened it, with `preview` on initially for that click; and `flares`
|
||||
//! (ids) with `shown` (the settings the dialog opened with) for the selected flares.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params};
|
||||
|
||||
use super::document_setup::check;
|
||||
use super::{DialogResult, DialogSpec, form, set_tool_options_and_close};
|
||||
use super::{DialogResult, DialogSpec, form, run_and_close, set_tool_options_and_close};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
@@ -38,7 +42,8 @@ const LABEL_W: f32 = 78.0;
|
||||
const FIELD_W: f32 = 90.0;
|
||||
|
||||
/// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a
|
||||
/// flare there on OK.
|
||||
/// flare there on OK. Opened without a click while flares are selected, they show the first one's
|
||||
/// settings, to change the selected flares on OK.
|
||||
pub fn open(app: &mut VectorcraftApp, at: Option<Point>) -> Value {
|
||||
let mut fields = match app.session.tool_options_of("flare") {
|
||||
Value::Object(o) => o,
|
||||
@@ -48,11 +53,79 @@ pub fn open(app: &mut VectorcraftApp, at: Option<Point>) -> Value {
|
||||
fields.insert("preview".into(), json!(true));
|
||||
fields.insert("x".into(), json!(p.x));
|
||||
fields.insert("y".into(), json!(p.y));
|
||||
} else if let Some((ids, settings)) = selected_flares(app) {
|
||||
// A flare without rays or rings shows that checkbox off, with the tool's count.
|
||||
for (key, on) in [("rays", "raysOn"), ("rings", "ringsOn")] {
|
||||
let n = settings.get(key).and_then(Value::as_f64).unwrap_or(0.0);
|
||||
fields.insert(on.into(), json!(n > 0.0));
|
||||
if n > 0.0 {
|
||||
fields.insert(key.into(), json!(n));
|
||||
}
|
||||
}
|
||||
for (key, ..) in FLARE_OPTIONS.iter().filter(|(k, ..)| !matches!(*k, "rays" | "rings")) {
|
||||
if let Some(v) = settings.get(*key) {
|
||||
fields.insert(key.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
fields.insert("shown".into(), Value::Object(shown(&fields)));
|
||||
fields.insert("flares".into(), json!(ids));
|
||||
}
|
||||
app.ui.dialog = Some(Dialog { kind: KIND.into(), fields });
|
||||
json!({ "dialog": KIND })
|
||||
}
|
||||
|
||||
/// The selected flares that can be edited (ids) and the first one's settings as the dialog shows
|
||||
/// them: its rings' path length and direction from its center to its end point, where the flare is
|
||||
/// drawn now.
|
||||
fn selected_flares(app: &VectorcraftApp) -> Option<(Vec<u64>, Map<String, Value>)> {
|
||||
let st = app.session.doc().ok()?;
|
||||
let flares: Vec<_> = st
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.filter(|id| st.doc.is_editable(**id))
|
||||
.filter_map(|id| vectorcraft_engine::flare_settings(&st.doc, *id).map(|spec| (id.0, spec)))
|
||||
.collect();
|
||||
let (_, first) = flares.first()?;
|
||||
let Value::Object(mut settings) = first.params.clone() else { return None };
|
||||
let d = first.end()? - first.center()?;
|
||||
settings.insert("pathLength".into(), json!(d.hypot()));
|
||||
// Counter-clockwise from 3 o'clock, 0° to 360°, as `shape.flare` takes it.
|
||||
settings.insert("direction".into(), json!((-d.y).atan2(d.x).to_degrees().rem_euclid(360.0)));
|
||||
Some((flares.iter().map(|(id, _)| *id).collect(), settings))
|
||||
}
|
||||
|
||||
/// The settings `fields` give a flare: each option, with a count of 0 when its checkbox is off.
|
||||
fn shown(fields: &Map<String, Value>) -> Map<String, Value> {
|
||||
let get = |key: &str, default: f64| fields.get(key).and_then(Value::as_f64).unwrap_or(default);
|
||||
let on = |key: &str| fields.get(key).and_then(Value::as_bool) != Some(false);
|
||||
FLARE_OPTIONS
|
||||
.iter()
|
||||
.map(|&(key, default, ..)| {
|
||||
let v = match key {
|
||||
"rays" if !on("raysOn") => 0.0,
|
||||
"rings" if !on("ringsOn") => 0.0,
|
||||
"rays" | "rings" => get(key, default).round(),
|
||||
_ => get(key, default),
|
||||
};
|
||||
(key.to_string(), json!(v))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `shape.editFlare`'s params for the selected flares: the settings changed since the dialog opened.
|
||||
fn edit_params(d: &Dialog) -> Option<Value> {
|
||||
let ids = d.fields.get("flares")?.clone();
|
||||
let start = d.fields.get("shown").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let mut params = json!({ "ids": ids });
|
||||
for (key, v) in shown(&d.fields) {
|
||||
if start.get(&key) != Some(&v) {
|
||||
params[key.as_str()] = if matches!(key.as_str(), "rays" | "rings") { json!(v.as_f64().unwrap_or(0.0) as u64) } else { v };
|
||||
}
|
||||
}
|
||||
Some(params)
|
||||
}
|
||||
|
||||
/// A row for option `key`, kept within its range: a distance in `unit`, else a number.
|
||||
fn field(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit, (key, label): (&str, &str)) {
|
||||
let Some(&(_, default, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return };
|
||||
@@ -119,8 +192,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// A click-created flare previews at that original click; toolbar options draw no artwork.
|
||||
/// A click-created flare previews at that original click, and the selected flares preview with the
|
||||
/// settings changed; toolbar options draw no artwork.
|
||||
fn preview_command(app: &VectorcraftApp, d: &Dialog) -> Option<(String, Value)> {
|
||||
if let Some(params) = edit_params(d) {
|
||||
return Some(("shape.editFlare".into(), params));
|
||||
}
|
||||
let at = Point::new(d.fields.get("x")?.as_f64().filter(|v| v.is_finite())?, d.fields.get("y")?.as_f64().filter(|v| v.is_finite())?);
|
||||
// Use the same clamping and whole-count conversion as accepted tool settings.
|
||||
let mut tool = vectorcraft_tools::create("flare");
|
||||
@@ -143,8 +220,16 @@ fn reset(_: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// OK: set the tool's options; opened by a click, draw a flare there with them.
|
||||
/// OK: set the tool's options; opened by a click, draw a flare there with them. Opened for the
|
||||
/// selected flares, draw them again with the settings changed, leaving the tool's options.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
|
||||
if let Some(params) = edit_params(d) {
|
||||
return if d.fields.contains_key(form::PREVIEWED) {
|
||||
form::commit_preview(app, "shape.editFlare", params)
|
||||
} else {
|
||||
run_and_close(app, "shape.editFlare", params)
|
||||
};
|
||||
}
|
||||
let command = preview_command(app, d);
|
||||
if command.is_none() && (d.fields.contains_key("x") || d.fields.contains_key("y") || d.fields.contains_key(form::PREVIEWED)) {
|
||||
return Err("Flare click coordinates must be finite numbers".into());
|
||||
@@ -321,6 +406,41 @@ mod tests {
|
||||
assert_eq!(app.session.tool_options_of("flare"), before);
|
||||
}
|
||||
|
||||
/// With a flare selected, the toolbar's Flare Tool Options show its settings, and OK draws it
|
||||
/// again with the settings changed, as one undo step, leaving the tool's options.
|
||||
#[test]
|
||||
fn with_a_flare_selected_the_options_show_its_settings_and_ok_draws_it_again() {
|
||||
let mut app = app();
|
||||
let flare = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 0, "rings": 4, "x2": 200, "y2": 0, "largest": 80, "seed": 5});
|
||||
app.run("shape.flare", flare).unwrap();
|
||||
app.run("object.move", json!({"dx": 30, "dy": 0})).unwrap();
|
||||
let options = app.session.tool_options_of("flare");
|
||||
app.run("tool.options", json!({"tool": "flare"})).unwrap();
|
||||
painted(&mut app);
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
let shown = (d.f64("diameter", 0.0), d.bool("raysOn"), d.f64("rays", 0.0), d.f64("rings", 0.0), d.f64("largest", 0.0));
|
||||
assert_eq!(shown, (60.0, false, 15.0, 4.0, 80.0));
|
||||
assert!((d.f64("pathLength", 0.0) - 200.0).abs() < 1e-9 && (d.f64("direction", 0.0) - 90.0).abs() < 1e-9);
|
||||
d.fields.insert("rings".into(), json!(7));
|
||||
d.fields.insert("raysOn".into(), json!(true));
|
||||
let depth = app.session.doc().unwrap().history.undo.len();
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1);
|
||||
let parts = flare_parts(&app);
|
||||
assert_eq!((parts.iter().filter(|p| *p == "Ring").count(), parts.iter().any(|p| p == "Rays")), (7, true), "{parts:?}");
|
||||
// Still where it was moved to.
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
let id = app.session.doc().unwrap().selection.objects[0];
|
||||
assert!(vectorcraft_engine::flare_settings(doc, id).unwrap().center().unwrap().distance(Point::new(230.0, 200.0)) < 1e-9);
|
||||
assert_eq!(app.session.tool_options_of("flare"), options);
|
||||
// With nothing selected, the dialog shows the tool's options again.
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.run("tool.options", json!({"tool": "flare"})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.f64("diameter", 0.0), d.fields.contains_key("flares")), (100.0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_dialog_reset_puts_the_defaults_back_and_keeps_where_a_click_opened_it() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -280,6 +280,7 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
variation: (0.0, 100.0),
|
||||
};
|
||||
varied(ui, d, &roundness, &Variation::ALL);
|
||||
tip_preview(ui, d, roundness.range.0);
|
||||
size_rows(ui, d, &Variation::ALL);
|
||||
} else {
|
||||
if d.fields.contains_key("angle") {
|
||||
@@ -291,7 +292,7 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
}
|
||||
if d.str("tool") == "blobBrush" {
|
||||
blob_tip_preview(ui, d);
|
||||
tip_preview(ui, d, 0.0);
|
||||
}
|
||||
// The Eraser's Size rows are above.
|
||||
if !eraser && d.fields.contains_key("sizeMode") {
|
||||
@@ -331,26 +332,26 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Side of the Blob Brush tip preview's square, in points.
|
||||
/// Side of the Blob Brush's and the Eraser's tip preview square, in points.
|
||||
const TIP_PREVIEW: f32 = 64.0;
|
||||
|
||||
/// Half the length of the Blob Brush tip in its preview, in points.
|
||||
/// Half the length of the tip in its preview, in points.
|
||||
const TIP_LONG: f32 = 18.0;
|
||||
|
||||
/// How far from a Roundness dot of the tip preview a press still takes the dot, in points.
|
||||
const TIP_DOT_REACH: f32 = 8.0;
|
||||
|
||||
/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness, a line with an
|
||||
/// arrowhead along its long axis and a black dot at each end of its short axis, and beside it three
|
||||
/// dabs of the tip, the middle one darker. A click or a drag that starts on a dot sets the
|
||||
/// Roundness from the pointer's distance from the center along the short axis
|
||||
/// ([`blob_tip_roundness_at`]) until the release, inside the square or out of it, and gives the
|
||||
/// The Blob Brush's and the Eraser's tip preview: a square with the tip at its Angle and
|
||||
/// Roundness, a line with an arrowhead along its long axis and a black dot at each end of its short
|
||||
/// axis, and beside it three dabs of the tip, the middle one darker. A click or a drag that starts
|
||||
/// on a dot sets the Roundness from the pointer's distance from the center along the short axis
|
||||
/// ([`tip_roundness_at`]) until the release, inside the square or out of it, and gives the
|
||||
/// Roundness slider the keyboard focus. A click or a drag that starts anywhere else in the square
|
||||
/// points the Angle at the pointer and gives the Angle slider the focus. Screen readers get the
|
||||
/// square as the Angle slider and then the Roundness slider, and their keys step the Angle within
|
||||
/// -180° to 180° and the Roundness within 0% to 100% as a dialog slider's do
|
||||
/// -180° to 180° and the Roundness within `min_roundness` to 100% as a dialog slider's do
|
||||
/// ([`widgets::stepped_area`]).
|
||||
fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
fn tip_preview(ui: &mut egui::Ui, d: &mut Dialog, min_roundness: f64) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(CONTENT_W, TIP_PREVIEW), egui::Sense::hover());
|
||||
let square = egui::Rect::from_min_size(rect.min, egui::vec2(TIP_PREVIEW, TIP_PREVIEW));
|
||||
@@ -359,7 +360,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
// Whether the press that started this click or drag was on a dot: it is kept until the release.
|
||||
let on_dot = response.id.with("on-dot");
|
||||
let near_dot = |p: egui::Pos2, d: &Dialog| {
|
||||
blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH)
|
||||
tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH)
|
||||
};
|
||||
let mut started = ui.data(|m| m.get_temp::<bool>(on_dot));
|
||||
if started.is_none() && response.is_pointer_button_down_on() {
|
||||
@@ -383,7 +384,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
if let Some((p, _)) = widgets::pointer_phase(&response) {
|
||||
let delta = p - center;
|
||||
if dot_drag {
|
||||
d.fields.insert("roundness".into(), json!(blob_tip_roundness_at(delta, d.f64("angle", 0.0))));
|
||||
d.fields.insert("roundness".into(), json!(tip_roundness_at(delta, d.f64("angle", 0.0), min_roundness)));
|
||||
} else if delta.length_sq() > 1.0 {
|
||||
d.fields.insert("angle".into(), json!(f64::from((-delta.y).atan2(delta.x)).to_degrees().round()));
|
||||
}
|
||||
@@ -406,13 +407,13 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
if dot_drag && (response.drag_started() || response.clicked()) {
|
||||
widgets::focus_by_pointer(ui, roundness.id);
|
||||
}
|
||||
let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), 0.0..=100.0, "%", 0);
|
||||
let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), min_roundness..=100.0, "%", 0);
|
||||
if let Some(r) = widgets::stepped_area(ui, &roundness, tl!("Roundness"), Some(shown)) {
|
||||
d.fields.insert("roundness".into(), json!(r));
|
||||
}
|
||||
let (u, v) = blob_tip_axes(d.f64("angle", 0.0));
|
||||
let (u, v) = tip_axes(d.f64("angle", 0.0));
|
||||
let long = TIP_LONG;
|
||||
let short = long * blob_tip_short_ratio(d.f64("roundness", 100.0));
|
||||
let short = long * tip_short_ratio(d.f64("roundness", 100.0));
|
||||
let dab = |center: egui::Pos2, color: egui::Color32| {
|
||||
let points = (0..32)
|
||||
.map(|i| {
|
||||
@@ -427,7 +428,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let arrowhead = vec![center + u * 28.0, center + u * 22.0 + v * 3.0, center + u * 22.0 - v * 3.0];
|
||||
painter.add(egui::Shape::convex_polygon(arrowhead, t.accent, egui::Stroke::NONE));
|
||||
// Black with a white rim, so a dot shows on the tip and on the square in either theme.
|
||||
for dot in blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) {
|
||||
for dot in tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) {
|
||||
painter.circle(dot, 3.0, egui::Color32::BLACK, egui::Stroke::new(1.0, egui::Color32::WHITE));
|
||||
}
|
||||
let strip = square.right() + 2.5 * long;
|
||||
@@ -438,7 +439,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
|
||||
/// The tip preview's long axis on screen at Angle `angle` (degrees, y down: a positive angle tilts
|
||||
/// it up to the right), and its short axis.
|
||||
fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) {
|
||||
fn tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) {
|
||||
let a = angle.clamp(-180.0, 180.0).to_radians();
|
||||
let u = egui::vec2(a.cos() as f32, -a.sin() as f32);
|
||||
(u, egui::vec2(-u.y, u.x))
|
||||
@@ -446,23 +447,23 @@ fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) {
|
||||
|
||||
/// The two Roundness dots of the tip preview centered on `center`: the ends of the tip's short
|
||||
/// axis at Angle `angle` and Roundness `roundness`.
|
||||
fn blob_tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] {
|
||||
let (_, v) = blob_tip_axes(angle);
|
||||
let short = v * (TIP_LONG * blob_tip_short_ratio(roundness));
|
||||
fn tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] {
|
||||
let (_, v) = tip_axes(angle);
|
||||
let short = v * (TIP_LONG * tip_short_ratio(roundness));
|
||||
[center + short, center - short]
|
||||
}
|
||||
|
||||
/// The Roundness, in whole percent from 0 to 100, that a dot of the tip preview dragged to `offset`
|
||||
/// from the preview's center gives at Angle `angle`: the distance along the tip's short axis, on
|
||||
/// either side of the center, as a percentage of half the tip's length.
|
||||
fn blob_tip_roundness_at(offset: egui::Vec2, angle: f64) -> f64 {
|
||||
let (_, v) = blob_tip_axes(angle);
|
||||
(f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(0.0, 100.0)
|
||||
/// The Roundness, in whole percent from `min` to 100, that a dot of the tip preview dragged to
|
||||
/// `offset` from the preview's center gives at Angle `angle`: the distance along the tip's short
|
||||
/// axis, on either side of the center, as a percentage of half the tip's length.
|
||||
fn tip_roundness_at(offset: egui::Vec2, angle: f64, min: f64) -> f64 {
|
||||
let (_, v) = tip_axes(angle);
|
||||
(f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(min, 100.0)
|
||||
}
|
||||
|
||||
/// The preview tip's short axis as a fraction of its long axis: Roundness in percent, with 0
|
||||
/// percent drawn as 0.1 percent, the minimum the brush draws with.
|
||||
fn blob_tip_short_ratio(roundness: f64) -> f32 {
|
||||
/// percent drawn as 0.1 percent, the minimum the Blob Brush draws with.
|
||||
fn tip_short_ratio(roundness: f64) -> f32 {
|
||||
(roundness.clamp(0.0, 100.0) as f32 / 100.0).max(0.001)
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,12 @@ fn a_refused_fidelity_keeps_the_dialog_open() {
|
||||
fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() {
|
||||
for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] {
|
||||
let drawn = vectorcraft_tools::draw2::blob_tip(0.0, roundness).as_coeffs()[3] as f32;
|
||||
assert!((blob_tip_short_ratio(roundness) - drawn).abs() < 1e-6, "roundness {roundness}: drawn {drawn}");
|
||||
assert!((tip_short_ratio(roundness) - drawn).abs() < 1e-6, "roundness {roundness}: drawn {drawn}");
|
||||
}
|
||||
// The Eraser's Roundness runs from 1% to 100%, where its tip and the Blob Brush's are the same.
|
||||
for roundness in [1.0, 2.0, 50.0, 100.0] {
|
||||
let drawn = vectorcraft_tools::draw2::eraser_tip(0.0, roundness).as_coeffs()[3] as f32;
|
||||
assert!((tip_short_ratio(roundness) - drawn).abs() < 1e-6, "Eraser roundness {roundness}: drawn {drawn}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,23 +66,35 @@ fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() {
|
||||
#[test]
|
||||
fn a_roundness_dot_sets_its_distance_along_the_short_axis() {
|
||||
for angle in [0.0, 30.0, 90.0, -135.0, 180.0] {
|
||||
let (u, v) = blob_tip_axes(angle);
|
||||
let (u, v) = tip_axes(angle);
|
||||
for (along, want) in [(0.0, 0.0), (4.5, 25.0), (-9.0, 50.0), (18.0, 100.0), (-18.0, 100.0), (40.0, 100.0), (-400.0, 100.0)] {
|
||||
for sideways in [0.0, 7.0, -30.0] {
|
||||
assert_eq!(blob_tip_roundness_at(v * along + u * sideways, angle), want, "angle {angle}, {along} along, {sideways} sideways");
|
||||
assert_eq!(tip_roundness_at(v * along + u * sideways, angle, 0.0), want, "angle {angle}, {along} along, {sideways} sideways");
|
||||
}
|
||||
}
|
||||
let center = egui::pos2(32.0, 32.0);
|
||||
for roundness in [0.0, 1.0, 37.0, 50.0, 99.0, 100.0] {
|
||||
let [a, b] = blob_tip_dots(center, angle, roundness);
|
||||
let [a, b] = tip_dots(center, angle, roundness);
|
||||
assert!(((a - center) + (b - center)).length() < 1e-4, "the dots face each other across the center");
|
||||
for dot in [a, b] {
|
||||
assert_eq!(blob_tip_roundness_at(dot - center, angle), roundness, "angle {angle}");
|
||||
assert_eq!(tip_roundness_at(dot - center, angle, 0.0), roundness, "angle {angle}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Eraser's 1% minimum, a Roundness dot dragged to the center or near it gives 1%, and
|
||||
/// any farther distance gives the same Roundness as with no minimum.
|
||||
#[test]
|
||||
fn a_roundness_dot_keeps_the_eraser_at_one_percent_or_more() {
|
||||
for angle in [0.0, 45.0, -90.0] {
|
||||
let (u, v) = tip_axes(angle);
|
||||
for (along, want) in [(0.0, 1.0), (0.05, 1.0), (-0.1, 1.0), (0.18, 1.0), (0.36, 2.0), (-9.0, 50.0), (30.0, 100.0)] {
|
||||
assert_eq!(tip_roundness_at(v * along + u * 5.0, angle, 1.0), want, "angle {angle}, {along} along");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The labels the open dialog paints.
|
||||
fn painted(app: &mut VectorcraftApp) -> String {
|
||||
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
|
||||
|
||||
@@ -173,10 +173,10 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Did a save whose applied result is `r` write the document (no error, and no question asked
|
||||
/// before writing)?
|
||||
/// Did a save whose applied result is `r` write the document (no error, no question asked before
|
||||
/// writing, and not canceled by Cancel Save)?
|
||||
fn saved(r: &Result<Value, String>) -> bool {
|
||||
r.as_ref().is_ok_and(|r| r.get("pending").is_none())
|
||||
r.as_ref().is_ok_and(|r| r.get("pending").is_none() && r.get("cancelled").and_then(Value::as_bool) != Some(true))
|
||||
}
|
||||
|
||||
/// Report the package `r` (`file.package`'s reply): the status bar, the web's download, and the
|
||||
|
||||
@@ -518,6 +518,10 @@ pub fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
}
|
||||
if let Some(k) = app.ui.dialog.as_mut() {
|
||||
k.fields.insert("overrides".into(), crate::keymap::stored::to_value(&shortcut_editor::saved_overrides(km.overrides(), &ov)));
|
||||
// VectorCraft's defaults have no hold shortcuts; Add to the Current Shortcuts keeps them.
|
||||
if !current {
|
||||
k.fields.insert("holds".into(), json!({}));
|
||||
}
|
||||
k.fields.insert("set".into(), json!(set));
|
||||
k.fields.insert("__message".into(), json!(tl!("Imported. Press OK to keep the imported set.")));
|
||||
}
|
||||
|
||||
@@ -2965,6 +2965,62 @@ fn a_drag_on_a_blob_brush_tip_dot_sets_the_roundness() {
|
||||
assert_eq!(values(&app), (46.0, 1.0), "Tab goes on to the Roundness slider");
|
||||
}
|
||||
|
||||
/// The Eraser Tool Options show the same tip preview as the Blob Brush, with the Angle and
|
||||
/// Roundness sliders for screen readers. A drag on the arrowhead sets only the Angle, and a drag on
|
||||
/// a black dot sets only the Roundness, which stays within the Eraser's 1% to 100% for a drag and
|
||||
/// for the keys. The fields show the new values, OK sets the tool's options to them, and Cancel
|
||||
/// leaves the options as they were.
|
||||
#[test]
|
||||
fn the_eraser_tip_preview_sets_the_angle_and_roundness_by_dragging() {
|
||||
use egui::Key::{ArrowDown, Home};
|
||||
use egui::Modifiers as M;
|
||||
let mut app = app();
|
||||
app.run("tool.options", json!({"tool": "eraser"})).unwrap();
|
||||
let values = |app: &VectorcraftApp| {
|
||||
let d = app.ui.dialog.as_ref().expect("Eraser Tool Options is open");
|
||||
(d.f64("angle", f64::NAN), d.f64("roundness", f64::NAN))
|
||||
};
|
||||
let mut f = Frames::new();
|
||||
f.run(&mut app, vec![]);
|
||||
let out = f.run(&mut app, vec![]);
|
||||
let (_, value, text) = slider_node(&out, "Angle");
|
||||
assert_eq!((value, text.as_deref()), (Some(0.0), Some("0°")));
|
||||
let (_, value, text) = slider_node(&out, "Roundness");
|
||||
assert_eq!((value, text.as_deref()), (Some(100.0), Some("100%")));
|
||||
let center = f.control(&mut app, "Angle", egui::accesskit::Role::Slider);
|
||||
// At 0° the arrowhead points right, 22 pt to 28 pt from the center.
|
||||
f.drag(&mut app, center + egui::vec2(25.0, 0.0), egui::vec2(-5.0, -20.0));
|
||||
assert_eq!(values(&app), (45.0, 100.0), "the arrowhead dragged up to the right");
|
||||
// At 45° and 100% the dots are 18 pt from the center, up to the left and down to the right.
|
||||
let v = egui::vec2(1.0, 1.0).normalized();
|
||||
f.drag(&mut app, center + v * 18.0, -v * 9.0);
|
||||
assert_eq!(values(&app), (45.0, 50.0), "the dot dragged half way to the center");
|
||||
f.drag(&mut app, center + v * 9.0, -v * 9.0);
|
||||
assert_eq!(values(&app), (45.0, 1.0), "the dot dragged to the center stops at 1%");
|
||||
f.key(&mut app, ArrowDown, M::NONE);
|
||||
f.key(&mut app, Home, M::NONE);
|
||||
assert_eq!(values(&app), (45.0, 1.0), "the keys stop at 1%");
|
||||
let out = f.run(&mut app, vec![]);
|
||||
assert_eq!(slider_node(&out, "Roundness").2.as_deref(), Some("1%"));
|
||||
let d = app.ui.dialog.as_mut().expect("Eraser Tool Options is open");
|
||||
d.fields.insert("roundness".into(), json!(30));
|
||||
let out = f.run(&mut app, vec![]);
|
||||
assert_eq!(slider_node(&out, "Roundness").2.as_deref(), Some("30%"), "the preview follows the field");
|
||||
confirm(&mut app).unwrap();
|
||||
let o = app.session.tool_options_of("eraser");
|
||||
assert_eq!((o["angle"].as_f64(), o["roundness"].as_f64()), (Some(45.0), Some(30.0)));
|
||||
app.run("tool.options", json!({"tool": "eraser"})).unwrap();
|
||||
let mut f = Frames::new();
|
||||
f.run(&mut app, vec![]);
|
||||
f.run(&mut app, vec![]);
|
||||
let center = f.control(&mut app, "Angle", egui::accesskit::Role::Slider);
|
||||
f.drag(&mut app, center + egui::vec2(18.0, 18.0), egui::vec2(2.0, 2.0));
|
||||
assert_eq!(values(&app), (-45.0, 30.0), "the drag points the Angle down to the right");
|
||||
app.ui.dialog = None;
|
||||
let o = app.session.tool_options_of("eraser");
|
||||
assert_eq!((o["angle"].as_f64(), o["roundness"].as_f64()), (Some(45.0), Some(30.0)), "Cancel keeps the options");
|
||||
}
|
||||
|
||||
/// Screen readers can set the Blob Brush tip preview's Angle to a number: the slider offers the
|
||||
/// set-value action, a fraction rounds to the whole degrees the field shows, a number past -180° to
|
||||
/// 180° sets the nearer end, the last request in a frame wins, and a value that is not a finite
|
||||
|
||||
@@ -280,6 +280,27 @@ fn a_failed_save_before_packaging_writes_no_package() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A save before packaging that Cancel Save stops writes no package either: the document keeps
|
||||
/// its unsaved changes, so the package would not hold it as saved.
|
||||
#[test]
|
||||
fn a_canceled_save_before_packaging_writes_no_package() {
|
||||
let dir = Folder::new("canceled-save");
|
||||
let gate = Gate::default();
|
||||
let (mut app, files) = saved_with_worker(&dir, &gate);
|
||||
let out = dir.path("out");
|
||||
// An export holds the worker, so the save waits behind it and Cancel comes before it starts.
|
||||
crate::io::export(&mut app, Some("svg"), Some(dir.path("first.svg")), &json!({})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
package_dialog(&mut app, &out);
|
||||
assert_eq!(confirm(&mut app).unwrap()["background"], true);
|
||||
assert_eq!(app.run("file.cancelSave", json!({})).unwrap()["cancelled"], 1);
|
||||
gate.open();
|
||||
background::wait_all(&mut app);
|
||||
assert_eq!(written(&files), [dir.path("first.svg")], "only the export");
|
||||
assert!(!std::path::Path::new(&out).join("card Folder").exists(), "no package folder");
|
||||
assert!(app.session.active().unwrap().is_dirty(), "the save was canceled");
|
||||
}
|
||||
|
||||
/// A package that an automation request confined to its roots asks for, started once the
|
||||
/// document's background save is written, is still confined to those roots, though the save's
|
||||
/// result arrives outside the request.
|
||||
|
||||
@@ -234,6 +234,24 @@ fn cancel_and_apply_go_back_to_keyboard_shortcuts() {
|
||||
assert_eq!((app.ui.shortcut_set.as_str(), app.ui.shortcut_overrides.len()), ("Acme Keys", 3));
|
||||
}
|
||||
|
||||
/// Started from VectorCraft's defaults, an import leaves no hold shortcut in the working set; added
|
||||
/// to the current shortcuts, it keeps them. OK keeps what the working set shows.
|
||||
#[test]
|
||||
fn an_import_from_the_defaults_clears_the_hold_shortcuts() {
|
||||
let mut app = app();
|
||||
earlier_answers(&mut app);
|
||||
for (start, kept) in [("defaults", json!({})), ("current", json!({"paint.swap": "X"}))] {
|
||||
app.ui.shortcut_holds = [("paint.swap".to_string(), "X".to_string())].into();
|
||||
shortcut_editor::open(&mut app);
|
||||
super::shortcut_import::open(&mut app, "/sets/Acme Keys.kys", SET.as_bytes()).unwrap();
|
||||
set(&mut app, "start", json!(start));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(dialog(&app).fields["holds"], kept, "{start}");
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(json!(app.ui.shortcut_holds), kept, "{start}: OK keeps it");
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's Missing Fonts dialog that Keyboard Shortcuts replaced waits while Cancel goes back
|
||||
/// from Import Shortcut Set to Keyboard Shortcuts, and opens again once Keyboard Shortcuts closes.
|
||||
#[test]
|
||||
|
||||
@@ -7,11 +7,17 @@
|
||||
//! Cancel), Continue in Background (`file.exportInBackground`) closes the
|
||||
//! dialog and leaves the export to the status bar.
|
||||
//!
|
||||
//! A save running in the background (Background Save) shows in the same window, with a moving bar
|
||||
//! (a save counts no steps) and how many more saves wait: Cancel (`file.cancelSave`, also Esc)
|
||||
//! stops it before it replaces its file, and Continue in Background (`file.saveInBackground`)
|
||||
//! leaves it to the status bar.
|
||||
//!
|
||||
//! It opens after [`DELAY`] so a quick export doesn't flash it, and waits while another dialog is
|
||||
//! open (the overwrite question, an options dialog): never two modals at once.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::background::Kind;
|
||||
use crate::dialogs::modal;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
@@ -24,11 +30,12 @@ fn seen_id() -> egui::Id {
|
||||
egui::Id::unique("export-progress-seen")
|
||||
}
|
||||
|
||||
/// What the dialog shows: (label, steps done, steps in all, share done, exports after this one,
|
||||
/// what the steps are).
|
||||
/// What the dialog shows: (label, steps done, steps in all, share done, jobs of its kind after this
|
||||
/// one, what the steps are).
|
||||
fn shown(app: &VectorcraftApp, now: f64, ctx: &egui::Context) -> Option<(String, u64, u64, f32, usize, Steps)> {
|
||||
let jobs: Vec<_> = app.background.jobs.iter().filter(|j| !j.hidden && !j.cancelled()).filter(|j| j.progress.is_some()).collect();
|
||||
let first = jobs.first()?;
|
||||
let more = jobs.iter().filter(|j| j.kind == first.kind).count() - 1;
|
||||
let since = ctx.data_mut(|m| {
|
||||
let seen = m.get_temp_mut_or_insert_with(seen_id(), || (first.id(), now));
|
||||
if seen.0 != first.id() {
|
||||
@@ -42,11 +49,12 @@ fn shown(app: &VectorcraftApp, now: f64, ctx: &egui::Context) -> Option<(String,
|
||||
let (done, total) = first.progress.as_ref().map(|p| p.counts()).unwrap_or_default();
|
||||
let frac = first.progress.as_ref().and_then(|p| p.fraction()).unwrap_or(0.0) as f32;
|
||||
let steps = match &first.progress {
|
||||
_ if first.kind == Kind::Save => Steps::Save,
|
||||
Some(p) if p.counts_share() => Steps::Share,
|
||||
Some(p) if p.counts_files() => Steps::Files,
|
||||
_ => Steps::Artboards,
|
||||
};
|
||||
Some((first.label.clone(), done, total, frac, jobs.len() - 1, steps))
|
||||
Some((first.label.clone(), done, total, frac, more, steps))
|
||||
}
|
||||
|
||||
/// What an export's steps are.
|
||||
@@ -57,6 +65,8 @@ enum Steps {
|
||||
Files,
|
||||
/// An exporter plug-in's own steps, shown as a share of the work.
|
||||
Share,
|
||||
/// A save, which counts no steps: a moving bar.
|
||||
Save,
|
||||
}
|
||||
|
||||
/// Draws the window for the first export running in the background that wasn't hidden or
|
||||
@@ -71,6 +81,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let t = Tokens::get(ctx);
|
||||
let heading = format!("{}…", crate::i18n::msg(&label));
|
||||
let pressed = window(ctx, "export-progress", &heading, |ui| {
|
||||
if steps == Steps::Save {
|
||||
indeterminate(ui, tl!("Encoding and writing the file…"));
|
||||
if more > 0 {
|
||||
ui.add_space(6.0);
|
||||
let queued = crate::i18n::tn(more as u64, "{n} more save waiting", "{n} more saves waiting");
|
||||
ui.label(egui::RichText::new(queued).size(11.5).color(t.text_dim));
|
||||
}
|
||||
return;
|
||||
}
|
||||
// One step says nothing a spinner doesn't: the bar would sit at 0 % until the file is written.
|
||||
if steps == Steps::Share && total > 0 {
|
||||
share(ui, tl!("Encoding and writing the file…"), frac);
|
||||
@@ -95,10 +114,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
ui.label(egui::RichText::new(queued).size(11.5).color(t.text_dim));
|
||||
}
|
||||
});
|
||||
let id = match pressed {
|
||||
Some(Pressed::Cancel) => "file.cancelExport",
|
||||
Some(Pressed::Hide) => "file.exportInBackground",
|
||||
None => return,
|
||||
let id = match (pressed, steps == Steps::Save) {
|
||||
(Some(Pressed::Cancel), false) => "file.cancelExport",
|
||||
(Some(Pressed::Hide), false) => "file.exportInBackground",
|
||||
(Some(Pressed::Cancel), true) => "file.cancelSave",
|
||||
(Some(Pressed::Hide), true) => "file.saveInBackground",
|
||||
(None, _) => return,
|
||||
};
|
||||
if let Err(e) = app.run(id, json!({})) {
|
||||
app.status(e);
|
||||
@@ -298,6 +319,45 @@ mod tests {
|
||||
assert!(app.background.jobs.is_empty());
|
||||
}
|
||||
|
||||
/// A Background Save shows in the window after the delay, with a moving bar and how many more
|
||||
/// saves wait, never over another dialog; Continue in Background hides it and the saves go on.
|
||||
/// With Background Save off the save is written at once and no window shows.
|
||||
#[test]
|
||||
fn a_background_save_shows_in_the_window_and_continue_hides_it() {
|
||||
let go = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let mut app = app(go.clone());
|
||||
for name in ["a", "b"] {
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = app.run("file.save", json!({"path": format!("/docs/{name}.vectorcraft")})).unwrap();
|
||||
assert_eq!(r["background"], true, "{r}");
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
assert!(!frame(&mut app, &ctx, 0.0).contains("Saving a.vectorcraft"), "not before the delay");
|
||||
// Another dialog is open: the window waits.
|
||||
app.ui.dialog = Some(crate::state::Dialog::new("about", json!({})));
|
||||
frame(&mut app, &ctx, 1.0);
|
||||
assert!(!frame(&mut app, &ctx, 1.1).contains("Saving a.vectorcraft"), "never over another dialog");
|
||||
app.ui.dialog = None;
|
||||
frame(&mut app, &ctx, 1.2);
|
||||
let shown = frame(&mut app, &ctx, 1.3);
|
||||
assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("1 more save waiting"), "{shown}");
|
||||
assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}");
|
||||
assert_eq!(app.run("file.saveInBackground", json!({})).unwrap()["hidden"], 2);
|
||||
assert!(!frame(&mut app, &ctx, 2.0).contains("Saving"), "hidden saves aren't shown");
|
||||
assert!(crate::menus::enabled(&app, "file.cancelSave"), "they can still be canceled");
|
||||
go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
background::wait_all(&mut app);
|
||||
assert!(app.background.jobs.is_empty());
|
||||
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/docs/b.vectorcraft"));
|
||||
app.session.execute("prefs.set", &json!({"values": {"backgroundSave": false}})).unwrap();
|
||||
app.services.write = Some(Box::new(|_: &str, _: &[u8]| Ok(())));
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = app.run("file.save", json!({"path": "/docs/c.vectorcraft"}));
|
||||
assert!(r.as_ref().is_ok_and(|r| r.get("background").is_none()), "{r:?}");
|
||||
assert!(app.background.jobs.is_empty() && !frame(&mut app, &ctx, 3.0).contains("Saving"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_export_of_files_counts_files() {
|
||||
let go = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
|
||||
@@ -842,6 +842,7 @@ font-technology Variable Променливи
|
||||
Duplicate Action or Action Set Дублиране на действие или набор от действия
|
||||
Delete the action set “{name}” and its actions? Изтриване на набора от действия „{name}“ и неговите действия?
|
||||
Delete the selected action sets and their actions? Изтриване на избраните набори от действия и техните действия?
|
||||
Delete all action sets and their actions? Изтриване на всички набори от действия и техните действия?
|
||||
Delete Theme Изтриване на тема
|
||||
Delete theme Изтриване на тема
|
||||
Delete these {n} graphic styles? Изтриване на тези {n} графични стила?
|
||||
@@ -1303,6 +1304,7 @@ font-technology Variable Променливи
|
||||
Fit to Selected Art Побиране спрямо избраната графика
|
||||
Flag… Знаме…
|
||||
Flare Взрив
|
||||
Edit Flare Редактиране на взрива
|
||||
Flare Tool Инструмент „Взрив“
|
||||
Flare Tool Options Опции на инструмента „Взрив“
|
||||
Halo Ореол
|
||||
@@ -2179,6 +2181,9 @@ font-technology Variable Променливи
|
||||
Navigate Навигация
|
||||
Navigator Навигатор
|
||||
Navigator Panel Options Опции за панела „Навигатор“
|
||||
Attributes Panel Options Опции за панела „Атрибути“
|
||||
Number of Recent URLs: Брой скорошни URL адреси:
|
||||
@msg `count` must be a whole number from 1 to 30 `count` трябва да е цяло число от 1 до 30
|
||||
Draw Dashed Lines as Solid Lines Изчертаване на прекъснатите линии като плътни
|
||||
Needs the desktop app Изисква десктоп приложение
|
||||
Neutral Gradients Неутрални градиенти
|
||||
@@ -2645,6 +2650,7 @@ font-technology Variable Променливи
|
||||
Save Actions… Запазване на действия…
|
||||
Load Actions… Зареждане на действия…
|
||||
Replace Actions… Замяна на действия…
|
||||
Clear Actions Изчистване на действия
|
||||
Reset Actions Нулиране на действия
|
||||
Replace the current actions with the default set? Да се заменят ли текущите действия с набора по подразбиране?
|
||||
Append adds the default set after the current sets instead. С „Добавяне“ наборът по подразбиране се добавя след текущите набори.
|
||||
@@ -3084,6 +3090,8 @@ digits Malayalam Малаялам
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колелцето на мишката с натиснат Cmd/Ctrl превърта платното настрани.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Влаченето настрани върху етикета на числово поле променя стойността на полето.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. Жест за завъртане с два пръста върху тъчпад завърта изгледа на платното.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Задържането на клавиш изпълнява инструмента или командата от колоната „Задръжте“ в „Клавишни комбинации“; краткото натискане изпълнява обичайната му комбинация.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Колко секунди трябва да се задържи клавиш, преди вместо обичайната му комбинация да се изпълни комбинацията му със задържане.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Когато премествате котвени точки, всяка крива с една преместена крайна точка запазва формата си спрямо краищата си.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Задържането на клавишната комбинация на инструмент го избира, докато я пуснете, а след това отново се избира предишният инструмент.
|
||||
Shows the bounding box while you move the selection or draw a shape. Показва ограничителната рамка, докато премествате селекцията или рисувате форма.
|
||||
@@ -4810,6 +4818,7 @@ axis Both И двете
|
||||
@msg no graphic style `{n}` няма графичен стил `{n}`
|
||||
@msg no interaction in progress няма текущо взаимодействие
|
||||
@msg no key object няма основен обект
|
||||
@msg Align to Key Object isn't available with the Artboard tool „Подравняване спрямо ключов обект“ не е налично с инструмента „Работна област“
|
||||
@msg no library `{key}` (see {list}) няма библиотека `{key}` (вижте {list})
|
||||
@msg no native format няма нативен формат
|
||||
@msg no pages няма страници
|
||||
@@ -4861,6 +4870,8 @@ axis Both И двете
|
||||
@msg no such spine point няма такава точка от оста
|
||||
@msg `with` must be a list of at most 10000 spine point indexes `with` трябва да е списък с най-много 10000 индекса на точки от оста
|
||||
@msg `with` moves points, not a handle `with` мести точки, не дръжка
|
||||
@msg `link` and `independent` cannot both be true `link` и `independent` не могат и двата да са true
|
||||
@msg `link` places a handle: give `handle` `link` поставя дръжка: задайте `handle`
|
||||
@msg no such spine segment няма такъв сегмент от оста
|
||||
@msg no such subpath няма такъв подпът
|
||||
@msg no such user library няма такава потребителска библиотека
|
||||
@@ -4947,6 +4958,7 @@ axis Both И двете
|
||||
@msg select a blend изберете преход (blend)
|
||||
@msg select a blend or give `id` изберете преливане или задайте неговия `id`
|
||||
@msg select a clip group изберете група за изрязване
|
||||
@msg select a flare изберете взрив
|
||||
@msg select a gradient mesh изберете мрежа на градиент (gradient mesh)
|
||||
@msg select a linked image: an embedded one has no file изберете свързано изображение: вграденото няма файл
|
||||
@msg select a repeat изберете повторение (repeat)
|
||||
@@ -5160,6 +5172,7 @@ axis Both И двете
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} свързано изображение е променено на диска: „Обновяване на връзките“ показва новата версия|{n} свързани изображения са променени на диска: „Обновяване на връзките“ показва новите версии
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Обновен е {n} свързан файл, променен на диска|Обновени са {n} свързани файла, променени на диска
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings документът задава изтичане, което този PDF/X файл пропуска: включете „Използване на настройките за изтичане на документа“
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} обект достига ръба на обрязване, но не стига до изтичането|{n} обекта достигат ръба на обрязване, но не стигат до изтичането
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} е експортиран с {n} бележка: {first}|{what} е експортиран с {n} бележки: {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} шрифтов файл вече е в {folder}|{n} шрифтови файла вече са в {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} шрифтов файл вече е в {folder}; {failed} не можаха да бъдат добавени: {reason}|{n} шрифтови файла вече са в {folder}; {failed} не можаха да бъдат добавени: {reason}
|
||||
@@ -6334,6 +6347,9 @@ theme Appearance Външен вид
|
||||
Continue in Background Продължаване във фонов режим
|
||||
Cancel Export Отказ от експортирането
|
||||
@msg Export cancelled Експортирането е отказано
|
||||
Cancel Save Отказ от записването
|
||||
@plural {n} more save waiting|{n} more saves waiting Още {n} записване в изчакване|Още {n} записвания в изчакване
|
||||
@msg Save canceled Записването е отказано
|
||||
# Paragraph panel menu › Justification…
|
||||
Desired Желано
|
||||
Word Spacing: Разстояние между думите:
|
||||
@@ -6637,6 +6653,12 @@ axis Y Axis Y ос
|
||||
Bus Lines Шинни линии
|
||||
Terminal Nodes Крайни възли
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Стрелки
|
||||
Solid Arrow Плътна стрелка
|
||||
Open Arrow Отворена стрелка
|
||||
Chevron Arrow Стрелка с шеврон
|
||||
|
||||
Notched Ribbon Назъбена лента
|
||||
Double Line Двойна линия
|
||||
Wave Вълна
|
||||
@@ -7291,10 +7313,18 @@ breakText Glyphs Глифи
|
||||
Smooth Bridge… Плавен мост…
|
||||
Smooth Bridge Плавен мост
|
||||
Keep Originals Запазване на оригиналите
|
||||
@msg select two circles to bridge изберете два кръга за свързване
|
||||
@msg select two or more circles to bridge изберете два или повече кръга за свързване
|
||||
@msg one circle is inside the other единият кръг е вътре в другия
|
||||
@msg the circles are too far apart for this radius: raise the radius кръговете са твърде далеч един от друг за този радиус: увеличете радиуса
|
||||
@msg the circles are too far apart for this radius кръговете са твърде далеч един от друг за този радиус
|
||||
Constant Gap Постоянно разстояние
|
||||
Reach: Обхват:
|
||||
@msg the circles are too far apart for this gap: raise the gap кръговете са твърде далеч един от друг за това разстояние: увеличете разстоянието
|
||||
@msg the circles are too far apart for this gap кръговете са твърде далеч един от друг за това разстояние
|
||||
@msg no two circles are within reach: raise the reach няма два кръга в обхват: увеличете обхвата
|
||||
@msg select at most 2000 circles to bridge изберете най-много 2000 кръга за свързване
|
||||
@msg that makes too many bridges (at most 8000): lower the reach това дава твърде много мостове (най-много 8000): намалете обхвата
|
||||
@msg the bridged circles are too complex to unite свързаните кръгове са твърде сложни за обединяване
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Общи допирателни…
|
||||
Common Tangents Общи допирателни
|
||||
@@ -7654,6 +7684,17 @@ 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"
|
||||
Tap Кратко натискане
|
||||
Clear Hold Изчистване на задържането
|
||||
Hold Shortcuts Комбинации със задържане
|
||||
Hold Shortcut Delay Забавяне на комбинациите със задържане
|
||||
How hold shortcuts work Как работят комбинациите със задържане
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Щракнете и натиснете клавиш, който да се задържа за това (Esc отменя). Задържането на клавиша изпълнява това; краткото натискане изпълнява собствената комбинация на клавиша.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Краткото натискане на клавиш изпълнява неговата комбинация. Задържането на клавиша за времето на забавяне изпълнява вместо това инструмента или командата от колоната му „Задръжте“. Комбинация със задържане е клавиш с буква, цифра или препинателен знак, самостоятелно или с Shift.
|
||||
@msg Hold {_1} is already used by {_2} Задържането на {_1} вече се използва от {_2}
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) комбинация със задържане е клавиш, който въвежда знак, самостоятелно или с Shift ({shown} съдържа Cmd, Ctrl или Alt)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} не може да бъде комбинация със задържане: използвайте буква, цифра или препинателен знак
|
||||
Dashed Arrow Пунктирана стрелка
|
||||
Pressure Sensitive Чувствителни на натиск
|
||||
Flex Ribbon Гъвкава лента
|
||||
Pulse Stroke Пулсиращ щрих
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -810,6 +810,9 @@
|
||||
Magic Wand Čarobni štapić
|
||||
Navigator Navigator
|
||||
Navigator Panel Options Opcije panela navigatora
|
||||
Attributes Panel Options Opcije panela atributa
|
||||
Number of Recent URLs: Broj nedavnih URL-ova:
|
||||
@msg `count` must be a whole number from 1 to 30 `count` mora biti cijeli broj od 1 do 30
|
||||
Draw Dashed Lines as Solid Lines Crtaj isprekidane linije kao pune
|
||||
Pattern Options Opcije uzorka
|
||||
Properties Svojstva
|
||||
@@ -1561,6 +1564,7 @@ lighting Light Svjetlo
|
||||
Save Actions… Sačuvaj akcije…
|
||||
Load Actions… Učitaj akcije…
|
||||
Replace Actions… Zamijeni akcije…
|
||||
Clear Actions Očisti akcije
|
||||
Reset Actions Vrati akcije na početno
|
||||
Replace the current actions with the default set? Zamijeniti trenutne akcije zadanim skupom?
|
||||
Append adds the default set after the current sets instead. Dugme Dodaj umjesto toga dodaje zadani skup iza trenutnih skupova.
|
||||
@@ -1865,6 +1869,7 @@ digits Malayalam Malajalam
|
||||
Duplicate Action or Action Set Dupliciraj akciju ili skup akcija
|
||||
Delete the action set “{name}” and its actions? Izbrisati skup akcija „{name}” i njegove akcije?
|
||||
Delete the selected action sets and their actions? Izbrisati odabrane skupove akcija i njihove akcije?
|
||||
Delete all action sets and their actions? Izbrisati sve skupove akcija i njihove akcije?
|
||||
Delete these {n} graphic styles? Izbrisati ove grafičke stilove ({n})?
|
||||
Delete this {n} graphic style? Izbrisati ovaj grafički stil ({n})?
|
||||
Graphic Style Libraries Menu Meni biblioteka grafičkih stilova
|
||||
@@ -4260,6 +4265,7 @@ theme Appearance Izgled
|
||||
Set Tab Stops Postavi tabulatore
|
||||
Tab Stops Tabulatori
|
||||
Flare Odsjaj
|
||||
Edit Flare Uredi odsjaj
|
||||
Rays Zrake
|
||||
Rectangle Pravougaonik
|
||||
Paintbrush Kist
|
||||
@@ -4551,6 +4557,8 @@ font-technology Variable Varijabilni
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Točkić miša uz pritisnut Cmd/Ctrl pomjera platno u stranu.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Prevlačenje u stranu po oznaci brojčanog polja mijenja vrijednost polja.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. Pokret rotacije s dva prsta na dodirnoj podlozi rotira prikaz platna.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Držanje tipke pokreće alat ili naredbu iz njene kolone „Zadrži“ u Prečicama na tastaturi; kratki pritisak pokreće njenu uobičajenu prečicu.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Koliko sekundi tipka mora biti pritisnuta prije nego što se umjesto uobičajene prečice pokrene njena prečica zadržavanjem.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kada pomjerate sidrene tačke, svaka kriva s jednim pomjerenim krajem zadržava svoj oblik u odnosu na svoje krajeve.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Držanje prečice alata bira taj alat dok je ne pustite, a zatim se ponovo bira prethodni alat.
|
||||
Shows the bounding box while you move the selection or draw a shape. Prikazuje granični okvir dok pomjerate odabir ili crtate oblik.
|
||||
@@ -5223,6 +5231,7 @@ imageTrace Outline Obris
|
||||
@msg no graphic style `{n}` nema grafičkog stila `{n}`
|
||||
@msg no interaction in progress nema interakcije u toku
|
||||
@msg no key object nema ključnog objekta
|
||||
@msg Align to Key Object isn't available with the Artboard tool „Poravnaj s ključnim objektom“ nije dostupno s alatom radna ploča
|
||||
@msg no library `{key}` (see {list}) nema biblioteke `{key}` (vidi {list})
|
||||
@msg no native format nema izvornog formata
|
||||
@msg no pages nema stranica
|
||||
@@ -5278,6 +5287,8 @@ imageTrace Outline Obris
|
||||
@msg no such spine point nema takve tačke kičme
|
||||
@msg `with` must be a list of at most 10000 spine point indexes `with` mora biti lista od najviše 10000 indeksa tačaka kičme
|
||||
@msg `with` moves points, not a handle `with` pomjera tačke, ne ručicu
|
||||
@msg `link` and `independent` cannot both be true `link` i `independent` ne mogu oba biti true
|
||||
@msg `link` places a handle: give `handle` `link` postavlja ručicu: navedite `handle`
|
||||
@msg no such spine segment nema takvog segmenta kičme
|
||||
@msg no such subpath nema takve podputanje
|
||||
@msg no such user library nema takve korisničke biblioteke
|
||||
@@ -5366,6 +5377,7 @@ imageTrace Outline Obris
|
||||
@msg select a blend odaberite stapanje
|
||||
@msg select a blend or give `id` odaberite stapanje ili navedite `id`
|
||||
@msg select a clip group odaberite grupu isijecanja
|
||||
@msg select a flare odaberite odsjaj
|
||||
@msg select a gradient mesh odaberite gradijentnu mrežu
|
||||
@msg select a linked image: an embedded one has no file odaberite povezanu sliku: ugrađena nema datoteku
|
||||
@msg select a repeat odaberite ponavljanje
|
||||
@@ -5589,6 +5601,7 @@ imageTrace Outline Obris
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} povezana slika promijenjena je na disku: Ažuriraj veze prikazuje novu verziju|{n} povezane slike promijenjene su na disku: Ažuriraj veze prikazuje nove verzije|{n} povezanih slika promijenjeno je na disku: Ažuriraj veze prikazuje nove verzije
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Ažurirana je {n} povezana datoteka promijenjena na disku|Ažurirane su {n} povezane datoteke promijenjene na disku|Ažurirano je {n} povezanih datoteka promijenjenih na disku
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings dokument zadaje napust koji ova PDF/X datoteka izostavlja: uključite „Koristi postavke napusta dokumenta“
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} objekt doseže rub obreza, ali ne doseže napust|{n} objekta dosežu rub obreza, ali ne dosežu napust|{n} objekata doseže rub obreza, ali ne doseže napust
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Izvezeno {what} s {n} bilješkom: {first}|Izvezeno {what} s {n} bilješke: {first}|Izvezeno {what} s {n} bilješki: {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} datoteka fonta sada je u {folder}|{n} datoteke fontova sada su u {folder}|{n} datoteka fontova sada je u {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} datoteka fonta sada je u {folder}; {failed} nije moguće dodati: {reason}|{n} datoteke fontova sada su u {folder}; {failed} nije moguće dodati: {reason}|{n} datoteka fontova sada je u {folder}; {failed} nije moguće dodati: {reason}
|
||||
@@ -6358,6 +6371,9 @@ mark-style Japanese Japanski
|
||||
Continue in Background Nastavi u pozadini
|
||||
Cancel Export Otkaži izvoz
|
||||
@msg Export cancelled Izvoz otkazan
|
||||
Cancel Save Otkaži čuvanje
|
||||
@plural {n} more save waiting|{n} more saves waiting Čeka još {n} čuvanje|Čekaju još {n} čuvanja|Čeka još {n} čuvanja
|
||||
@msg Save canceled Čuvanje otkazano
|
||||
Desired Željeno
|
||||
Word Spacing: Razmak riječi:
|
||||
Letter Spacing: Razmak slova:
|
||||
@@ -6693,6 +6709,12 @@ axis Y Axis Y osa
|
||||
Bus Lines Linije sabirnice
|
||||
Terminal Nodes Priključni čvorovi
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Strelice
|
||||
Solid Arrow Puna strelica
|
||||
Open Arrow Otvorena strelica
|
||||
Chevron Arrow Strelica sa ševronom
|
||||
|
||||
Notched Ribbon Zarezana traka
|
||||
Double Line Dvostruka linija
|
||||
Wave Talas
|
||||
@@ -7340,10 +7362,18 @@ shape Open Otvoren
|
||||
Smooth Bridge… Glatki most…
|
||||
Smooth Bridge Glatki most
|
||||
Keep Originals Zadrži originale
|
||||
@msg select two circles to bridge odaberite dva kruga za premošćavanje
|
||||
@msg select two or more circles to bridge odaberite dva ili više krugova za premošćavanje
|
||||
@msg one circle is inside the other jedan krug je unutar drugog
|
||||
@msg the circles are too far apart for this radius: raise the radius krugovi su predaleko jedan od drugog za ovaj radijus: povećajte radijus
|
||||
@msg the circles are too far apart for this radius krugovi su predaleko jedan od drugog za ovaj radijus
|
||||
Constant Gap Stalni razmak
|
||||
Reach: Domet:
|
||||
@msg the circles are too far apart for this gap: raise the gap krugovi su predaleko jedan od drugog za ovaj razmak: povećajte razmak
|
||||
@msg the circles are too far apart for this gap krugovi su predaleko jedan od drugog za ovaj razmak
|
||||
@msg no two circles are within reach: raise the reach nijedna dva kruga nisu u dometu: povećajte domet
|
||||
@msg select at most 2000 circles to bridge odaberite najviše 2000 krugova za premošćavanje
|
||||
@msg that makes too many bridges (at most 8000): lower the reach to daje previše mostova (najviše 8000): smanjite domet
|
||||
@msg the bridged circles are too complex to unite premošteni krugovi su previše složeni za spajanje
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Zajedničke tangente…
|
||||
Common Tangents Zajedničke tangente
|
||||
@@ -7709,6 +7739,17 @@ 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"
|
||||
Tap Kratki pritisak
|
||||
Clear Hold Očisti zadržavanje
|
||||
Hold Shortcuts Prečice zadržavanjem
|
||||
Hold Shortcut Delay Kašnjenje prečica zadržavanjem
|
||||
How hold shortcuts work Kako rade prečice zadržavanjem
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Kliknite, zatim pritisnite tipku koju treba zadržati za ovo (Esc otkazuje). Zadržavanje tipke pokreće ovo; kratki pritisak pokreće vlastitu prečicu tipke.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Kratki pritisak tipke pokreće njenu prečicu. Zadržavanje tipke tokom kašnjenja umjesto toga pokreće alat ili naredbu iz njene kolone Zadrži. Prečica zadržavanjem je tipka sa slovom, cifrom ili interpunkcijskim znakom, sama ili sa Shift.
|
||||
@msg Hold {_1} is already used by {_2} Zadržavanje {_1} već koristi {_2}
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) prečica zadržavanjem je tipka koja upisuje znak, sama ili sa Shift ({shown} ima Cmd, Ctrl ili Alt)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} ne može biti prečica zadržavanjem: koristite slovo, cifru ili interpunkcijsku tipku
|
||||
Dashed Arrow Isprekidana strelica
|
||||
Pressure Sensitive Osjetljivo na pritisak
|
||||
Flex Ribbon Savijajuća traka
|
||||
Pulse Stroke Pulsirajući potez
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1227,6 +1227,7 @@ antiAlias Sharp Nítid
|
||||
Duplicate Action or Action Set Duplica l’acció o el conjunt d’accions
|
||||
Delete the action set “{name}” and its actions? Voleu suprimir el conjunt d’accions “{name}” i les seves accions?
|
||||
Delete the selected action sets and their actions? Voleu suprimir els conjunts d’accions seleccionats i les seves accions?
|
||||
Delete all action sets and their actions? Voleu suprimir tots els conjunts d’accions i les seves accions?
|
||||
Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”?
|
||||
Delete Theme Suprimeix el tema
|
||||
Delete theme Suprimeix el tema
|
||||
@@ -1836,6 +1837,7 @@ digits Malayalam Malaiàlam
|
||||
Fixed Fix
|
||||
Flag… Marca…
|
||||
Flare Resplendor
|
||||
Edit Flare Edita el resplendor
|
||||
Flare Tool Eina de resplendor
|
||||
Flare Tool Options Opcions de l’eina de resplendor
|
||||
Flat Angle Angle pla
|
||||
@@ -2861,6 +2863,9 @@ digits Malayalam Malaiàlam
|
||||
Navigate Navega
|
||||
Navigator Navegador
|
||||
Navigator Panel Options Opcions del panell Navegador
|
||||
Attributes Panel Options Opcions del panell Atributs
|
||||
Number of Recent URLs: Nombre d’URL recents:
|
||||
@msg `count` must be a whole number from 1 to 30 `count` ha de ser un nombre enter d’1 a 30
|
||||
Draw Dashed Lines as Solid Lines Dibuixa les línies discontínues com a contínues
|
||||
Needs a choice Necessita una tria
|
||||
Needs a key Necessita una clau
|
||||
@@ -3423,6 +3428,7 @@ digits Malayalam Malaiàlam
|
||||
Save Actions… Desa les accions…
|
||||
Load Actions… Carrega accions…
|
||||
Replace Actions… Reemplaça les accions…
|
||||
Clear Actions Esborra les accions
|
||||
Reset Actions Restableix les accions
|
||||
Replace the current actions with the default set? Voleu reemplaçar les accions actuals pel conjunt predeterminat?
|
||||
Append adds the default set after the current sets instead. Amb Afegeix, el conjunt predeterminat s’afegeix després dels conjunts actuals.
|
||||
@@ -3935,6 +3941,8 @@ digits Malayalam Malaiàlam
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La roda del ratolí amb Cmd/Ctrl premut desplaça el llenç en horitzontal.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Arrossegar en horitzontal sobre l’etiqueta d’un camp numèric canvia el valor del camp.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. Un gest de rotació amb dos dits al trackpad gira la vista del llenç.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Mantenir premuda una tecla executa l’eina o l’ordre de la seva columna Mantén a Dreceres de teclat; una pulsació breu executa la seva drecera habitual.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Quants segons cal mantenir premuda una tecla perquè s’executi la seva drecera de pulsació llarga en lloc de la drecera habitual.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quan moveu punts d’ancoratge, cada corba amb un extrem desplaçat conserva la forma respecte dels seus extrems.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantenir premuda la drecera d’una eina la tria fins que la deixeu anar, i després es torna a triar l’eina anterior.
|
||||
Shows the bounding box while you move the selection or draw a shape. Mostra el quadre delimitador mentre moveu la selecció o dibuixeu una forma.
|
||||
@@ -4301,6 +4309,12 @@ digits Malayalam Malaiàlam
|
||||
Bus Lines Línies de bus
|
||||
Terminal Nodes Nodes terminals
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Fletxes
|
||||
Solid Arrow Fletxa sòlida
|
||||
Open Arrow Fletxa oberta
|
||||
Chevron Arrow Fletxa amb galó
|
||||
|
||||
Notched Ribbon Cinta dentada
|
||||
Double Line Línia doble
|
||||
Wave Ona
|
||||
@@ -6426,6 +6440,9 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg Expand: no gradient fills Expandeix: no hi ha farciments de degradat
|
||||
@msg Expand: nothing to expand Expandeix: no hi ha res per expandir
|
||||
@msg Export cancelled Exportació cancel·lada
|
||||
Cancel Save Cancel·la el desament
|
||||
@plural {n} more save waiting|{n} more saves waiting {n} desament més en espera|{n} desaments més en espera
|
||||
@msg Save canceled Desament cancel·lat
|
||||
@msg Exported {path} S’ha exportat {path}
|
||||
@msg Exported {what} S’ha exportat {what}
|
||||
@msg Exporting {_1} S’està exportant {_1}
|
||||
@@ -6636,6 +6653,7 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg no history state {v} no hi ha cap estat de l’historial {v}
|
||||
@msg no interaction in progress no hi ha cap interacció en curs
|
||||
@msg no key object no hi ha objecte clau
|
||||
@msg Align to Key Object isn't available with the Artboard tool «Alinea a l’objecte clau» no està disponible amb l’eina de tauler
|
||||
@msg no library `{id}` no hi ha la biblioteca `{id}`
|
||||
@msg the library has another item of that kind named `{name}` la biblioteca ja té un altre element d’aquest tipus anomenat `{name}`
|
||||
@msg no library `{key}` (see {list}) no hi ha la biblioteca `{key}` (vegeu {list})
|
||||
@@ -6707,6 +6725,8 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg no such spine point no existeix aquest punt de l’espina
|
||||
@msg `with` must be a list of at most 10000 spine point indexes `with` ha de ser una llista d’un màxim de 10000 índexs de punts de l’espina
|
||||
@msg `with` moves points, not a handle `with` mou punts, no una nansa
|
||||
@msg `link` and `independent` cannot both be true `link` i `independent` no poden ser true alhora
|
||||
@msg `link` places a handle: give `handle` `link` col·loca una nansa: indiqueu `handle`
|
||||
@msg no such spine segment no existeix aquest segment de l’espina
|
||||
@msg no such subpath no existeix aquest subtraçat
|
||||
@msg no such user library no existeix aquesta biblioteca d’usuari
|
||||
@@ -6852,6 +6872,7 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} imatge enllaçada ha canviat al disc: Actualitza els enllaços mostra la versió nova|{n} imatges enllaçades han canviat al disc: Actualitza els enllaços mostra les versions noves
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk S’ha actualitzat {n} fitxer enllaçat que ha canviat al disc|S’han actualitzat {n} fitxers enllaçats que han canviat al disc
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings el document defineix un sangrat que aquest fitxer PDF/X omet: activeu «Utilitza la configuració de sangrat del document»
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} objecte arriba a la vora de tall però no arriba al sangrat|{n} objectes arriben a la vora de tall però no arriben al sangrat
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} S’ha exportat {what} amb {n} nota: {first}|S’ha exportat {what} amb {n} notes: {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} fitxer de tipus de lletra ja és a {folder}|{n} fitxers de tipus de lletra ja són a {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} fitxer de tipus de lletra ja és a {folder}; {failed} no s’han pogut afegir: {reason}|{n} fitxers de tipus de lletra ja són a {folder}; {failed} no s’han pogut afegir: {reason}
|
||||
@@ -6896,6 +6917,7 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg select a blend selecciona una fusió
|
||||
@msg select a blend or give `id` selecciona una fusió o dona `id`
|
||||
@msg select a clip group selecciona un grup de retall
|
||||
@msg select a flare selecciona un resplendor
|
||||
@msg select a gradient mesh selecciona una malla de degradat
|
||||
@msg select a linked image: an embedded one has no file selecciona una imatge enllaçada: una d’incrustada no té fitxer
|
||||
@msg select a Live Paint group selecciona un grup de pintura interactiva
|
||||
@@ -8084,10 +8106,18 @@ breakText Glyphs Glifs
|
||||
Smooth Bridge… Pont suau…
|
||||
Smooth Bridge Pont suau
|
||||
Keep Originals Conserva els originals
|
||||
@msg select two circles to bridge seleccioneu dos cercles per unir-los
|
||||
@msg select two or more circles to bridge seleccioneu dos o més cercles per unir-los
|
||||
@msg one circle is inside the other un cercle és dins de l’altre
|
||||
@msg the circles are too far apart for this radius: raise the radius els cercles estan massa separats per a aquest radi: augmenteu el radi
|
||||
@msg the circles are too far apart for this radius els cercles estan massa separats per a aquest radi
|
||||
Constant Gap Separació constant
|
||||
Reach: Abast:
|
||||
@msg the circles are too far apart for this gap: raise the gap els cercles estan massa separats per a aquesta separació: augmenteu la separació
|
||||
@msg the circles are too far apart for this gap els cercles estan massa separats per a aquesta separació
|
||||
@msg no two circles are within reach: raise the reach no hi ha dos cercles dins de l’abast: augmenteu l’abast
|
||||
@msg select at most 2000 circles to bridge seleccioneu com a màxim 2000 cercles per unir-los
|
||||
@msg that makes too many bridges (at most 8000): lower the reach això fa massa ponts (com a màxim 8000): reduïu l’abast
|
||||
@msg the bridged circles are too complex to unite els cercles units són massa complexos per combinar-los
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Tangents comunes…
|
||||
Common Tangents Tangents comunes
|
||||
@@ -8611,6 +8641,17 @@ 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"
|
||||
Tap Pulsació breu
|
||||
Clear Hold Esborra la pulsació llarga
|
||||
Hold Shortcuts Dreceres de pulsació llarga
|
||||
Hold Shortcut Delay Retard de les dreceres de pulsació llarga
|
||||
How hold shortcuts work Com funcionen les dreceres de pulsació llarga
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Fes clic i prem una tecla per mantenir premuda per a això (Esc cancel·la). Mantenir premuda la tecla executa això; una pulsació breu executa la drecera pròpia de la tecla.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Una pulsació breu d’una tecla executa la seva drecera. Mantenir premuda la tecla durant el retard executa en canvi l’eina o l’ordre de la seva columna Mantén. Una drecera de pulsació llarga és una tecla de lletra, xifra o puntuació, sola o amb Shift.
|
||||
@msg Hold {_1} is already used by {_2} La pulsació llarga de {_1} ja la fa servir {_2}
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) una drecera de pulsació llarga és una tecla que escriu un caràcter, sola o amb Shift ({shown} té Cmd, Ctrl o Alt)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} no pot ser una drecera de pulsació llarga: fes servir una lletra, una xifra o una tecla de puntuació
|
||||
Dashed Arrow Fletxa discontínua
|
||||
@msg a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first una línia o un altre traçat obert que no tanca cap àrea no aporta cap àrea a la forma composta; per incloure’l, apliqueu-hi primer Objecte › Traçat › Contorneja el traç
|
||||
Pressure Sensitive Sensible a la pressió
|
||||
Flex Ribbon Cinta flexible
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -824,6 +824,9 @@
|
||||
Magic Wand Kouzelná hůlka
|
||||
Navigator Navigátor
|
||||
Navigator Panel Options Možnosti panelu Navigátor
|
||||
Attributes Panel Options Možnosti panelu Atributy
|
||||
Number of Recent URLs: Počet nedávných URL:
|
||||
@msg `count` must be a whole number from 1 to 30 `count` musí být celé číslo od 1 do 30
|
||||
Draw Dashed Lines as Solid Lines Kreslit čárkované čáry jako plné
|
||||
Pattern Options Možnosti vzorku
|
||||
Properties Vlastnosti
|
||||
@@ -1590,6 +1593,7 @@ lighting Light Světlo
|
||||
Save Actions… Uložit akce…
|
||||
Load Actions… Načíst akce…
|
||||
Replace Actions… Nahradit akce…
|
||||
Clear Actions Vymazat akce
|
||||
Reset Actions Obnovit akce
|
||||
Replace the current actions with the default set? Nahradit aktuální akce výchozí sadou?
|
||||
Append adds the default set after the current sets instead. Tlačítko Připojit místo toho přidá výchozí sadu za aktuální sady.
|
||||
@@ -1937,6 +1941,7 @@ digits Malayalam Malajálamské
|
||||
Duplicate Action or Action Set Duplikovat akci nebo sadu akcí
|
||||
Delete the action set “{name}” and its actions? Odstranit sadu akcí „{name}“ a její akce?
|
||||
Delete the selected action sets and their actions? Odstranit vybrané sady akcí a jejich akce?
|
||||
Delete all action sets and their actions? Odstranit všechny sady akcí a jejich akce?
|
||||
Delete these {n} graphic styles? Odstranit tyto grafické styly ({n})?
|
||||
Delete this {n} graphic style? Odstranit tento grafický styl ({n})?
|
||||
Graphic Style Libraries Menu Nabídka knihoven grafických stylů
|
||||
@@ -4371,6 +4376,7 @@ theme Appearance Motiv
|
||||
Set Tab Stops Nastavit zarážky tabulátoru
|
||||
Tab Stops Zarážky tabulátoru
|
||||
Flare Odlesk
|
||||
Edit Flare Upravit odlesk
|
||||
Rays Paprsky
|
||||
Rectangle Obdélník
|
||||
Paintbrush Štětec
|
||||
@@ -4662,6 +4668,8 @@ font-technology Variable Variabilní
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Kolečko myši s podrženou klávesou Cmd/Ctrl posouvá plátno do stran.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Tažení do stran po popisku číselného pole mění hodnotu pole.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. Gesto otočení dvěma prsty na trackpadu otáčí zobrazení plátna.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Podržení klávesy spustí nástroj nebo příkaz ze sloupce Podržení v Klávesových zkratkách; krátký stisk spustí její obvyklou zkratku.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Jak dlouho v sekundách je nutné klávesu podržet, než se místo obvyklé zkratky spustí její zkratka podržením.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Když přesouváte kotvové body, každá křivka s jedním přesunutým koncem si zachová tvar vůči svým koncům.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Podržení zkratky nástroje vybere nástroj, dokud ji nepustíte, a pak se znovu vybere předchozí nástroj.
|
||||
Shows the bounding box while you move the selection or draw a shape. Zobrazí ohraničovací rámeček, když přesouváte výběr nebo kreslíte tvar.
|
||||
@@ -5541,6 +5549,7 @@ liquify-list-end {0}, {1} {0} a {1}
|
||||
@msg no graphic style `{n}` grafický styl `{n}` neexistuje
|
||||
@msg no interaction in progress neprobíhá žádná interakce
|
||||
@msg no key object žádný klíčový objekt
|
||||
@msg Align to Key Object isn't available with the Artboard tool „Zarovnat ke klíčovému objektu“ není s nástrojem Pracovní plocha k dispozici
|
||||
@msg no library `{key}` (see {list}) knihovna `{key}` neexistuje (viz {list})
|
||||
@msg no native format chybí nativní formát
|
||||
@msg no pages žádné stránky
|
||||
@@ -5596,6 +5605,8 @@ liquify-list-end {0}, {1} {0} a {1}
|
||||
@msg no such spine point takový bod páteře neexistuje
|
||||
@msg `with` must be a list of at most 10000 spine point indexes `with` musí být seznam nejvýše 10000 indexů bodů páteře
|
||||
@msg `with` moves points, not a handle `with` posouvá body, ne táhlo
|
||||
@msg `link` and `independent` cannot both be true `link` a `independent` nemohou být zároveň true
|
||||
@msg `link` places a handle: give `handle` `link` umisťuje táhlo: zadejte `handle`
|
||||
@msg no such spine segment takový segment páteře neexistuje
|
||||
@msg no such subpath taková dílčí cesta neexistuje
|
||||
@msg no such user library taková uživatelská knihovna neexistuje
|
||||
@@ -5684,6 +5695,7 @@ liquify-list-end {0}, {1} {0} a {1}
|
||||
@msg select a blend vyberte prolnutí
|
||||
@msg select a blend or give `id` vyberte prolnutí, nebo zadejte `id`
|
||||
@msg select a clip group vyberte ořezovou skupinu
|
||||
@msg select a flare vyberte odlesk
|
||||
@msg select a gradient mesh vyberte přechodovou síť
|
||||
@msg select a linked image: an embedded one has no file vyberte propojený obrázek: vložený nemá soubor
|
||||
@msg select a repeat vyberte opakování
|
||||
@@ -5941,6 +5953,7 @@ variable-list-end {0}, {1} {0} a {1}
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions Na disku se změnil {n} propojený obrázek: novou verzi zobrazí Aktualizovat propojení|Na disku se změnily {n} propojené obrázky: nové verze zobrazí Aktualizovat propojení|Na disku se změnilo {n} propojených obrázků: nové verze zobrazí Aktualizovat propojení
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Aktualizován {n} propojený soubor změněný na disku|Aktualizovány {n} propojené soubory změněné na disku|Aktualizováno {n} propojených souborů změněných na disku
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings dokument nastavuje spadávku, kterou tento soubor PDF/X vynechává: zapněte „Použít nastavení spadávky dokumentu“
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} objekt sahá k hraně ořezu, ale nedosahuje do spadávky|{n} objekty sahají k hraně ořezu, ale nedosahují do spadávky|{n} objektů sahá k hraně ořezu, ale nedosahuje do spadávky
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Exportováno: {what}, {n} poznámka: {first}|Exportováno: {what}, {n} poznámky: {first}|Exportováno: {what}, {n} poznámek: {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} soubor písma je nyní ve složce {folder}|{n} soubory písem jsou nyní ve složce {folder}|{n} souborů písem je nyní ve složce {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} soubor písma je nyní ve složce {folder}; nepodařilo se přidat {failed}: {reason}|{n} soubory písem jsou nyní ve složce {folder}; nepodařilo se přidat {failed}: {reason}|{n} souborů písem je nyní ve složce {folder}; nepodařilo se přidat {failed}: {reason}
|
||||
@@ -6867,6 +6880,9 @@ mark-style Japanese Japonské
|
||||
Continue in Background Pokračovat na pozadí
|
||||
Cancel Export Zrušit export
|
||||
@msg Export cancelled Export byl zrušen
|
||||
Cancel Save Zrušit ukládání
|
||||
@plural {n} more save waiting|{n} more saves waiting Čeká ještě {n} uložení|Čekají ještě {n} uložení|Čeká ještě {n} uložení
|
||||
@msg Save canceled Ukládání bylo zrušeno
|
||||
# Paragraph panel menu › Justification…
|
||||
Desired Požadované
|
||||
Word Spacing: Mezery mezi slovy:
|
||||
@@ -7385,6 +7401,12 @@ axis Y Axis osa Y
|
||||
Bus Lines Sběrnicové linky
|
||||
Terminal Nodes Koncové uzly
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Šipky
|
||||
Solid Arrow Plná šipka
|
||||
Open Arrow Otevřená šipka
|
||||
Chevron Arrow Šipka s krokví
|
||||
|
||||
Notched Ribbon Vroubkovaná stuha
|
||||
Double Line Dvojitá čára
|
||||
Wave Vlna
|
||||
@@ -8069,10 +8091,18 @@ breakText Glyphs Glyfy
|
||||
Smooth Bridge… Hladký most…
|
||||
Smooth Bridge Hladký most
|
||||
Keep Originals Zachovat originály
|
||||
@msg select two circles to bridge vyberte dva kruhy k propojení
|
||||
@msg select two or more circles to bridge vyberte dva nebo více kruhů k propojení
|
||||
@msg one circle is inside the other jeden kruh je uvnitř druhého
|
||||
@msg the circles are too far apart for this radius: raise the radius kruhy jsou pro tento poloměr příliš daleko od sebe: zvětšete poloměr
|
||||
@msg the circles are too far apart for this radius kruhy jsou pro tento poloměr příliš daleko od sebe
|
||||
Constant Gap Stálá mezera
|
||||
Reach: Dosah:
|
||||
@msg the circles are too far apart for this gap: raise the gap kruhy jsou pro tuto mezeru příliš daleko od sebe: zvětšete mezeru
|
||||
@msg the circles are too far apart for this gap kruhy jsou pro tuto mezeru příliš daleko od sebe
|
||||
@msg no two circles are within reach: raise the reach žádné dva kruhy nejsou v dosahu: zvětšete dosah
|
||||
@msg select at most 2000 circles to bridge vyberte nejvýše 2000 kruhů k propojení
|
||||
@msg that makes too many bridges (at most 8000): lower the reach to dává příliš mnoho mostů (nejvýše 8000): zmenšete dosah
|
||||
@msg the bridged circles are too complex to unite propojené kruhy jsou příliš složité na sloučení
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Společné tečny…
|
||||
Common Tangents Společné tečny
|
||||
@@ -10376,6 +10406,16 @@ breakText Glyphs Glyfy
|
||||
No objects are selected. Nejsou vybrány žádné objekty.
|
||||
Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu.
|
||||
Remove Fold Line Role Odstranit typ linie
|
||||
Tap Krátký stisk
|
||||
Clear Hold Vymazat podržení
|
||||
Hold Shortcuts Zkratky podržením
|
||||
Hold Shortcut Delay Prodleva zkratek podržením
|
||||
How hold shortcuts work Jak fungují zkratky podržením
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Klikněte a stiskněte klávesu, kterou pro toto podržíte (Esc zruší). Podržení klávesy spustí toto; krátký stisk spustí vlastní zkratku klávesy.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Krátký stisk klávesy spustí její zkratku. Podržení klávesy po dobu prodlevy místo toho spustí nástroj nebo příkaz z jejího sloupce Podržení. Zkratka podržením je klávesa s písmenem, číslicí nebo interpunkcí, samotná nebo se Shiftem.
|
||||
@msg Hold {_1} is already used by {_2} Podržení {_1} už používá {_2}
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) zkratka podržením je klávesa, která píše znak, samotná nebo se Shiftem ({shown} obsahuje Cmd, Ctrl nebo Alt)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} nemůže být zkratkou podržením: použijte písmeno, číslici nebo interpunkční klávesu
|
||||
Check Zkontrolovat
|
||||
Check Fold Lines Zkontrolovat linie skladu
|
||||
@msg No cut lines are in the selection. Ve výběru nejsou žádné linie řezu.
|
||||
@@ -10396,6 +10436,7 @@ 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}
|
||||
Dashed Arrow Přerušovaná šipka
|
||||
Pressure Sensitive Citlivé na tlak
|
||||
Flex Ribbon Pružná stuha
|
||||
Pulse Stroke Pulzující tah
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -295,6 +295,8 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg no such spine point intet sådant rygradpunkt
|
||||
@msg `with` must be a list of at most 10000 spine point indexes `with` skal være en liste med højst 10000 rygradpunktindekser
|
||||
@msg `with` moves points, not a handle `with` flytter punkter, ikke et håndtag
|
||||
@msg `link` and `independent` cannot both be true `link` og `independent` kan ikke begge være true
|
||||
@msg `link` places a handle: give `handle` `link` placerer et håndtag: angiv `handle`
|
||||
@msg no such spine segment intet sådant rygradsegment
|
||||
@msg node {_1} is on a locked artboard node {_1} ligger på en låst tegneflade
|
||||
@msg not a blend ikke en blanding
|
||||
@@ -3497,6 +3499,9 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
Magic Wand Magisk tryllestav
|
||||
Navigator Navigator
|
||||
Navigator Panel Options Indstillinger for navigatorpanelet
|
||||
Attributes Panel Options Indstillinger for attributpanelet
|
||||
Number of Recent URLs: Antal seneste URL'er:
|
||||
@msg `count` must be a whole number from 1 to 30 `count` skal være et heltal fra 1 til 30
|
||||
Draw Dashed Lines as Solid Lines Tegn stiplede linjer som hele linjer
|
||||
Pattern Options Mønsterindstillinger
|
||||
Properties Egenskaber
|
||||
@@ -4217,6 +4222,7 @@ lighting Light Lys
|
||||
Save Actions… Gem handlinger…
|
||||
Load Actions… Indlæs handlinger…
|
||||
Replace Actions… Erstat handlinger…
|
||||
Clear Actions Ryd handlinger
|
||||
Reset Actions Nulstil handlinger
|
||||
Replace the current actions with the default set? Vil du erstatte de aktuelle handlinger med standardsættet?
|
||||
Append adds the default set after the current sets instead. Tilføj tilføjer i stedet standardsættet efter de aktuelle sæt.
|
||||
@@ -4561,6 +4567,7 @@ digits Malayalam Malayalam
|
||||
Duplicate Action or Action Set Duplikér handling eller handlingssæt
|
||||
Delete the action set “{name}” and its actions? Slet handlingssættet »{name}« og dets handlinger?
|
||||
Delete the selected action sets and their actions? Slet de markerede handlingssæt og deres handlinger?
|
||||
Delete all action sets and their actions? Slet alle handlingssæt og deres handlinger?
|
||||
Delete these {n} graphic styles? Slet disse {n} grafiske typografier?
|
||||
Delete this {n} graphic style? Slet denne {n} grafiske typografi?
|
||||
Graphic Style Libraries Menu Menu med biblioteker af grafiske typografier
|
||||
@@ -6801,6 +6808,7 @@ theme Appearance Udseende
|
||||
Set Tab Stops Angiv tabulatorstop
|
||||
Tab Stops Tabulatorstop
|
||||
Flare Flare
|
||||
Edit Flare Redigér flare
|
||||
Rays Stråler
|
||||
Rectangle Rektangel
|
||||
Paintbrush Malerpensel
|
||||
@@ -7081,6 +7089,8 @@ font-technology Variable Variable
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Musehjulet med Cmd/Ctrl holdt nede ruller lærredet sidelæns.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Når du trækker sidelæns på et talfelts etiket, ændres feltets værdi.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsbevægelse med to fingre på en pegeplade roterer visningen af lærredet.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Når du holder en tast nede, køres værktøjet eller kommandoen i dens Hold-kolonne i Tastaturgenveje; et kort tryk kører dens sædvanlige genvej.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hvor mange sekunder en tast skal holdes nede, før dens holdegenvej køres i stedet for dens sædvanlige genvej.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Når du flytter ankerpunkter, beholder hver kurve med ét flyttet endepunkt sin form i forhold til sine endepunkter.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Når du holder et værktøjs genvejstast nede, er værktøjet valgt, indtil du slipper, og derefter vælges det forrige værktøj igen.
|
||||
Shows the bounding box while you move the selection or draw a shape. Viser afgrænsningsboksen, mens du flytter markeringen eller tegner en form.
|
||||
@@ -7711,6 +7721,7 @@ imageTrace Outline Kontur
|
||||
@msg no graphic style `{n}` ingen grafisk stil `{n}`
|
||||
@msg no interaction in progress ingen interaktion i gang
|
||||
@msg no key object intet nøgleobjekt
|
||||
@msg Align to Key Object isn't available with the Artboard tool Juster til nøgleobjekt er ikke tilgængelig med tegnebrætværktøjet
|
||||
@msg no library `{key}` (see {list}) intet bibliotek `{key}` (se {list})
|
||||
@msg no native format intet indbygget format
|
||||
@msg no pages ingen sider
|
||||
@@ -7841,6 +7852,7 @@ imageTrace Outline Kontur
|
||||
@msg select a Live Paint group markér en Live Paint-gruppe
|
||||
@msg select a blend markér en blanding
|
||||
@msg select a clip group markér en klipgruppe
|
||||
@msg select a flare markér en flare
|
||||
@msg select a gradient mesh markér et gradientnet
|
||||
@msg select a linked image: an embedded one has no file markér et linket billede: et indlejret har ingen fil
|
||||
@msg select a repeat markér en gentagelse
|
||||
@@ -8048,6 +8060,7 @@ imageTrace Outline Kontur
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} linket billede er ændret på disken: Opdatér links viser den nye version|{n} linkede billeder er ændret på disken: Opdatér links viser de nye versioner
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Opdaterede {n} linket fil ændret på disken|Opdaterede {n} linkede filer ændret på disken
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings dokumentet angiver et udløb, som denne PDF/X-fil udelader: slå „Brug dokumentets udløbsindstillinger“ til
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} objekt når til beskæringskanten, men stopper før udløbet|{n} objekter når til beskæringskanten, men stopper før udløbet
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Eksporterede {what} med {n} note: {first}|Eksporterede {what} med {n} noter: {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} skrifttypefil er nu i {folder}|{n} skrifttypefiler er nu i {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} skrifttypefil er nu i {folder}; {failed} kunne ikke tilføjes: {reason}|{n} skrifttypefiler er nu i {folder}; {failed} kunne ikke tilføjes: {reason}
|
||||
@@ -9149,6 +9162,9 @@ swatch Bright Violet Kraftig violet
|
||||
Continue in Background Fortsæt i baggrunden
|
||||
Cancel Export Annullér eksport
|
||||
@msg Export cancelled Eksport annulleret
|
||||
Cancel Save Annullér gemning
|
||||
@plural {n} more save waiting|{n} more saves waiting {n} gemning mere venter|{n} gemninger mere venter
|
||||
@msg Save canceled Gemning annulleret
|
||||
# Paragraph panel menu › Justification…
|
||||
Desired Ønsket
|
||||
Word Spacing: Ordafstand:
|
||||
@@ -9470,6 +9486,12 @@ axis Y Axis Y-akse
|
||||
Bus Lines Buslinjer
|
||||
Terminal Nodes Terminalpunkter
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Pile
|
||||
Solid Arrow Massiv pil
|
||||
Open Arrow Åben pil
|
||||
Chevron Arrow Chevronpil
|
||||
|
||||
Notched Ribbon Takket bånd
|
||||
Double Line Dobbelt linje
|
||||
Wave Bølge
|
||||
@@ -10123,10 +10145,18 @@ breakText Glyphs Glyffer
|
||||
Smooth Bridge… Blød bro…
|
||||
Smooth Bridge Blød bro
|
||||
Keep Originals Behold originaler
|
||||
@msg select two circles to bridge vælg to cirkler, der skal forbindes
|
||||
@msg select two or more circles to bridge vælg to eller flere cirkler, der skal forbindes
|
||||
@msg one circle is inside the other den ene cirkel er inden i den anden
|
||||
@msg the circles are too far apart for this radius: raise the radius cirklerne er for langt fra hinanden til denne radius: gør radius større
|
||||
@msg the circles are too far apart for this radius cirklerne er for langt fra hinanden til denne radius
|
||||
Constant Gap Konstant afstand
|
||||
Reach: Rækkevidde:
|
||||
@msg the circles are too far apart for this gap: raise the gap cirklerne er for langt fra hinanden til denne afstand: gør afstanden større
|
||||
@msg the circles are too far apart for this gap cirklerne er for langt fra hinanden til denne afstand
|
||||
@msg no two circles are within reach: raise the reach ingen to cirkler er inden for rækkevidde: gør rækkevidden større
|
||||
@msg select at most 2000 circles to bridge vælg højst 2000 cirkler, der skal forbindes
|
||||
@msg that makes too many bridges (at most 8000): lower the reach det giver for mange broer (højst 8000): gør rækkevidden mindre
|
||||
@msg the bridged circles are too complex to unite de forbundne cirkler er for komplekse til at blive samlet
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Fælles tangenter…
|
||||
Common Tangents Fælles tangenter
|
||||
@@ -10499,6 +10529,17 @@ 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"
|
||||
Tap Kort tryk
|
||||
Clear Hold Ryd hold
|
||||
Hold Shortcuts Holdegenveje
|
||||
Hold Shortcut Delay Forsinkelse for holdegenveje
|
||||
How hold shortcuts work Sådan virker holdegenveje
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Klik, og tryk derefter på en tast, der skal holdes nede for dette (Esc annullerer). Når tasten holdes nede, køres dette; et kort tryk kører tastens egen genvej.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Et kort tryk på en tast kører dens genvej. Når tasten holdes nede i forsinkelsens varighed, køres i stedet værktøjet eller kommandoen i dens Hold-kolonne. En holdegenvej er en bogstav-, ciffer- eller tegnsætningstast, alene eller med Shift.
|
||||
@msg Hold {_1} is already used by {_2} Hold {_1} bruges allerede af {_2}
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) en holdegenvej er en tast, der skriver et tegn, alene eller med Shift ({shown} har Cmd, Ctrl eller Alt)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} kan ikke være en holdegenvej: brug et bogstav, et ciffer eller en tegnsætningstast
|
||||
Dashed Arrow Stiplet pil
|
||||
@msg a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first en linje eller anden åben kurve, der ikke omslutter noget område, tilføjer intet område til den sammensatte figur; anvend først Objekt › Kurve › Streg til kontur på den for at tage den med
|
||||
Pressure Sensitive Trykfølsom
|
||||
Flex Ribbon Fleksibelt bånd
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -854,6 +854,7 @@ font-technology Variable Variabel
|
||||
Duplicate Action or Action Set Aktion oder Aktionssatz duplizieren
|
||||
Delete the action set “{name}” and its actions? Aktionssatz „{name}“ und seine Aktionen löschen?
|
||||
Delete the selected action sets and their actions? Ausgewählte Aktionssätze und ihre Aktionen löschen?
|
||||
Delete all action sets and their actions? Alle Aktionssätze und ihre Aktionen löschen?
|
||||
Delete Theme Thema löschen
|
||||
Delete theme Thema löschen
|
||||
Delete these {n} graphic styles? Diese {n} Grafikstile löschen?
|
||||
@@ -1357,6 +1358,7 @@ font-technology Variable Variabel
|
||||
Fit to Selected Art An ausgewählte Grafik anpassen
|
||||
Flag… Flagge…
|
||||
Flare Blendenfleck
|
||||
Edit Flare Blendenfleck bearbeiten
|
||||
Flare Tool Blendenfleck-Werkzeug
|
||||
Flare Tool Options Optionen für das Blendenfleck-Werkzeug
|
||||
Halo Lichtkranz
|
||||
@@ -2275,6 +2277,9 @@ file-filter Templates Vorlagen
|
||||
Navigate Navigieren
|
||||
Navigator Navigator
|
||||
Navigator Panel Options Optionen für das Navigatorbedienfeld
|
||||
Attributes Panel Options Optionen für das Attributebedienfeld
|
||||
Number of Recent URLs: Anzahl zuletzt verwendeter URLs:
|
||||
@msg `count` must be a whole number from 1 to 30 `count` muss eine ganze Zahl von 1 bis 30 sein
|
||||
Draw Dashed Lines as Solid Lines Gestrichelte Linien als durchgezogene Linien zeichnen
|
||||
Needs the desktop app Erfordert die Desktop-App
|
||||
Neutral Gradients Neutrale Verläufe
|
||||
@@ -2711,6 +2716,7 @@ diagnostics ui Oberfläche
|
||||
Save Actions… Aktionen speichern…
|
||||
Load Actions… Aktionen laden…
|
||||
Replace Actions… Aktionen ersetzen…
|
||||
Clear Actions Aktionen löschen
|
||||
Reset Actions Aktionen zurücksetzen
|
||||
Replace the current actions with the default set? Aktuelle Aktionen durch den Standardsatz ersetzen?
|
||||
Append adds the default set after the current sets instead. Mit „Anhängen“ wird der Standardsatz stattdessen nach den aktuellen Sätzen hinzugefügt.
|
||||
@@ -3156,6 +3162,8 @@ digits Malayalam Malayalam
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Mit gedrückter Befehls-/Strg-Taste scrollt das Mausrad die Arbeitsfläche seitwärts.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Seitliches Ziehen auf der Beschriftung eines Zahlenfelds ändert den Wert des Felds.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. Eine Drehgeste mit zwei Fingern auf einem Trackpad dreht die Ansicht der Arbeitsfläche.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Halten Sie eine Taste, wird das Werkzeug oder der Befehl aus ihrer Spalte „Halten“ unter „Tastaturbefehle“ ausgeführt; ein kurzer Druck führt ihren üblichen Tastaturbefehl aus.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Wie viele Sekunden eine Taste gehalten werden muss, bevor statt ihres üblichen Tastaturbefehls ihr Halte-Tastaturbefehl ausgeführt wird.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Wenn Sie Ankerpunkte verschieben, behält jede Kurve mit einem verschobenen Ende ihre Form relativ zu ihren Enden.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Solange Sie das Tastaturkürzel eines Werkzeugs gedrückt halten, ist dieses Werkzeug gewählt; danach wird wieder das vorherige gewählt.
|
||||
Shows the bounding box while you move the selection or draw a shape. Zeigt den Begrenzungsrahmen an, während Sie die Auswahl verschieben oder eine Form zeichnen.
|
||||
@@ -5137,6 +5145,7 @@ liquify-list-end {0}, {1} {0} und {1}
|
||||
@msg no graphic style `{n}` kein Grafikstil `{n}`
|
||||
@msg no interaction in progress keine Interaktion im Gange
|
||||
@msg no key object kein Basisobjekt
|
||||
@msg Align to Key Object isn't available with the Artboard tool „An Basisobjekt ausrichten“ ist mit dem Zeichenflächen-Werkzeug nicht verfügbar
|
||||
@msg no library `{key}` (see {list}) keine Bibliothek `{key}` (siehe {list})
|
||||
@msg no native format kein natives Format
|
||||
@msg no pages keine Seiten
|
||||
@@ -5192,6 +5201,8 @@ liquify-list-end {0}, {1} {0} und {1}
|
||||
@msg no such spine point kein solcher Achsenpunkt
|
||||
@msg `with` must be a list of at most 10000 spine point indexes `with` muss eine Liste von höchstens 10000 Achsenpunkt-Indizes sein
|
||||
@msg `with` moves points, not a handle `with` verschiebt Punkte, keinen Griff
|
||||
@msg `link` and `independent` cannot both be true `link` und `independent` können nicht beide true sein
|
||||
@msg `link` places a handle: give `handle` `link` platziert einen Griff: geben Sie `handle` an
|
||||
@msg no such spine segment kein solches Achsensegment
|
||||
@msg no such subpath kein solcher Teilpfad
|
||||
@msg no such user library keine solche Benutzerbibliothek
|
||||
@@ -5281,6 +5292,7 @@ liquify-list-end {0}, {1} {0} und {1}
|
||||
@msg select a blend wählen Sie eine Angleichung aus
|
||||
@msg select a blend or give `id` wählen Sie eine Angleichung aus oder geben Sie `id` an
|
||||
@msg select a clip group wählen Sie eine Schnittgruppe aus
|
||||
@msg select a flare wählen Sie einen Blendenfleck aus
|
||||
@msg select a gradient mesh wählen Sie ein Verlaufsgitter aus
|
||||
@msg select a linked image: an embedded one has no file wählen Sie ein verknüpftes Bild aus: Ein eingebettetes hat keine Datei
|
||||
@msg select a repeat wählen Sie eine Wiederholung aus
|
||||
@@ -5538,6 +5550,7 @@ variable-list-end {0}, {1} {0} und {1}
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} verknüpftes Bild wurde auf dem Datenträger geändert: „Verknüpfungen aktualisieren“ zeigt die neue Version|{n} verknüpfte Bilder wurden auf dem Datenträger geändert: „Verknüpfungen aktualisieren“ zeigt die neuen Versionen
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk {n} auf dem Datenträger geänderte verknüpfte Datei aktualisiert|{n} auf dem Datenträger geänderte verknüpfte Dateien aktualisiert
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings das Dokument legt einen Anschnitt fest, den diese PDF/X-Datei auslässt: „Anschnitteinstellungen des Dokuments verwenden“ aktivieren
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} Objekt reicht bis zur Endformatkante, endet aber vor dem Anschnitt|{n} Objekte reichen bis zur Endformatkante, enden aber vor dem Anschnitt
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} mit {n} Hinweis exportiert: {first}|{what} mit {n} Hinweisen exportiert: {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} Schriftdatei liegt jetzt in {folder}|{n} Schriftdateien liegen jetzt in {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} Schriftdatei liegt jetzt in {folder}; {failed} konnten nicht hinzugefügt werden: {reason}|{n} Schriftdateien liegen jetzt in {folder}; {failed} konnten nicht hinzugefügt werden: {reason}
|
||||
@@ -6446,6 +6459,9 @@ effect Soft Weich
|
||||
Continue in Background Im Hintergrund fortsetzen
|
||||
Cancel Export Export abbrechen
|
||||
@msg Export cancelled Export abgebrochen
|
||||
Cancel Save Speichern abbrechen
|
||||
@plural {n} more save waiting|{n} more saves waiting {n} weiterer Speichervorgang wartet|{n} weitere Speichervorgänge warten
|
||||
@msg Save canceled Speichern abgebrochen
|
||||
# Paragraph panel menu › Justification…
|
||||
Desired Optimal
|
||||
Word Spacing: Wortabstand:
|
||||
@@ -6969,6 +6985,13 @@ axis Y Axis Y-Achse
|
||||
Bus Lines Busleitungen
|
||||
Terminal Nodes Anschlussknoten
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Pfeile
|
||||
Solid Arrow Gefüllter Pfeil
|
||||
Open Arrow Offener Pfeil
|
||||
Double Arrow Doppelpfeil
|
||||
Chevron Arrow Winkelpfeil
|
||||
|
||||
Notched Ribbon Gekerbtes Band
|
||||
Double Line Doppellinie
|
||||
Wave Welle
|
||||
@@ -7664,10 +7687,18 @@ breakText Glyphs Glyphen
|
||||
Smooth Bridge… Weiche Brücke…
|
||||
Smooth Bridge Weiche Brücke
|
||||
Keep Originals Originale beibehalten
|
||||
@msg select two circles to bridge wählen Sie zwei Kreise zum Verbinden aus
|
||||
@msg select two or more circles to bridge wählen Sie zwei oder mehr Kreise zum Verbinden aus
|
||||
@msg one circle is inside the other ein Kreis liegt im anderen
|
||||
@msg the circles are too far apart for this radius: raise the radius die Kreise liegen für diesen Radius zu weit auseinander: vergrößern Sie den Radius
|
||||
@msg the circles are too far apart for this radius die Kreise liegen für diesen Radius zu weit auseinander
|
||||
Constant Gap Konstanter Abstand
|
||||
Reach: Reichweite:
|
||||
@msg the circles are too far apart for this gap: raise the gap die Kreise liegen für diesen Abstand zu weit auseinander: vergrößern Sie den Abstand
|
||||
@msg the circles are too far apart for this gap die Kreise liegen für diesen Abstand zu weit auseinander
|
||||
@msg no two circles are within reach: raise the reach keine zwei Kreise liegen in Reichweite: vergrößern Sie die Reichweite
|
||||
@msg select at most 2000 circles to bridge wählen Sie höchstens 2000 Kreise zum Verbinden aus
|
||||
@msg that makes too many bridges (at most 8000): lower the reach das ergibt zu viele Brücken (höchstens 8000): verringern Sie die Reichweite
|
||||
@msg the bridged circles are too complex to unite die verbundenen Kreise sind zu komplex zum Vereinen
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Gemeinsame Tangenten…
|
||||
Common Tangents Gemeinsame Tangenten
|
||||
@@ -9988,6 +10019,16 @@ breakText Glyphs Glyphen
|
||||
No objects are selected. Es sind keine Objekte ausgewählt.
|
||||
Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen.
|
||||
Remove Fold Line Role Linienart entfernen
|
||||
Tap Kurz drücken
|
||||
Clear Hold Halten löschen
|
||||
Hold Shortcuts Halte-Tastaturbefehle
|
||||
Hold Shortcut Delay Verzögerung für Halte-Tastaturbefehle
|
||||
How hold shortcuts work So funktionieren Halte-Tastaturbefehle
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Klicken Sie und drücken Sie dann eine Taste, die hierfür gehalten werden soll (Esc bricht ab). Halten der Taste führt dies aus; kurzes Drücken führt den eigenen Tastaturbefehl der Taste aus.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Kurzes Drücken einer Taste führt ihren Tastaturbefehl aus. Halten der Taste für die Dauer der Verzögerung führt stattdessen das Werkzeug oder den Befehl in ihrer Spalte „Halten“ aus. Ein Halte-Tastaturbefehl ist eine Buchstaben-, Ziffern- oder Satzzeichentaste, allein oder mit Shift.
|
||||
@msg Hold {_1} is already used by {_2} Halten {_1} wird bereits von {_2} verwendet
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) Ein Halte-Tastaturbefehl ist eine Taste, die ein Zeichen eingibt, allein oder mit Shift ({shown} enthält Cmd, Ctrl oder Alt)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} kann kein Halte-Tastaturbefehl sein: Verwenden Sie einen Buchstaben, eine Ziffer oder eine Satzzeichentaste
|
||||
Check Prüfen
|
||||
Check Fold Lines Faltlinien prüfen
|
||||
@msg No cut lines are in the selection. Die Auswahl enthält keine Schnittlinien.
|
||||
@@ -10008,6 +10049,7 @@ 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}
|
||||
Dashed Arrow Gestrichelter Pfeil
|
||||
Pressure Sensitive Druckempfindlich
|
||||
Flex Ribbon Flexibles Band
|
||||
Pulse Stroke Pulsierender Strich
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -827,6 +827,7 @@ font-technology Variable Μεταβλητές
|
||||
Duplicate Action or Action Set Δημιουργία αντιγράφου ενέργειας ή συνόλου ενεργειών
|
||||
Delete the action set “{name}” and its actions? Να διαγραφεί το σύνολο ενεργειών «{name}» και οι ενέργειές του;
|
||||
Delete the selected action sets and their actions? Να διαγραφούν τα επιλεγμένα σύνολα ενεργειών και οι ενέργειές τους;
|
||||
Delete all action sets and their actions? Να διαγραφούν όλα τα σύνολα ενεργειών και οι ενέργειές τους;
|
||||
Delete Theme Διαγραφή θέματος
|
||||
Delete theme Διαγραφή θέματος
|
||||
Delete these {n} graphic styles? Να διαγραφούν αυτά τα {n} στυλ γραφικών;
|
||||
@@ -1295,6 +1296,7 @@ font-technology Variable Μεταβλητές
|
||||
Fit to Selected Art Προσαρμογή στο επιλεγμένο γραφικό
|
||||
Flag… Σημαία…
|
||||
Flare Λάμψη
|
||||
Edit Flare Επεξεργασία λάμψης
|
||||
Flare Tool Λάμψη (Flare Tool)
|
||||
Flare Tool Options Επιλογές εργαλείου λάμψης
|
||||
Halo Άλως
|
||||
@@ -1959,6 +1961,9 @@ font-technology Variable Μεταβλητές
|
||||
Name: Όνομα:
|
||||
Navigator Πλοήγηση
|
||||
Navigator Panel Options Επιλογές πίνακα πλοήγησης
|
||||
Attributes Panel Options Επιλογές πίνακα χαρακτηριστικών
|
||||
Number of Recent URLs: Αριθμός πρόσφατων διευθύνσεων URL:
|
||||
@msg `count` must be a whole number from 1 to 30 Το `count` πρέπει να είναι ακέραιος από 1 έως 30
|
||||
Draw Dashed Lines as Solid Lines Σχεδίαση διακεκομμένων γραμμών ως συνεχών
|
||||
New Νέο
|
||||
Scatter: Διασπορά:
|
||||
@@ -3656,6 +3661,7 @@ theme Appearance Εμφάνιση
|
||||
Save Actions… Αποθήκευση ενεργειών…
|
||||
Load Actions… Φόρτωση ενεργειών…
|
||||
Replace Actions… Αντικατάσταση ενεργειών…
|
||||
Clear Actions Απαλοιφή ενεργειών
|
||||
Reset Actions Επαναφορά ενεργειών
|
||||
Replace the current actions with the default set? Να αντικατασταθούν οι τρέχουσες ενέργειες με το προεπιλεγμένο σύνολο;
|
||||
Append adds the default set after the current sets instead. Η Προσάρτηση προσθέτει αντί γι’ αυτό το προεπιλεγμένο σύνολο μετά τα τρέχοντα σύνολα.
|
||||
@@ -4007,6 +4013,8 @@ digits Malayalam Μαλαγιάλαμ
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Ο τροχός του ποντικιού με πατημένο το Cmd/Ctrl κυλά τον καμβά οριζόντια.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Η μεταφορά προς τα πλάγια πάνω στην ετικέτα ενός αριθμητικού πεδίου αλλάζει την τιμή του πεδίου.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. Μια κίνηση περιστροφής με δύο δάχτυλα σε επιφάνεια αφής περιστρέφει την προβολή του καμβά.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Το παρατεταμένο πάτημα ενός πλήκτρου εκτελεί το εργαλείο ή την εντολή της στήλης «Κρατήστε πατημένο» στις Συντομεύσεις πληκτρολογίου· ένα σύντομο πάτημα εκτελεί τη συνηθισμένη συντόμευσή του.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Πόσα δευτερόλεπτα πρέπει να μένει πατημένο ένα πλήκτρο πριν εκτελεστεί η συντόμευση παρατεταμένου πατήματος αντί για τη συνηθισμένη συντόμευσή του.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Όταν μετακινείτε σημεία αγκύρωσης, κάθε καμπύλη με ένα μετακινημένο άκρο διατηρεί το σχήμα της σε σχέση με τα άκρα της.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Όσο κρατάτε πατημένη τη συντόμευση ενός εργαλείου, το εργαλείο είναι επιλεγμένο, και μετά επιλέγεται ξανά το προηγούμενο εργαλείο.
|
||||
Shows the bounding box while you move the selection or draw a shape. Εμφανίζει το πλαίσιο οριοθέτησης όσο μετακινείτε την επιλογή ή σχεδιάζετε ένα σχήμα.
|
||||
@@ -5193,6 +5201,7 @@ digits Malayalam Μαλαγιάλαμ
|
||||
@msg no graphic style `{n}` δεν υπάρχει στυλ γραφικών `{n}`
|
||||
@msg no interaction in progress δεν υπάρχει αλληλεπίδραση σε εξέλιξη
|
||||
@msg no key object δεν υπάρχει βασικό αντικείμενο
|
||||
@msg Align to Key Object isn't available with the Artboard tool η «Στοίχιση ως προς το βασικό αντικείμενο» δεν είναι διαθέσιμη με το εργαλείο πίνακα σχεδίασης
|
||||
@msg no library `{key}` (see {list}) δεν υπάρχει βιβλιοθήκη `{key}` (δείτε {list})
|
||||
@msg no native format δεν υπάρχει εγγενής μορφή
|
||||
@msg no pages δεν υπάρχουν σελίδες
|
||||
@@ -5248,6 +5257,8 @@ digits Malayalam Μαλαγιάλαμ
|
||||
@msg no such spine point δεν υπάρχει τέτοιο σημείο κεντρικής καμπύλης
|
||||
@msg `with` must be a list of at most 10000 spine point indexes το `with` πρέπει να είναι λίστα με έως 10000 δείκτες σημείων κεντρικής καμπύλης
|
||||
@msg `with` moves points, not a handle το `with` μετακινεί σημεία, όχι λαβή
|
||||
@msg `link` and `independent` cannot both be true Τα `link` και `independent` δεν μπορούν να είναι και τα δύο true
|
||||
@msg `link` places a handle: give `handle` το `link` τοποθετεί μια λαβή: δώστε `handle`
|
||||
@msg no such spine segment δεν υπάρχει τέτοιο τμήμα κεντρικής καμπύλης
|
||||
@msg no such subpath δεν υπάρχει τέτοια υποδιαδρομή
|
||||
@msg no such user library δεν υπάρχει τέτοια βιβλιοθήκη χρήστη
|
||||
@@ -5341,6 +5352,7 @@ digits Malayalam Μαλαγιάλαμ
|
||||
@msg select a blend επιλέξτε ανάμειξη
|
||||
@msg select a blend or give `id` επιλέξτε ανάμειξη ή δώστε το `id`
|
||||
@msg select a clip group επιλέξτε ομάδα αποκοπής
|
||||
@msg select a flare επιλέξτε λάμψη
|
||||
@msg select a gradient mesh επιλέξτε πλέγμα ντεγκραντέ
|
||||
@msg select a linked image: an embedded one has no file επιλέξτε συνδεδεμένη εικόνα: η ενσωματωμένη δεν έχει αρχείο
|
||||
@msg select a repeat επιλέξτε επανάληψη
|
||||
@@ -5591,6 +5603,7 @@ variable-list-end {0}, {1} {0} και {1}
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} συνδεδεμένη εικόνα άλλαξε στον δίσκο: η Ενημέρωση συνδέσμων εμφανίζει τη νέα έκδοση|{n} συνδεδεμένες εικόνες άλλαξαν στον δίσκο: η Ενημέρωση συνδέσμων εμφανίζει τις νέες εκδόσεις
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Ενημερώθηκε {n} συνδεδεμένο αρχείο που άλλαξε στον δίσκο|Ενημερώθηκαν {n} συνδεδεμένα αρχεία που άλλαξαν στον δίσκο
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings το έγγραφο ορίζει ξάκρισμα που αυτό το αρχείο PDF/X παραλείπει: ενεργοποιήστε τη «Χρήση ρυθμίσεων ξακρίσματος εγγράφου»
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} αντικείμενο φτάνει στο άκρο κοπής αλλά σταματά πριν από το ξάκρισμα|{n} αντικείμενα φτάνουν στο άκρο κοπής αλλά σταματούν πριν από το ξάκρισμα
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Εξήχθη το {what} με {n} σημείωση: {first}|Εξήχθη το {what} με {n} σημειώσεις: {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} αρχείο γραμματοσειράς βρίσκεται πλέον στον φάκελο {folder}|{n} αρχεία γραμματοσειρών βρίσκονται πλέον στον φάκελο {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} αρχείο γραμματοσειράς βρίσκεται πλέον στον φάκελο {folder}· δεν ήταν δυνατή η προσθήκη {failed}: {reason}|{n} αρχεία γραμματοσειρών βρίσκονται πλέον στον φάκελο {folder}· δεν ήταν δυνατή η προσθήκη {failed}: {reason}
|
||||
@@ -6853,6 +6866,9 @@ effect Points Σημεία
|
||||
Continue in Background Συνέχεια στο παρασκήνιο
|
||||
Cancel Export Ακύρωση εξαγωγής
|
||||
@msg Export cancelled Η εξαγωγή ακυρώθηκε
|
||||
Cancel Save Ακύρωση αποθήκευσης
|
||||
@plural {n} more save waiting|{n} more saves waiting {n} ακόμη αποθήκευση σε αναμονή|{n} ακόμη αποθηκεύσεις σε αναμονή
|
||||
@msg Save canceled Η αποθήκευση ακυρώθηκε
|
||||
# Paragraph panel menu › Justification…
|
||||
Desired Επιθυμητό
|
||||
Word Spacing: Απόσταση λέξεων:
|
||||
@@ -7372,6 +7388,12 @@ axis Y Axis Άξονας Y
|
||||
Bus Lines Γραμμές διαύλου
|
||||
Terminal Nodes Τερματικοί κόμβοι
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Βέλη
|
||||
Solid Arrow Συμπαγές βέλος
|
||||
Open Arrow Ανοιχτό βέλος
|
||||
Chevron Arrow Βέλος με σεβρόν
|
||||
|
||||
Notched Ribbon Οδοντωτή κορδέλα
|
||||
Double Line Διπλή γραμμή
|
||||
Wave Κύμα
|
||||
@@ -8057,10 +8079,18 @@ breakText Glyphs Γλύφοι
|
||||
Smooth Bridge… Ομαλή γέφυρα…
|
||||
Smooth Bridge Ομαλή γέφυρα
|
||||
Keep Originals Διατήρηση πρωτοτύπων
|
||||
@msg select two circles to bridge επιλέξτε δύο κύκλους για γεφύρωση
|
||||
@msg select two or more circles to bridge επιλέξτε δύο ή περισσότερους κύκλους για γεφύρωση
|
||||
@msg one circle is inside the other ο ένας κύκλος βρίσκεται μέσα στον άλλο
|
||||
@msg the circles are too far apart for this radius: raise the radius οι κύκλοι απέχουν πολύ μεταξύ τους για αυτή την ακτίνα: αυξήστε την ακτίνα
|
||||
@msg the circles are too far apart for this radius οι κύκλοι απέχουν πολύ μεταξύ τους για αυτή την ακτίνα
|
||||
Constant Gap Σταθερή απόσταση
|
||||
Reach: Εμβέλεια:
|
||||
@msg the circles are too far apart for this gap: raise the gap οι κύκλοι απέχουν πολύ μεταξύ τους για αυτή την απόσταση: αυξήστε την απόσταση
|
||||
@msg the circles are too far apart for this gap οι κύκλοι απέχουν πολύ μεταξύ τους για αυτή την απόσταση
|
||||
@msg no two circles are within reach: raise the reach δεν υπάρχουν δύο κύκλοι εντός εμβέλειας: αυξήστε την εμβέλεια
|
||||
@msg select at most 2000 circles to bridge επιλέξτε έως 2000 κύκλους για γεφύρωση
|
||||
@msg that makes too many bridges (at most 8000): lower the reach αυτό δημιουργεί πάρα πολλές γέφυρες (έως 8000): μειώστε την εμβέλεια
|
||||
@msg the bridged circles are too complex to unite οι γεφυρωμένοι κύκλοι είναι πολύ σύνθετοι για ένωση
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Κοινές εφαπτόμενες…
|
||||
Common Tangents Κοινές εφαπτόμενες
|
||||
@@ -8585,6 +8615,17 @@ 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"
|
||||
Tap Σύντομο πάτημα
|
||||
Clear Hold Εκκαθάριση παρατεταμένου πατήματος
|
||||
Hold Shortcuts Συντομεύσεις παρατεταμένου πατήματος
|
||||
Hold Shortcut Delay Καθυστέρηση συντομεύσεων παρατεταμένου πατήματος
|
||||
How hold shortcuts work Πώς λειτουργούν οι συντομεύσεις παρατεταμένου πατήματος
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Κάντε κλικ και πατήστε ένα πλήκτρο που θα κρατάτε πατημένο για αυτό (Esc για ακύρωση). Το παρατεταμένο πάτημα του πλήκτρου εκτελεί αυτό. Ένα σύντομο πάτημα εκτελεί τη συντόμευση του ίδιου του πλήκτρου.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Ένα σύντομο πάτημα πλήκτρου εκτελεί τη συντόμευσή του. Αν κρατήσετε πατημένο το πλήκτρο για τον χρόνο καθυστέρησης, εκτελείται αντί γι’ αυτό το εργαλείο ή η εντολή της στήλης «Κρατήστε πατημένο». Μια συντόμευση παρατεταμένου πατήματος είναι ένα πλήκτρο γράμματος, ψηφίου ή σημείου στίξης, μόνο του ή με Shift.
|
||||
@msg Hold {_1} is already used by {_2} το παρατεταμένο πάτημα του {_1} χρησιμοποιείται ήδη από το {_2}
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) μια συντόμευση παρατεταμένου πατήματος είναι ένα πλήκτρο που πληκτρολογεί έναν χαρακτήρα, μόνο του ή με Shift (το {shown} έχει Cmd, Ctrl ή Alt)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key το {shown} δεν μπορεί να είναι συντόμευση παρατεταμένου πατήματος: χρησιμοποιήστε γράμμα, ψηφίο ή πλήκτρο στίξης
|
||||
Dashed Arrow Διακεκομμένο βέλος
|
||||
@msg a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first μια γραμμή ή άλλη ανοιχτή διαδρομή που δεν περικλείει εμβαδόν δεν προσθέτει εμβαδόν στο σύνθετο σχήμα· για να τη συμπεριλάβετε, εφαρμόστε της πρώτα Αντικείμενο › Διαδρομή › Μετατροπή περιγράμματος σε διαδρομή
|
||||
Pressure Sensitive Ευαίσθητα στην πίεση
|
||||
Flex Ribbon Εύκαμπτη κορδέλα
|
||||
|
||||
|
Can't render this file because it is too large.
|
+1801
-1
File diff suppressed because it is too large.
Load diff
@@ -810,6 +810,9 @@
|
||||
Magic Wand Taikasauva
|
||||
Navigator Navigaattori
|
||||
Navigator Panel Options Navigaattori-paneelin asetukset
|
||||
Attributes Panel Options Määritteet-paneelin asetukset
|
||||
Number of Recent URLs: Viimeisimpien URL-osoitteiden määrä:
|
||||
@msg `count` must be a whole number from 1 to 30 `count` on oltava kokonaisluku 1–30
|
||||
Draw Dashed Lines as Solid Lines Piirrä katkoviivat yhtenäisinä viivoina
|
||||
Pattern Options Kuvion asetukset
|
||||
Properties Ominaisuudet
|
||||
@@ -1559,6 +1562,7 @@ lighting Light Valo
|
||||
Save Actions… Tallenna toiminnot…
|
||||
Load Actions… Lataa toiminnot…
|
||||
Replace Actions… Korvaa toiminnot…
|
||||
Clear Actions Tyhjennä toiminnot
|
||||
Reset Actions Palauta toiminnot
|
||||
Replace the current actions with the default set? Korvataanko nykyiset toiminnot oletussarjalla?
|
||||
Append adds the default set after the current sets instead. Lisää-painike lisää sen sijaan oletussarjan nykyisten sarjojen perään.
|
||||
@@ -1908,6 +1912,7 @@ digits Malayalam Malajalam
|
||||
Duplicate Action or Action Set Monista toiminto tai toimintosarja
|
||||
Delete the action set “{name}” and its actions? Poistetaanko toimintosarja ”{name}” ja sen toiminnot?
|
||||
Delete the selected action sets and their actions? Poistetaanko valitut toimintosarjat ja niiden toiminnot?
|
||||
Delete all action sets and their actions? Poistetaanko kaikki toimintosarjat ja niiden toiminnot?
|
||||
Delete these {n} graphic styles? Poistetaanko nämä {n} grafiikkatyyliä?
|
||||
Delete this {n} graphic style? Poistetaanko tämä {n} grafiikkatyyli?
|
||||
Graphic Style Libraries Menu Grafiikkatyylikirjastojen valikko
|
||||
@@ -4288,6 +4293,7 @@ theme Appearance Ulkoasu
|
||||
Set Tab Stops Aseta sarkainkohdat
|
||||
Tab Stops Sarkainkohdat
|
||||
Flare Häikäisy
|
||||
Edit Flare Muokkaa häikäisyä
|
||||
Rays Säteet
|
||||
Rectangle Suorakulmio
|
||||
Paintbrush Maalaussivellin
|
||||
@@ -4572,6 +4578,8 @@ font-technology Variable Muuttuvat
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Hiiren rulla vierittää piirtopintaa sivuttain, kun Cmd/Ctrl on painettuna.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Numerokentän nimiön vetäminen sivuttain muuttaa kentän arvoa.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. Kahden sormen kiertoele kosketuslevyllä kiertää piirtopinnan näkymää.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Näppäimen pitäminen painettuna suorittaa työkalun tai komennon sen Pidä pohjassa -sarakkeesta Pikanäppäimissä; lyhyt painallus suorittaa sen tavallisen pikanäppäimen.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Kuinka monta sekuntia näppäintä on pidettävä painettuna, ennen kuin tavallisen pikanäppäimen sijaan suoritetaan sen pitkän painalluksen pikanäppäin.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kun siirrät ankkuripisteitä, jokainen käyrä, jonka toinen pää siirtyy, säilyttää muotonsa suhteessa päihinsä.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Työkalun pikanäppäimen pitäminen painettuna valitsee työkalun, kunnes päästät irti, ja sitten edellinen työkalu valitaan uudelleen.
|
||||
Shows the bounding box while you move the selection or draw a shape. Näyttää rajausruudun, kun siirrät valintaa tai piirrät muotoa.
|
||||
@@ -5459,6 +5467,7 @@ liquify-list-end {0}, {1} {0} ja {1}
|
||||
@msg no graphic style `{n}` ei grafiikkatyyliä `{n}`
|
||||
@msg no interaction in progress mikään vuorovaikutus ei ole käynnissä
|
||||
@msg no key object ei avainobjektia
|
||||
@msg Align to Key Object isn't available with the Artboard tool ”Tasaa avainobjektiin” ei ole käytettävissä piirtoalustatyökalulla
|
||||
@msg no library `{key}` (see {list}) ei kirjastoa `{key}` (ks. {list})
|
||||
@msg no native format ei omaa tiedostomuotoa
|
||||
@msg no pages ei sivuja
|
||||
@@ -5514,6 +5523,8 @@ liquify-list-end {0}, {1} {0} ja {1}
|
||||
@msg no such spine point selkärangan pistettä ei ole
|
||||
@msg `with` must be a list of at most 10000 spine point indexes `with`-arvon on oltava luettelo, jossa on enintään 10000 selkärangan pisteen indeksiä
|
||||
@msg `with` moves points, not a handle `with` siirtää pisteitä, ei kahvaa
|
||||
@msg `link` and `independent` cannot both be true `link` ja `independent` eivät voi olla molemmat true
|
||||
@msg `link` places a handle: give `handle` `link` sijoittaa kahvan: anna `handle`
|
||||
@msg no such spine segment selkärangan segmenttiä ei ole
|
||||
@msg no such subpath alipolkua ei ole
|
||||
@msg no such user library käyttäjäkirjastoa ei ole
|
||||
@@ -5606,6 +5617,7 @@ liquify-list-end {0}, {1} {0} ja {1}
|
||||
@msg select a blend valitse sulautus
|
||||
@msg select a blend or give `id` valitse sulautus tai anna sen `id`
|
||||
@msg select a clip group valitse leikkausryhmä
|
||||
@msg select a flare valitse häikäisy
|
||||
@msg select a gradient mesh valitse liukuväriverkko
|
||||
@msg select a linked image: an embedded one has no file valitse linkitetty kuva: upotetulla kuvalla ei ole tiedostoa
|
||||
@msg select a repeat valitse toisto
|
||||
@@ -5856,6 +5868,7 @@ variable-list-end {0}, {1} {0} ja {1}
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} linkitetty kuva muuttui levyllä: Päivitä linkit näyttää uuden version|{n} linkitettyä kuvaa muuttui levyllä: Päivitä linkit näyttää uudet versiot
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk Päivitettiin {n} levyllä muuttunut linkitetty tiedosto|Päivitettiin {n} levyllä muuttunutta linkitettyä tiedostoa
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings asiakirjassa on leikkuuvara, jonka tämä PDF/X-tiedosto jättää pois: ota käyttöön ”Käytä asiakirjan leikkuuvara-asetuksia”
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} objekti ulottuu leikkuureunaan mutta ei leikkuuvaraan|{n} objektia ulottuu leikkuureunaan mutta ei leikkuuvaraan
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} Vietiin {what}, {n} huomautus: {first}|Vietiin {what}, {n} huomautusta: {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} fonttitiedosto on nyt kansiossa {folder}|{n} fonttitiedostoa on nyt kansiossa {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} fonttitiedosto on nyt kansiossa {folder}; {failed} ei voitu lisätä: {reason}|{n} fonttitiedostoa on nyt kansiossa {folder}; {failed} ei voitu lisätä: {reason}
|
||||
@@ -6858,6 +6871,9 @@ mark-style Japanese Japanilainen
|
||||
Continue in Background Jatka taustalla
|
||||
Cancel Export Peruuta vienti
|
||||
@msg Export cancelled Vienti peruutettiin
|
||||
Cancel Save Peruuta tallennus
|
||||
@plural {n} more save waiting|{n} more saves waiting {n} tallennus odottaa|{n} tallennusta odottaa
|
||||
@msg Save canceled Tallennus peruutettiin
|
||||
# Paragraph panel menu › Justification…
|
||||
Desired Haluttu
|
||||
Word Spacing: Sanaväli:
|
||||
@@ -7449,6 +7465,12 @@ axis Y Axis Y-akseli
|
||||
Bus Lines Väylälinjat
|
||||
Terminal Nodes Liitäntäpisteet
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Nuolet
|
||||
Solid Arrow Umpinainen nuoli
|
||||
Open Arrow Avoin nuoli
|
||||
Chevron Arrow Kulmanuoli
|
||||
|
||||
Notched Ribbon Lovettu nauha
|
||||
Double Line Kaksoisviiva
|
||||
Wave Aalto
|
||||
@@ -8133,10 +8155,18 @@ breakText Glyphs Merkit
|
||||
Smooth Bridge… Pehmeä silta…
|
||||
Smooth Bridge Pehmeä silta
|
||||
Keep Originals Säilytä alkuperäiset
|
||||
@msg select two circles to bridge valitse kaksi yhdistettävää ympyrää
|
||||
@msg select two or more circles to bridge valitse vähintään kaksi yhdistettävää ympyrää
|
||||
@msg one circle is inside the other toinen ympyrä on toisen sisällä
|
||||
@msg the circles are too far apart for this radius: raise the radius ympyrät ovat liian kaukana toisistaan tälle säteelle: suurenna sädettä
|
||||
@msg the circles are too far apart for this radius ympyrät ovat liian kaukana toisistaan tälle säteelle
|
||||
Constant Gap Vakioväli
|
||||
Reach: Ulottuvuus:
|
||||
@msg the circles are too far apart for this gap: raise the gap ympyrät ovat liian kaukana toisistaan tälle välille: suurenna väliä
|
||||
@msg the circles are too far apart for this gap ympyrät ovat liian kaukana toisistaan tälle välille
|
||||
@msg no two circles are within reach: raise the reach mitkään kaksi ympyrää eivät ole ulottuvilla: suurenna ulottuvuutta
|
||||
@msg select at most 2000 circles to bridge valitse enintään 2000 yhdistettävää ympyrää
|
||||
@msg that makes too many bridges (at most 8000): lower the reach siitä tulee liikaa siltoja (enintään 8000): pienennä ulottuvuutta
|
||||
@msg the bridged circles are too complex to unite yhdistetyt ympyrät ovat liian monimutkaisia koottaviksi yhdeksi muodoksi
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Yhteiset tangentit…
|
||||
Common Tangents Yhteiset tangentit
|
||||
@@ -8668,6 +8698,17 @@ 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"
|
||||
Tap Lyhyt painallus
|
||||
Clear Hold Tyhjennä pitkä painallus
|
||||
Hold Shortcuts Pitkän painalluksen pikanäppäimet
|
||||
Hold Shortcut Delay Pitkän painalluksen viive
|
||||
How hold shortcuts work Näin pitkän painalluksen pikanäppäimet toimivat
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Napsauta ja paina sitten näppäintä, jota pidetään pohjassa tätä varten (Esc peruuttaa). Näppäimen pitäminen pohjassa suorittaa tämän; lyhyt painallus suorittaa näppäimen oman pikanäppäimen.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Näppäimen lyhyt painallus suorittaa sen pikanäppäimen. Kun näppäintä pidetään pohjassa viiveen ajan, suoritetaan sen sijaan sen Pidä pohjassa -sarakkeen työkalu tai komento. Pitkän painalluksen pikanäppäin on kirjain-, numero- tai välimerkkinäppäin yksin tai Shiftin kanssa.
|
||||
@msg Hold {_1} is already used by {_2} Pitkä painallus {_1} on jo käytössä kohteella {_2}
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) pitkän painalluksen pikanäppäin on merkin kirjoittava näppäin yksin tai Shiftin kanssa ({shown} sisältää Cmd-, Ctrl- tai Alt-näppäimen)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} ei voi olla pitkän painalluksen pikanäppäin: käytä kirjainta, numeroa tai välimerkkinäppäintä
|
||||
Dashed Arrow Katkoviivanuoli
|
||||
@msg a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first viiva tai muu avoin polku, joka ei rajaa aluetta, ei lisää yhdistelmämuotoon aluetta; jos haluat sisällyttää sen, käytä siihen ensin komentoa Objekti › Polku › Ääriviivaa viiva
|
||||
Pressure Sensitive Paineherkkä
|
||||
Flex Ribbon Joustava nauha
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -859,6 +859,7 @@ font-technology Variable Variables
|
||||
Duplicate Action or Action Set Dupliquer le script ou le jeu de scripts
|
||||
Delete the action set “{name}” and its actions? Supprimer le jeu de scripts « {name} » et ses scripts ?
|
||||
Delete the selected action sets and their actions? Supprimer les jeux de scripts sélectionnés et leurs scripts ?
|
||||
Delete all action sets and their actions? Supprimer tous les jeux de scripts et leurs scripts ?
|
||||
Delete Slices Supprimer les tranches
|
||||
Delete Spine Point Supprimer le point de la dorsale
|
||||
Delete Stop Supprimer l’étape de dégradé
|
||||
@@ -1372,6 +1373,7 @@ font-technology Variable Variables
|
||||
Fit to Selected Art Ajuster à l’illustration sélectionnée
|
||||
Flag… Drapeau…
|
||||
Flare Halo
|
||||
Edit Flare Modifier le halo
|
||||
Flare Tool Outil Halo
|
||||
Flare Tool Options Options de l’outil Halo
|
||||
Halo Halo
|
||||
@@ -2264,6 +2266,9 @@ font-technology Variable Variables
|
||||
Navigate Naviguer
|
||||
Navigator Navigation
|
||||
Navigator Panel Options Options du panneau Navigation
|
||||
Attributes Panel Options Options du panneau Options d’objet
|
||||
Number of Recent URLs: Nombre d’URL récentes :
|
||||
@msg `count` must be a whole number from 1 to 30 `count` doit être un nombre entier compris entre 1 et 30
|
||||
Draw Dashed Lines as Solid Lines Dessiner les pointillés en traits pleins
|
||||
Needs the desktop app Nécessite l’application de bureau
|
||||
Neutral Gradients Dégradés neutres
|
||||
@@ -2739,6 +2744,7 @@ font-technology Variable Variables
|
||||
Save Actions… Enregistrer les scripts…
|
||||
Load Actions… Charger des scripts…
|
||||
Replace Actions… Remplacer les scripts…
|
||||
Clear Actions Effacer les scripts
|
||||
Reset Actions Réinitialiser les scripts
|
||||
Replace the current actions with the default set? Remplacer les scripts actuels par le jeu par défaut ?
|
||||
Append adds the default set after the current sets instead. Le bouton Ajouter ajoute plutôt le jeu par défaut après les jeux actuels.
|
||||
@@ -3181,6 +3187,8 @@ digits Malayalam Malayalam
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La molette de la souris avec Cmd/Ctrl enfoncée fait défiler la zone de travail latéralement.
|
||||
Dragging sideways on a numeric field's label changes the field's value. Faire glisser latéralement le libellé d’un champ numérique modifie la valeur du champ.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. Un geste de rotation à deux doigts sur un pavé tactile fait pivoter la vue de la zone de travail.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Maintenir une touche exécute l’outil ou la commande de sa colonne Maintenir dans Raccourcis clavier. Un appui bref exécute son raccourci habituel.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Durée, en secondes, pendant laquelle une touche doit être maintenue pour que son raccourci de maintien s’exécute à la place de son raccourci habituel.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quand vous déplacez des points d’ancrage, chaque courbe dont une extrémité bouge garde sa forme par rapport à ses extrémités.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Maintenir le raccourci d’un outil choisit cet outil jusqu’à ce que vous le relâchiez, puis l’outil précédent est de nouveau choisi.
|
||||
Shows the bounding box while you move the selection or draw a shape. Affiche le cadre de sélection pendant que vous déplacez la sélection ou dessinez une forme.
|
||||
@@ -5207,6 +5215,7 @@ liquify-list-end {0}, {1} {0} et {1}
|
||||
@msg no graphic style `{n}` aucun style graphique `{n}`
|
||||
@msg no interaction in progress aucune interaction en cours
|
||||
@msg no key object aucun objet clé
|
||||
@msg Align to Key Object isn't available with the Artboard tool L’alignement sur l’objet clé n’est pas disponible avec l’outil Plan de travail
|
||||
@msg no library `{key}` (see {list}) aucune bibliothèque `{key}` (voir {list})
|
||||
@msg no native format aucun format natif
|
||||
@msg no pages aucune page
|
||||
@@ -5262,6 +5271,8 @@ liquify-list-end {0}, {1} {0} et {1}
|
||||
@msg no such spine point point de la dorsale inexistant
|
||||
@msg `with` must be a list of at most 10000 spine point indexes `with` doit être une liste d’au plus 10000 indices de points de la dorsale
|
||||
@msg `with` moves points, not a handle `with` déplace des points, pas une poignée
|
||||
@msg `link` and `independent` cannot both be true `link` et `independent` ne peuvent pas valoir true tous les deux
|
||||
@msg `link` places a handle: give `handle` `link` place une poignée : indiquez `handle`
|
||||
@msg no such spine segment segment de la dorsale inexistant
|
||||
@msg no such subpath sous-tracé inexistant
|
||||
@msg no such user library bibliothèque utilisateur inexistante
|
||||
@@ -5351,6 +5362,7 @@ liquify-list-end {0}, {1} {0} et {1}
|
||||
@msg select a blend sélectionnez un dégradé de formes
|
||||
@msg select a blend or give `id` sélectionnez un dégradé de formes ou indiquez son `id`
|
||||
@msg select a clip group sélectionnez un groupe d’écrêtage
|
||||
@msg select a flare sélectionnez un halo
|
||||
@msg select a gradient mesh sélectionnez un filet de dégradé
|
||||
@msg select a linked image: an embedded one has no file sélectionnez une image liée : une image incorporée n’a pas de fichier
|
||||
@msg select a repeat sélectionnez une répétition
|
||||
@@ -5606,6 +5618,7 @@ variable-list-end {0}, {1} {0} et {1}
|
||||
@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions {n} image liée modifiée sur le disque : Mettre à jour les liens affiche la nouvelle version|{n} images liées modifiées sur le disque : Mettre à jour les liens affiche les nouvelles versions
|
||||
@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk {n} fichier lié modifié sur le disque mis à jour|{n} fichiers liés modifiés sur le disque mis à jour
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings le document définit un fond perdu que ce fichier PDF/X omet : activez « Utiliser les paramètres de fond perdu du document »
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} objet atteint le bord de coupe mais s’arrête avant le fond perdu|{n} objets atteignent le bord de coupe mais s’arrêtent avant le fond perdu
|
||||
@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} exporté avec {n} remarque : {first}|{what} exporté avec {n} remarques : {first}
|
||||
@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} fichier de polices se trouve maintenant dans {folder}|{n} fichiers de polices se trouvent maintenant dans {folder}
|
||||
@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} fichier de polices se trouve maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason}|{n} fichiers de polices se trouvent maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason}
|
||||
@@ -6863,6 +6876,9 @@ theme Appearance Apparence
|
||||
Continue in Background Continuer en arrière-plan
|
||||
Cancel Export Annuler l’exportation
|
||||
@msg Export cancelled Exportation annulée
|
||||
Cancel Save Annuler l’enregistrement
|
||||
@plural {n} more save waiting|{n} more saves waiting {n} autre enregistrement en attente|{n} autres enregistrements en attente
|
||||
@msg Save canceled Enregistrement annulé
|
||||
# Paragraph panel menu › Justification…
|
||||
Desired Optimal
|
||||
Word Spacing: Espacement des mots :
|
||||
@@ -7381,6 +7397,12 @@ axis Y Axis Axe Y
|
||||
Bus Lines Lignes de bus
|
||||
Terminal Nodes Nœuds terminaux
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows Flèches
|
||||
Solid Arrow Flèche pleine
|
||||
Open Arrow Flèche ouverte
|
||||
Chevron Arrow Flèche à chevron
|
||||
|
||||
Notched Ribbon Ruban cranté
|
||||
Double Line Double ligne
|
||||
Wave Vague
|
||||
@@ -8065,10 +8087,18 @@ breakText Glyphs Glyphes
|
||||
Smooth Bridge… Pont lissé…
|
||||
Smooth Bridge Pont lissé
|
||||
Keep Originals Conserver les originaux
|
||||
@msg select two circles to bridge sélectionnez deux cercles à relier
|
||||
@msg select two or more circles to bridge sélectionnez au moins deux cercles à relier
|
||||
@msg one circle is inside the other un cercle est à l’intérieur de l’autre
|
||||
@msg the circles are too far apart for this radius: raise the radius les cercles sont trop éloignés pour ce rayon : augmentez le rayon
|
||||
@msg the circles are too far apart for this radius les cercles sont trop éloignés pour ce rayon
|
||||
Constant Gap Écart constant
|
||||
Reach: Portée :
|
||||
@msg the circles are too far apart for this gap: raise the gap les cercles sont trop éloignés pour cet écart : augmentez l’écart
|
||||
@msg the circles are too far apart for this gap les cercles sont trop éloignés pour cet écart
|
||||
@msg no two circles are within reach: raise the reach aucun couple de cercles n’est à portée : augmentez la portée
|
||||
@msg select at most 2000 circles to bridge sélectionnez au plus 2000 cercles à relier
|
||||
@msg that makes too many bridges (at most 8000): lower the reach cela crée trop de ponts (au plus 8000) : réduisez la portée
|
||||
@msg the bridged circles are too complex to unite les cercles reliés sont trop complexes pour être réunis
|
||||
# Path Precision Tools add-on: Common Tangents.
|
||||
Common Tangents… Tangentes communes…
|
||||
Common Tangents Tangentes communes
|
||||
@@ -10361,6 +10391,16 @@ breakText Glyphs Glyphes
|
||||
No objects are selected. Aucun objet n’est sélectionné.
|
||||
Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage.
|
||||
Remove Fold Line Role Supprimer le type de ligne
|
||||
Tap Appui bref
|
||||
Clear Hold Effacer le maintien
|
||||
Hold Shortcuts Raccourcis de maintien
|
||||
Hold Shortcut Delay Délai des raccourcis de maintien
|
||||
How hold shortcuts work Fonctionnement des raccourcis de maintien
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. Cliquez, puis appuyez sur une touche à maintenir pour cet élément (Échap annule). Maintenir la touche exécute cet élément ; un appui bref exécute le raccourci propre à la touche.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. Un appui bref sur une touche exécute son raccourci. Maintenir la touche pendant le délai exécute à la place l’outil ou la commande de sa colonne Maintenir. Un raccourci de maintien est une touche de lettre, de chiffre ou de ponctuation, seule ou avec Maj.
|
||||
@msg Hold {_1} is already used by {_2} Le maintien de {_1} est déjà utilisé par {_2}
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) un raccourci de maintien est une touche qui saisit un caractère, seule ou avec Maj ({shown} comporte Cmd, Ctrl ou Alt)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} ne peut pas être un raccourci de maintien : utilisez une lettre, un chiffre ou une touche de ponctuation
|
||||
Check Vérifier
|
||||
Check Fold Lines Vérifier les lignes de pliage
|
||||
@msg No cut lines are in the selection. La sélection ne contient aucune ligne de découpe.
|
||||
@@ -10392,6 +10432,7 @@ 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
|
||||
Dashed Arrow Flèche en pointillés
|
||||
Pressure Sensitive Sensible à la pression
|
||||
Flex Ribbon Ruban souple
|
||||
Pulse Stroke Trait pulsé
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -502,6 +502,7 @@
|
||||
Can't save “{name}”. “{name}” સાચવી શકાતી નથી.
|
||||
Cancel રદ કરો
|
||||
Cancel Export નિકાસ રદ કરો
|
||||
Cancel Save સાચવવાનું રદ કરો
|
||||
Cancel Image Trace ઇમેજ ટ્રેસ રદ કરો
|
||||
Cancel Key Object કી ઑબ્જેક્ટ રદ કરો
|
||||
Cancel Opening ખોલવાનું રદ કરો
|
||||
@@ -735,6 +736,7 @@
|
||||
Constrain મર્યાદિત કરો
|
||||
Constrain Angle ખૂણો મર્યાદિત કરો
|
||||
Constrain Width and Height Proportions પહોળાઈ અને ઊંચાઈનો પ્રમાણ મર્યાદિત કરો
|
||||
Constant Gap સ્થિર ગેપ
|
||||
Copy Width to Height પહોળાઈને ઊંચાઈમાં નકલ કરો
|
||||
Construction Guides બાંધકામ ગાઇડ્સ
|
||||
Contextual Alternates સંદર્ભિત વૈકલ્પિક અક્ષરો
|
||||
@@ -1482,6 +1484,7 @@
|
||||
Fix Selected પસંદ કરેલું ઠીક કરો
|
||||
Flag… ફ્લેગ…
|
||||
Flare ફ્લેર
|
||||
Edit Flare ફ્લેર સંપાદિત કરો
|
||||
Flare Tool ફ્લેર ટૂલ
|
||||
Flare Tool Options ફ્લેર ટૂલ વિકલ્પો
|
||||
Flat Image ફ્લેટ છબી
|
||||
@@ -2117,6 +2120,8 @@
|
||||
Live preview લાઇવ પૂર્વાવલોકન
|
||||
Load Actions… ઍક્શન લોડ કરો…
|
||||
Replace Actions… ઍક્શન બદલો…
|
||||
Clear Actions ઍક્શન સાફ કરો
|
||||
Delete all action sets and their actions? બધા ઍક્શન સેટ અને તેમની ઍક્શન કાઢી નાખવી છે?
|
||||
Reset Actions ઍક્શન રીસેટ કરો
|
||||
Replace the current actions with the default set? વર્તમાન ઍક્શનને ડિફૉલ્ટ સેટથી બદલવા છે?
|
||||
Append adds the default set after the current sets instead. ઉમેરો તેના બદલે ડિફૉલ્ટ સેટને વર્તમાન સેટ પછી ઉમેરે છે.
|
||||
@@ -2350,6 +2355,9 @@
|
||||
Navigate નેવિગેટ કરો
|
||||
Navigator નેવિગેટર
|
||||
Navigator Panel Options નેવિગેટર પૅનલ વિકલ્પો
|
||||
Attributes Panel Options ગુણધર્મો પૅનલ વિકલ્પો
|
||||
Number of Recent URLs: તાજેતરના URLની સંખ્યા:
|
||||
@msg `count` must be a whole number from 1 to 30 `count` 1 થી 30 સુધીની પૂર્ણ સંખ્યા હોવી જોઈએ
|
||||
Needs Attention Only માત્ર ધ્યાન માગતા
|
||||
Needs a choice પસંદગી જરૂરી
|
||||
Needs a key કીની જરૂર છે
|
||||
@@ -2966,6 +2974,7 @@
|
||||
Rating: રેટિંગ:
|
||||
Ratio ગુણોત્તર
|
||||
Rays કિરણો
|
||||
Reach: પહોંચ:
|
||||
Read Action Set File ક્રિયા સેટ ફાઇલ વાંચો
|
||||
Read Shortcut Set File શોર્ટકટ સેટ ફાઇલ વાંચો
|
||||
Read files you open in its format and make documents from them તમે ખોલો તે ફાઇલોને તેના ફોર્મેટમાં વાંચો અને તેમાંથી દસ્તાવેજ બનાવો
|
||||
@@ -3240,6 +3249,8 @@
|
||||
The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl દબાવી રાખીને માઉસ વ્હીલ ફેરવવાથી કેનવાસ બાજુમાં સ્ક્રોલ થાય છે.
|
||||
Dragging sideways on a numeric field's label changes the field's value. સંખ્યાત્મક ફીલ્ડના લેબલ પર બાજુમાં ખેંચવાથી ફીલ્ડનું મૂલ્ય બદલાય છે.
|
||||
A two-finger rotate gesture on a trackpad rotates the canvas view. ટ્રેકપેડ પર બે આંગળીથી ફેરવવાનો હાવભાવ કેનવાસનું દૃશ્ય ફેરવે છે.
|
||||
Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. કી દબાવી રાખવાથી કીબોર્ડ શૉર્ટકટમાં તેની હોલ્ડ કૉલમનું ટૂલ અથવા કમાન્ડ ચાલે છે; ટૂંકું દબાણ તેનો સામાન્ય શોર્ટકટ ચલાવે છે.
|
||||
How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. કીનો હોલ્ડ શોર્ટકટ તેના સામાન્ય શોર્ટકટને બદલે ચાલે તે પહેલાં કીને કેટલી સેકન્ડ દબાવી રાખવી પડે.
|
||||
When you move anchor points, each curve with one moved end keeps its shape relative to its ends. જ્યારે તમે એન્કર પોઇન્ટ ખસેડો છો, ત્યારે એક ખસેલા છેડાવાળો દરેક વળાંક તેના છેડાઓની સાપેક્ષે પોતાનો આકાર જાળવે છે.
|
||||
Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ટૂલની શોર્ટકટ કી દબાવી રાખવાથી છોડો ત્યાં સુધી તે ટૂલ પસંદ રહે છે, પછી અગાઉનું ટૂલ ફરી પસંદ થાય છે.
|
||||
Shows the bounding box while you move the selection or draw a shape. તમે પસંદગી ખસેડો કે આકાર દોરો ત્યારે બાઉન્ડિંગ બોક્સ બતાવે છે.
|
||||
@@ -4623,6 +4634,7 @@ antiAlias Sharp શાર્પ
|
||||
Gurmukhi ગુરમુખી
|
||||
@plural Result: {n}|Results: {n} પરિણામ: {n}|પરિણામો: {n}
|
||||
@msg the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings દસ્તાવેજ એવી બ્લીડ સેટ કરે છે જે આ PDF/X ફાઇલ છોડી દે છે: "દસ્તાવેજની બ્લીડ સેટિંગ્સ વાપરો" ચાલુ કરો
|
||||
@msgplural {n} object reaches the trim edge but stops short of the bleed|{n} objects reach the trim edge but stop short of the bleed {n} ઑબ્જેક્ટ ટ્રિમ કિનારી સુધી પહોંચે છે પણ બ્લીડ પહેલાં અટકી જાય છે|{n} ઑબ્જેક્ટ ટ્રિમ કિનારી સુધી પહોંચે છે પણ બ્લીડ પહેલાં અટકી જાય છે
|
||||
@msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} સાચવ્યું, {n} નોંધ સાથે: {first}|{path} સાચવ્યું, {n} નોંધો સાથે: {first}
|
||||
@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {folder} માં {n} ફાઇલ ({note}) પેકેજ થઈ|{folder} માં {n} ફાઇલો ({note}) પેકેજ થઈ
|
||||
@msgplural Packaged {n} file {note}|Packaged {n} files {note} {n} ફાઇલ પેકેજ થઈ {note}|{n} ફાઇલો પેકેજ થઈ {note}
|
||||
@@ -4872,6 +4884,13 @@ antiAlias Sharp શાર્પ
|
||||
Bus Lines બસ રેખાઓ
|
||||
Terminal Nodes ટર્મિનલ નોડ્સ
|
||||
|
||||
# Original arrow art brushes.
|
||||
Arrows તીરો
|
||||
Solid Arrow ભરેલું તીર
|
||||
Open Arrow ખુલ્લું તીર
|
||||
Double Arrow બેવડું તીર
|
||||
Chevron Arrow શેવરોન તીર
|
||||
|
||||
Notched Ribbon ખાંચાવાળી રિબન
|
||||
Double Line બેવડી રેખા
|
||||
Wave તરંગ
|
||||
@@ -5341,7 +5360,6 @@ swatch [Registration] [રજિસ્ટ્રેશન]
|
||||
Gem રત્ન
|
||||
Hexagon ષટ્કોણ
|
||||
Key ચાવી
|
||||
Panel પેનલ
|
||||
Pin પિન
|
||||
Potion ઔષધ
|
||||
Rounded Square ગોળ ખૂણાવાળો ચોરસ
|
||||
@@ -5413,6 +5431,17 @@ swatch [Registration] [રજિસ્ટ્રેશન]
|
||||
Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર
|
||||
Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine"
|
||||
Tap ટૂંકું દબાણ
|
||||
Clear Hold હોલ્ડ સાફ કરો
|
||||
Hold Shortcuts હોલ્ડ શોર્ટકટ
|
||||
Hold Shortcut Delay હોલ્ડ શોર્ટકટ વિલંબ
|
||||
How hold shortcuts work હોલ્ડ શોર્ટકટ કેવી રીતે કામ કરે છે
|
||||
Click, then press a key to hold for this (Esc cancels). Holding the key runs this; a quick press runs the key's own shortcut. ક્લિક કરો, પછી આ માટે દબાવી રાખવાની કી દબાવો (Esc રદ કરે છે). કી દબાવી રાખવાથી આ ચાલે છે; ટૂંકું દબાણ કીનો પોતાનો શોર્ટકટ ચલાવે છે.
|
||||
A quick press of a key runs its shortcut. Holding the key for the delay runs the tool or command in its Hold column instead. A hold shortcut is a letter, digit or punctuation key, alone or with Shift. કીને ટૂંકું દબાવવાથી તેનો શોર્ટકટ ચાલે છે. વિલંબ જેટલો સમય કી દબાવી રાખવાથી તેના બદલે તેની હોલ્ડ કૉલમમાંનું ટૂલ અથવા આદેશ ચાલે છે. હોલ્ડ શોર્ટકટ એ અક્ષર, અંક અથવા વિરામચિહ્નની કી છે, એકલી અથવા Shift સાથે.
|
||||
@msg Hold {_1} is already used by {_2} હોલ્ડ {_1} પહેલેથી {_2} વાપરે છે
|
||||
@msg a hold shortcut is a key that types a character, alone or with Shift ({shown} has Cmd, Ctrl or Alt) હોલ્ડ શોર્ટકટ એ અક્ષર લખતી કી છે, એકલી અથવા Shift સાથે ({shown} માં Cmd, Ctrl અથવા Alt છે)
|
||||
@msg {shown} can't be a hold shortcut: use a letter, a digit or a punctuation key {shown} હોલ્ડ શોર્ટકટ ન હોઈ શકે: અક્ષર, અંક અથવા વિરામચિહ્નની કી વાપરો
|
||||
Dashed Arrow તૂટક તીર
|
||||
Pressure Sensitive દબાણ સંવેદનશીલ
|
||||
Flex Ribbon લવચીક પટ્ટી
|
||||
Pulse Stroke ધબકતો ઘસારો
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user