mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-22 18:34:42 +01:00
Merge storytold/main (d38e414b77) into fix-8711-layers-target-ring
# Conflicts: # docs/roadmap.md # docs/target-app-parity.md # docs/ui-parity.md
This commit is contained in:
commit
c5a6971dfb
144 files changed
+9808
-952
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=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
@@ -6741,6 +6750,7 @@ dependencies = [
|
||||
name = "vectorcraft-color"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-cms",
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
"proptest",
|
||||
|
||||
@@ -11,6 +11,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
|
||||
|
||||
@@ -146,7 +146,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates 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 }
|
||||
|
||||
+96
-455
@@ -6,6 +6,8 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub use craft_cms::palette::css_property;
|
||||
use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteError, PaletteGroup, PaletteSwatch};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary};
|
||||
@@ -83,18 +85,93 @@ struct NativeFile {
|
||||
|
||||
const NATIVE_FORMAT: &str = "vcswatches";
|
||||
const GPL_HEADER: &str = "GIMP Palette";
|
||||
const GPL_GROUP: &str = "# Group:";
|
||||
const ASE_SIGNATURE: &[u8] = b"ASEF";
|
||||
const ASE_GROUP_START: u16 = 0xC001;
|
||||
const ASE_GROUP_END: u16 = 0xC002;
|
||||
const ASE_COLOR: u16 = 0x0001;
|
||||
/// The most colors and groups read from one `.ase` file.
|
||||
const ASE_MAX_ENTRIES: usize = 100_000;
|
||||
/// The most UTF-16 code units of a name that are kept.
|
||||
const ASE_MAX_NAME: usize = 1024;
|
||||
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
|
||||
const ACB_SIGNATURE: &[u8] = b"8BCB";
|
||||
const ACB_CUT_SHORT: &str = "the color book is cut short";
|
||||
#[cfg(test)]
|
||||
const ASE_GROUP_START: u16 = 0xC001;
|
||||
#[cfg(test)]
|
||||
const ASE_MAX_ENTRIES: usize = 100_000;
|
||||
|
||||
fn color_to_cms(c: Color) -> PaletteColor {
|
||||
match c {
|
||||
Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b },
|
||||
Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k },
|
||||
Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b },
|
||||
Color::Gray { k } => PaletteColor::Gray { k },
|
||||
}
|
||||
}
|
||||
|
||||
fn color_from_cms(c: PaletteColor) -> Color {
|
||||
match c {
|
||||
PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b),
|
||||
PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k),
|
||||
PaletteColor::Lab { l, a, b } => Color::lab(l, a, b),
|
||||
PaletteColor::Gray { k } => Color::gray(k),
|
||||
}
|
||||
}
|
||||
|
||||
// GPL must retain the app-managed display conversion; ASE preserves authoring models.
|
||||
fn swatches_to_cms(list: &[Swatch], rgb_only: bool) -> Vec<PaletteSwatch> {
|
||||
list.iter()
|
||||
.filter_map(|w| {
|
||||
w.paint.color().map(|c| PaletteSwatch {
|
||||
name: w.name.clone(),
|
||||
color: if rgb_only {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
PaletteColor::rgb8(r, g, b)
|
||||
} else {
|
||||
color_to_cms(c)
|
||||
},
|
||||
global: w.global,
|
||||
spot: w.spot,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn swatches_from_cms(list: Vec<PaletteSwatch>) -> Vec<Swatch> {
|
||||
list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect()
|
||||
}
|
||||
|
||||
fn to_cms_palette(lib: &SwatchLibrary, rgb_only: bool) -> Palette {
|
||||
Palette {
|
||||
name: lib.name.clone(),
|
||||
swatches: swatches_to_cms(&lib.swatches, rgb_only),
|
||||
groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches, rgb_only) }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_cms_palette(p: Palette) -> SwatchLibrary {
|
||||
SwatchLibrary {
|
||||
name: p.name,
|
||||
swatches: swatches_from_cms(p.swatches),
|
||||
groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps structured shared palette errors to VectorCraft's translatable messages.
|
||||
fn palette_error(err: PaletteError) -> String {
|
||||
match err {
|
||||
PaletteError::UnsupportedFormat => "not a supported palette (.gpl, .ase, or .acb)".into(),
|
||||
PaletteError::TruncatedAse => "the swatch exchange file is cut short".into(),
|
||||
PaletteError::TruncatedAcb => "the color book is cut short".into(),
|
||||
PaletteError::AseWriteEntryLimit { limit, entries } => format!(
|
||||
"VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}",
|
||||
ASE_MAX_ENTRIES = limit
|
||||
),
|
||||
PaletteError::AseReadEntryLimit { limit } => {
|
||||
format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups", ASE_MAX_ENTRIES = limit)
|
||||
}
|
||||
PaletteError::AseBlockCount => "too many swatch exchange blocks".into(),
|
||||
PaletteError::AseBlockLength => "a swatch exchange block is too long".into(),
|
||||
PaletteError::AseNameLength => "a swatch exchange name is too long".into(),
|
||||
PaletteError::AseVersion { major, minor } => format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"),
|
||||
PaletteError::AcbVersion { version } => format!("color book version {version} isn't supported (only 1)"),
|
||||
PaletteError::AcbEntryLimit { limit } => format!("the color book holds more than {ASE_MAX_ENTRIES} colors", ASE_MAX_ENTRIES = limit),
|
||||
PaletteError::AcbColorSpace { space: other } => format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)"),
|
||||
PaletteError::AcbNameBytes { limit } => format!("the color book's names take more than {} MB", limit >> 20),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document)
|
||||
/// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid
|
||||
@@ -113,8 +190,12 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result<Vec<u8>, Stri
|
||||
let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library };
|
||||
serde_json::to_string_pretty(&file).unwrap_or_default()
|
||||
}
|
||||
PaletteFormat::Gpl => write_gpl(lib),
|
||||
PaletteFormat::Ase => return write_ase(lib),
|
||||
PaletteFormat::Gpl => {
|
||||
return cms_palette::write_palette_typed(&to_cms_palette(lib, true), cms_palette::PaletteFormat::Gpl).map_err(palette_error);
|
||||
}
|
||||
PaletteFormat::Ase => {
|
||||
return cms_palette::write_palette_typed(&to_cms_palette(lib, false), cms_palette::PaletteFormat::Ase).map_err(palette_error);
|
||||
}
|
||||
PaletteFormat::Css => write_css(lib, keep),
|
||||
};
|
||||
Ok(text.into_bytes())
|
||||
@@ -125,49 +206,6 @@ fn one_line(s: &str) -> String {
|
||||
s.split(['\n', '\r', '\t']).collect::<Vec<_>>().join(" ").trim().to_string()
|
||||
}
|
||||
|
||||
fn write_gpl(lib: &SwatchLibrary) -> String {
|
||||
let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name));
|
||||
let colors = |out: &mut String, list: &[Swatch]| {
|
||||
for w in list {
|
||||
if let Some(c) = w.paint.color() {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name)));
|
||||
}
|
||||
}
|
||||
};
|
||||
colors(&mut out, &lib.swatches);
|
||||
for g in &lib.groups {
|
||||
out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name)));
|
||||
colors(&mut out, &g.swatches);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as
|
||||
/// hyphens, other characters an identifier can't hold escaped with a backslash.
|
||||
pub fn css_property(name: &str) -> String {
|
||||
let mut out = String::from("--");
|
||||
for word in name.split_whitespace() {
|
||||
if out.len() > 2 {
|
||||
out.push('-');
|
||||
}
|
||||
for ch in word.chars().flat_map(char::to_lowercase) {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() {
|
||||
out.push(ch);
|
||||
} else if ch.is_ascii_graphic() {
|
||||
out.push('\\');
|
||||
out.push(ch);
|
||||
} else {
|
||||
out.push_str(&format!("\\{:x} ", ch as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.len() == 2 {
|
||||
out.push_str("swatch");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity).
|
||||
fn css_color(c: &Color, opacity: f32) -> String {
|
||||
let [r, g, b, a] = c.to_rgba8(opacity);
|
||||
@@ -265,108 +303,12 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// `.ase`, as [`read_ase`] reads it: version 1.0, the ungrouped colors, then each color group as a
|
||||
/// group start (its name), its colors and a group end, also for a group without colors. A color is
|
||||
/// written in its own model: RGB, CMYK and gray components from 0 to 1 (gray as a level, 1 is
|
||||
/// white), Lab lightness as a fraction of 100 and a and b from −128 to 127. Components are clamped
|
||||
/// to those ranges, and a component that isn't a finite number is written as 0. The color type is
|
||||
/// 1 for a spot color, 0 for another global color and 2 for a process color.
|
||||
///
|
||||
/// A swatch exchange file holds solid colors only: gradients, patterns and None are left out, and
|
||||
/// a tint swatch is written as the color it shows, a process color without its link to its base.
|
||||
/// The file has no library name ([`read_ase`] names a library after its file). More than
|
||||
/// [`ASE_MAX_ENTRIES`] colors and groups is an error.
|
||||
fn write_ase(lib: &SwatchLibrary) -> Result<Vec<u8>, String> {
|
||||
let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count();
|
||||
let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::<usize>();
|
||||
if entries > ASE_MAX_ENTRIES {
|
||||
return Err(format!(
|
||||
"VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}"
|
||||
));
|
||||
}
|
||||
let mut body = vec![];
|
||||
let mut blocks = put_ase_colors(&mut body, &lib.swatches)?;
|
||||
for g in &lib.groups {
|
||||
let mut name = vec![];
|
||||
put_ase_name(&mut name, &g.name)?;
|
||||
put_ase_block(&mut body, ASE_GROUP_START, &name)?;
|
||||
blocks += 2 + put_ase_colors(&mut body, &g.swatches)?;
|
||||
put_ase_block(&mut body, ASE_GROUP_END, &[])?;
|
||||
}
|
||||
let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?;
|
||||
let mut out = ASE_SIGNATURE.to_vec();
|
||||
out.extend(1u16.to_be_bytes());
|
||||
out.extend(0u16.to_be_bytes());
|
||||
out.extend(blocks.to_be_bytes());
|
||||
out.extend(body);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The color blocks of the solid colors in `list` → how many were written.
|
||||
fn put_ase_colors(out: &mut Vec<u8>, list: &[Swatch]) -> Result<usize, String> {
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 };
|
||||
let mut n = 0;
|
||||
for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) {
|
||||
let mut body = vec![];
|
||||
put_ase_name(&mut body, &w.name)?;
|
||||
let (model, values): (&[u8; 4], Vec<f32>) = match color {
|
||||
Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]),
|
||||
Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]),
|
||||
Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]),
|
||||
Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]),
|
||||
};
|
||||
body.extend(model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
let kind: u16 = if w.spot {
|
||||
1
|
||||
} else if w.global {
|
||||
0
|
||||
} else {
|
||||
2
|
||||
};
|
||||
body.extend(kind.to_be_bytes());
|
||||
put_ase_block(out, ASE_COLOR, &body)?;
|
||||
n += 1;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// A block: its type, the length of its body and the body.
|
||||
fn put_ase_block(out: &mut Vec<u8>, kind: u16, body: &[u8]) -> Result<(), String> {
|
||||
let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?;
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend(len.to_be_bytes());
|
||||
out.extend_from_slice(body);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included,
|
||||
/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units
|
||||
/// is cut before the character that would pass that limit.
|
||||
fn put_ase_name(out: &mut Vec<u8>, name: &str) -> Result<(), String> {
|
||||
let mut units: Vec<u16> = vec![];
|
||||
for c in name.chars().filter(|&c| c != '\0') {
|
||||
let mut buf = [0; 2];
|
||||
let encoded = c.encode_utf16(&mut buf);
|
||||
if units.len() + encoded.len() > ASE_MAX_NAME {
|
||||
break;
|
||||
}
|
||||
units.extend_from_slice(encoded);
|
||||
}
|
||||
units.push(0);
|
||||
let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?;
|
||||
out.extend(count.to_be_bytes());
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the
|
||||
/// file doesn't.
|
||||
pub fn read(text: &str, name: &str) -> Result<SwatchLibrary, String> {
|
||||
let text = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if text.starts_with(GPL_HEADER) {
|
||||
return Ok(read_gpl(text, name));
|
||||
return cms_palette::read_palette_typed(text.as_bytes(), name).map(from_cms_palette).map_err(palette_error);
|
||||
}
|
||||
if text.starts_with('{') {
|
||||
let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?;
|
||||
@@ -391,11 +333,8 @@ pub fn sniff(text: &str) -> bool {
|
||||
/// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or
|
||||
/// `.gpl` library ([`read`]). `name` names it when the file doesn't.
|
||||
pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
|
||||
if bytes.starts_with(ASE_SIGNATURE) {
|
||||
return read_ase(bytes, name);
|
||||
}
|
||||
if bytes.starts_with(ACB_SIGNATURE) {
|
||||
return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e });
|
||||
if bytes.starts_with(ASE_SIGNATURE) || bytes.starts_with(ACB_SIGNATURE) {
|
||||
return cms_palette::read_palette_typed(bytes, name).map(from_cms_palette).map_err(palette_error);
|
||||
}
|
||||
read(&String::from_utf8_lossy(bytes), name)
|
||||
}
|
||||
@@ -409,303 +348,5 @@ pub fn sniff_bytes(bytes: &[u8]) -> bool {
|
||||
|| sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)))
|
||||
}
|
||||
|
||||
/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and
|
||||
/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are
|
||||
/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets
|
||||
/// a number ([`UniqueNames`]).
|
||||
fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
|
||||
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
for line in text.lines().skip(1) {
|
||||
let line = line.trim();
|
||||
if let Some(g) = line.strip_prefix(GPL_GROUP) {
|
||||
lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] });
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = line.strip_prefix("Name:") {
|
||||
if !n.trim().is_empty() {
|
||||
lib.name = n.trim().to_string();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped.
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
let rgb: Vec<u8> = words.iter().take(3).map_while(|v| v.parse().ok()).collect();
|
||||
let [r, g, b] = rgb[..] else { continue };
|
||||
let rest = words[3..].join(" ");
|
||||
let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest };
|
||||
let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
|
||||
match lib.groups.last_mut() {
|
||||
Some(grp) => grp.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
}
|
||||
}
|
||||
lib
|
||||
}
|
||||
|
||||
/// `.ase`, from public descriptions of the format: the layout from
|
||||
/// <https://www.selapa.net/swatches/colors/fileformats.php>, the component ranges from
|
||||
/// <https://github.com/nsfmc/swatch>. After the signature come, big-endian, a `u16` major (1) and
|
||||
/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and
|
||||
/// the body. A group start's body is a name. A color's body is a name, a four-character model
|
||||
/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16`
|
||||
/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a
|
||||
/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness
|
||||
/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero
|
||||
/// included, then the units.
|
||||
///
|
||||
/// Color groups become groups: a group start inside an open group ends that group, and a group
|
||||
/// left open ends with the file. Blocks of other types and colors in other models are skipped.
|
||||
/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or
|
||||
/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than
|
||||
/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error.
|
||||
fn read_ase(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
|
||||
let mut data = AseData(bytes);
|
||||
data.bytes(ASE_SIGNATURE.len())?;
|
||||
let (major, minor) = (data.u16()?, data.u16()?);
|
||||
if major != 1 {
|
||||
return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"));
|
||||
}
|
||||
let blocks = data.u32()?;
|
||||
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
let (mut in_group, mut entries) = (false, 0usize);
|
||||
for _ in 0..blocks {
|
||||
let kind = data.u16()?;
|
||||
let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX);
|
||||
let mut body = AseData(data.bytes(len)?);
|
||||
if matches!(kind, ASE_GROUP_START | ASE_COLOR) {
|
||||
entries += 1;
|
||||
if entries > ASE_MAX_ENTRIES {
|
||||
return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups"));
|
||||
}
|
||||
}
|
||||
match kind {
|
||||
ASE_GROUP_START => {
|
||||
lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] });
|
||||
in_group = true;
|
||||
}
|
||||
ASE_GROUP_END => in_group = false,
|
||||
ASE_COLOR => {
|
||||
let Some(mut w) = ase_swatch(&mut body)? else { continue };
|
||||
w.name = names.unique(std::mem::take(&mut w.name));
|
||||
match lib.groups.last_mut().filter(|_| in_group) {
|
||||
Some(g) => g.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
}
|
||||
}
|
||||
// Other blocks are skipped.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(lib)
|
||||
}
|
||||
|
||||
/// `.acb` (a color book, read only), from public descriptions of the format: after the signature
|
||||
/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description
|
||||
/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0
|
||||
/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its
|
||||
/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab
|
||||
/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of
|
||||
/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand
|
||||
/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot
|
||||
/// or process colors (a book without it is a spot color book).
|
||||
///
|
||||
/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a
|
||||
/// name (the padding of a book's pages) are left out. A version other than 1, a color space other
|
||||
/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error.
|
||||
fn read_acb(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
|
||||
let mut data = AseData(bytes);
|
||||
data.bytes(ACB_SIGNATURE.len())?;
|
||||
let version = data.u16()?;
|
||||
if version != 1 {
|
||||
return Err(format!("color book version {version} isn't supported (only 1)"));
|
||||
}
|
||||
let _book_id = data.u16()?;
|
||||
let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?];
|
||||
let count = usize::from(data.u16()?);
|
||||
if count > ASE_MAX_ENTRIES {
|
||||
return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors"));
|
||||
}
|
||||
let (_page_size, _page_offset) = (data.u16()?, data.u16()?);
|
||||
let space = data.u16()?;
|
||||
let mut colors = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let name = data.acb_string()?;
|
||||
let _code = data.bytes(6)?;
|
||||
let color = match space {
|
||||
0 => {
|
||||
let [r, g, b] = data.array::<3>()?;
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
2 => {
|
||||
let ink = |v: u8| f32::from(255 - v) / 255.0;
|
||||
let [c, m, y, k] = data.array::<4>()?;
|
||||
Color::cmyk(ink(c), ink(m), ink(y), ink(k))
|
||||
}
|
||||
7 => {
|
||||
let [l, a, b] = data.array::<3>()?;
|
||||
Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0)
|
||||
}
|
||||
other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")),
|
||||
};
|
||||
colors.push((name, color));
|
||||
}
|
||||
// Spot colors unless the book says process ones.
|
||||
let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice());
|
||||
let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
// Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of
|
||||
// names taken): a megabyte book of long affixes and many colors came to hundreds of MB.
|
||||
let mut kept = 0usize;
|
||||
for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) {
|
||||
kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len()));
|
||||
if kept > ACB_MAX_NAME_BYTES {
|
||||
return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20));
|
||||
}
|
||||
let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string());
|
||||
lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot });
|
||||
}
|
||||
Ok(lib)
|
||||
}
|
||||
|
||||
/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted
|
||||
/// twice as they are kept twice.
|
||||
const ACB_MAX_NAME_BYTES: usize = 64 << 20;
|
||||
|
||||
/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray.
|
||||
/// Components are clamped to their ranges.
|
||||
fn ase_swatch(body: &mut AseData) -> Result<Option<Swatch>, String> {
|
||||
let name = body.name()?;
|
||||
let unit = |v: f32| v.clamp(0.0, 1.0);
|
||||
let color = match &body.array::<4>()? {
|
||||
b"RGB " => {
|
||||
let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
Color::rgb(unit(r), unit(g), unit(b))
|
||||
}
|
||||
b"CMYK" => {
|
||||
let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?];
|
||||
Color::cmyk(unit(c), unit(m), unit(y), unit(k))
|
||||
}
|
||||
// Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a
|
||||
// value above 1.
|
||||
b"LAB " => {
|
||||
let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 };
|
||||
Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0))
|
||||
}
|
||||
// A gray level (1 is white); a gray color holds its ink.
|
||||
b"Gray" => Color::gray(1.0 - unit(body.f32()?)),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
// Some writers leave the color type out, which makes a process color.
|
||||
let kind = if body.0.len() >= 2 { body.u16()? } else { 2 };
|
||||
// Spot colors are global.
|
||||
let (global, spot) = match kind {
|
||||
0 => (true, false),
|
||||
1 => (true, true),
|
||||
_ => (false, false),
|
||||
};
|
||||
let name = if name.is_empty() { value_name(color) } else { name };
|
||||
Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot }))
|
||||
}
|
||||
|
||||
/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0",
|
||||
/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30").
|
||||
fn value_name(c: Color) -> String {
|
||||
let pct = |v: f32| (v * 100.0).round();
|
||||
let byte = |v: f32| (v * 255.0).round();
|
||||
match c {
|
||||
Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
|
||||
Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
|
||||
Color::Gray { k } => format!("Gray K={}", pct(k)),
|
||||
// `+ 0.0` turns a rounded -0 into 0.
|
||||
Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// `.ase` data, read field by field; reading past its end is an error.
|
||||
struct AseData<'a>(&'a [u8]);
|
||||
|
||||
impl<'a> AseData<'a> {
|
||||
fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(head)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
let (head, rest) = self.0.split_first_chunk::<N>().ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(*head)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, String> {
|
||||
self.array().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
self.array().map(u32::from_be_bytes)
|
||||
}
|
||||
/// A component; one that isn't a finite number reads as 0.
|
||||
fn f32(&mut self) -> Result<f32, String> {
|
||||
let v = f32::from_be_bytes(self.array()?);
|
||||
Ok(if v.is_finite() { v } else { 0.0 })
|
||||
}
|
||||
/// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units,
|
||||
/// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units
|
||||
/// are kept.
|
||||
fn acb_string(&mut self) -> Result<String, String> {
|
||||
let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX);
|
||||
let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>();
|
||||
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
|
||||
let s = String::from_utf16_lossy(&units);
|
||||
let s = match s.strip_prefix("$$$/") {
|
||||
Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(),
|
||||
None => s,
|
||||
};
|
||||
Ok(s.replace("^R", "®").replace("^C", "©"))
|
||||
}
|
||||
/// A name up to its terminating zero, trimmed. A block that ends before it has no name.
|
||||
fn name(&mut self) -> Result<String, String> {
|
||||
if self.0.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let n = usize::from(self.u16()?);
|
||||
let (units, _) = self.bytes(n * 2)?.as_chunks::<2>();
|
||||
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
|
||||
Ok(String::from_utf16_lossy(&units).trim().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's name as a file gives it, trimmed; "Color Group" when it has none.
|
||||
fn group_name(name: &str) -> String {
|
||||
let name = name.trim();
|
||||
if name.is_empty() { "Color Group".into() } else { name.to_string() }
|
||||
}
|
||||
|
||||
/// The swatch and group names a reader has handed out. Swatches and color groups share one set of
|
||||
/// names, as in a document, and a name already taken gets the first free number ("Black 2").
|
||||
#[derive(Default)]
|
||||
struct UniqueNames {
|
||||
taken: HashSet<String>,
|
||||
/// The last number tried for each repeated name.
|
||||
last: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl UniqueNames {
|
||||
fn unique(&mut self, base: String) -> String {
|
||||
if self.taken.insert(base.clone()) {
|
||||
return base;
|
||||
}
|
||||
// Each pass tries the next number, and only finitely many names are taken.
|
||||
let n = self.last.entry(base.clone()).or_insert(1);
|
||||
loop {
|
||||
*n += 1;
|
||||
let name = format!("{base} {n}");
|
||||
if self.taken.insert(name.clone()) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -2,6 +2,9 @@ use super::*;
|
||||
use crate::{Gradient, GradientPaint, GradientStop};
|
||||
use proptest::prelude::*;
|
||||
|
||||
const ASE_COLOR: u16 = 0x0001;
|
||||
const ASE_GROUP_END: u16 = 0xC002;
|
||||
|
||||
#[test]
|
||||
fn gpl_blank_name_keeps_fallback() {
|
||||
let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n";
|
||||
@@ -700,3 +703,52 @@ proptest! {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_gpl_adapter_uses_app_color_conversion() {
|
||||
let colors = [Color::cmyk(0.2, 0.4, 0.6, 0.1), Color::lab(55.0, 30.0, -25.0), Color::gray(0.3)];
|
||||
let lib = SwatchLibrary {
|
||||
name: "Managed".into(),
|
||||
swatches: colors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &color)| Swatch { name: format!("Color {i}"), paint: Paint::solid(color), global: false, spot: false })
|
||||
.collect(),
|
||||
groups: vec![],
|
||||
};
|
||||
let mut expected = String::from("GIMP Palette\nName: Managed\nColumns: 0\n#\n");
|
||||
for (i, color) in colors.iter().enumerate() {
|
||||
let [r, g, b, _] = color.to_rgba8(1.0);
|
||||
expected.push_str(&format!("{r:3} {g:3} {b:3}\tColor {i}\n"));
|
||||
}
|
||||
assert_eq!(write(&lib, PaletteFormat::Gpl).unwrap(), expected.as_bytes());
|
||||
assert!(to_cms_palette(&lib, true).swatches.iter().all(|w| matches!(w.color, PaletteColor::Rgb { .. })));
|
||||
assert!(matches!(to_cms_palette(&lib, false).swatches[0].color, PaletteColor::Cmyk { .. }));
|
||||
assert!(matches!(to_cms_palette(&lib, false).swatches[1].color, PaletteColor::Lab { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_palette_errors_keep_app_wording() {
|
||||
let cases = [
|
||||
(PaletteError::UnsupportedFormat, "not a supported palette (.gpl, .ase, or .acb)"),
|
||||
(PaletteError::TruncatedAse, "the swatch exchange file is cut short"),
|
||||
(PaletteError::TruncatedAcb, "the color book is cut short"),
|
||||
(
|
||||
PaletteError::AseWriteEntryLimit { limit: 3, entries: 4 },
|
||||
"VectorCraft reads at most 3 colors and groups from a swatch exchange file, and this library has 4",
|
||||
),
|
||||
(PaletteError::AseReadEntryLimit { limit: 3 }, "the swatch exchange file holds more than 3 colors and groups"),
|
||||
(PaletteError::AseBlockCount, "too many swatch exchange blocks"),
|
||||
(PaletteError::AseBlockLength, "a swatch exchange block is too long"),
|
||||
(PaletteError::AseNameLength, "a swatch exchange name is too long"),
|
||||
(PaletteError::AseVersion { major: 2, minor: 3 }, "swatch exchange version 2.3 isn't supported (only 1.x)"),
|
||||
(PaletteError::AcbVersion { version: 2 }, "color book version 2 isn't supported (only 1)"),
|
||||
(PaletteError::AcbEntryLimit { limit: 3 }, "the color book holds more than 3 colors"),
|
||||
(PaletteError::AcbColorSpace { space: 5 }, "color books in color space 5 aren't supported (only RGB, CMYK and Lab)"),
|
||||
(PaletteError::AcbNameBytes { limit: 64 << 20 }, "the color book's names take more than 64 MB"),
|
||||
];
|
||||
for (error, expected) in cases {
|
||||
assert_eq!(palette_error(error), expected);
|
||||
}
|
||||
assert_eq!(read_bytes(b"8BCB\0\x01\0\0\0\0\0\x03\0x", "fallback").unwrap_err(), "the color book is cut short");
|
||||
}
|
||||
@@ -38,7 +38,7 @@ pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList,
|
||||
TabAlign, TabStop,
|
||||
};
|
||||
pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work};
|
||||
pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
|
||||
@@ -669,6 +669,34 @@ fn area_type() -> TextObject {
|
||||
t
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrap_object_below_every_area_type_object_makes_no_outline() {
|
||||
use crate::{Appearance, Document, Node, NodeKind};
|
||||
let mut d = Document::new(300.0, 300.0);
|
||||
let l = d.layers[0].id;
|
||||
let wrap = |d: &mut Document, r: Rect| {
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::path(id, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art());
|
||||
n.extras_mut().wrap = Some(TextWrap::default());
|
||||
n
|
||||
};
|
||||
// Bottom to top: a wrap object, the area type, then a wrap object.
|
||||
let below = wrap(&mut d, Rect::new(0.0, 0.0, 250.0, 250.0));
|
||||
d.insert(Some(l), 9, below).unwrap();
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(area_type())))).unwrap();
|
||||
let above = wrap(&mut d, Rect::new(60.0, 40.0, 80.0, 60.0));
|
||||
d.insert(Some(l), 9, above).unwrap();
|
||||
wrap::OUTLINES_MADE.with(|c| c.set(0));
|
||||
let mut sources = 0;
|
||||
wrap_sources(&d, |_, objects, shapes| {
|
||||
sources += 1;
|
||||
assert_eq!((objects.len(), shapes.len()), (1, 1));
|
||||
});
|
||||
assert_eq!(sources, 1);
|
||||
assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_resizes_its_frame_and_keeps_its_type() {
|
||||
let mut t = area_type();
|
||||
|
||||
@@ -7,6 +7,12 @@ use vectorcraft_geom::{PathData, shapes};
|
||||
use super::{TextKind, TextObject, WrapShape};
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many wrap outlines [`each_text`] has made on this thread (for tests).
|
||||
pub(super) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
|
||||
fn outline(n: &Node, out: &mut PathData) {
|
||||
match &n.kind {
|
||||
@@ -66,10 +72,45 @@ fn collect<'a>(n: &'a Node, out: &mut Vec<Item<'a>>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors and subpaths [`outline`] would collect for wrap object `n`, counted without copying
|
||||
/// them.
|
||||
fn outline_size(n: &Node) -> (usize, usize) {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, .. } => path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter(|sp| sp.closed || sp.anchors.len() > 2)
|
||||
.fold((0usize, 0usize), |(a, s), sp| (a.saturating_add(sp.anchors.len()), s.saturating_add(1))),
|
||||
NodeKind::Compound { children, .. } | NodeKind::Group { children, clip: false } => children
|
||||
.iter()
|
||||
.filter(|c| c.visible)
|
||||
.map(|c| outline_size(c))
|
||||
.fold((0, 0), |(a, s), (ca, cs)| (a.saturating_add(ca), s.saturating_add(cs))),
|
||||
NodeKind::Group { children, clip: true } => children.first().map_or((0, 0), |c| outline_size(c)),
|
||||
// A rectangle of the object's bounds.
|
||||
_ => {
|
||||
if n.geometric_bounds().is_some() {
|
||||
(4, 1)
|
||||
} else {
|
||||
(0, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How much [`resolve_wrap`] would copy into the wrap shapes of every area text object in `doc`:
|
||||
/// each wrap object's outline (its anchors, plus one for the shape) once for each area text object
|
||||
/// below it in its layer.
|
||||
pub fn wrap_work(doc: &Document) -> usize {
|
||||
work(doc, false)
|
||||
}
|
||||
|
||||
/// [`wrap_work`], with one more for each subpath of each outline, empty ones included.
|
||||
pub fn wrap_copy_units(doc: &Document) -> usize {
|
||||
work(doc, true)
|
||||
}
|
||||
|
||||
fn work(doc: &Document, count_subpaths: bool) -> usize {
|
||||
let mut total = 0usize;
|
||||
for layer in &doc.layers {
|
||||
let mut items = vec![];
|
||||
@@ -78,11 +119,10 @@ pub fn wrap_work(doc: &Document) -> usize {
|
||||
for it in items.iter().rev() {
|
||||
match it {
|
||||
Item::Wrap(n) => {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
let anchors: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum();
|
||||
above = above.saturating_add(anchors.saturating_add(1));
|
||||
let (anchors, subpaths) = outline_size(n);
|
||||
if anchors > 0 {
|
||||
let subpaths = if count_subpaths { subpaths } else { 0 };
|
||||
above = above.saturating_add(anchors).saturating_add(subpaths).saturating_add(1);
|
||||
}
|
||||
}
|
||||
Item::Text(_) => total = total.saturating_add(above),
|
||||
@@ -99,9 +139,15 @@ fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapS
|
||||
let mut items = vec![];
|
||||
collect(layer, &mut items);
|
||||
let mut above: Vec<(&Node, WrapShape)> = vec![];
|
||||
for it in items.iter().rev() {
|
||||
// A wrap object below every area text object of the layer wraps none of them: its outline is
|
||||
// not made.
|
||||
let first_text = items.iter().position(|it| matches!(it, Item::Text(_)));
|
||||
for (i, it) in items.iter().enumerate().rev() {
|
||||
match it {
|
||||
Item::Wrap(_) if first_text.is_none_or(|t| i < t) => {}
|
||||
Item::Wrap(n) => {
|
||||
#[cfg(test)]
|
||||
OUTLINES_MADE.with(|c| c.set(c.get() + 1));
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
|
||||
@@ -911,6 +911,10 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry};
|
||||
/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets.
|
||||
pub use buildcmds::{TracePreset, TracePresetChange};
|
||||
|
||||
/// The `format`, extensions and largest size of the tracing presets files
|
||||
/// `imageTrace.presets.export` writes and `imageTrace.presets.import` reads.
|
||||
pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES};
|
||||
|
||||
/// An Image Trace made off the UI thread, and what it traced (#3098).
|
||||
pub use buildcmds::{TraceRun, Traced, image_trace_target};
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::appearance::SharedStack;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_tools::builder::{edges, faces, is_live_paint};
|
||||
|
||||
use super::edit::{outermost, roots_of, selected_roots};
|
||||
use super::opacitymask::percent;
|
||||
@@ -48,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). In the contents of a Live Paint group the fill goes on its faces only, and its hidden source paths, like every contents edit, are left as they are. With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -57,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. In the contents of a Live Paint group the stroke goes on its edges only, and its hidden source paths are left as they are. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -129,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; a whole Live Paint group (selected, in ids, or `source` with `reverse`) takes the fill attributes on its faces and the stroke attributes on its edges (a whole-appearance pick: every fill row on each face and every stroke row on each edge, which keep their rows of the other kind and their effects; `append` adds the source's rows but not its object effects to them), and its hidden source paths keep their paint; a whole Live Paint group picked up (`source`, or selected first with `reverse`) gives its first face's fills with its first edge's strokes above them and the group's own opacity, blend mode and effects; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -280,7 +281,8 @@ impl ItemTarget {
|
||||
|
||||
/// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
|
||||
/// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
|
||||
/// ([`super::paint::live_paint_parts_skipped`]).
|
||||
/// ([`super::paint::live_paint_parts_skipped`]); an item edit with `target: "contents"` leaves out
|
||||
/// the parts of the other kind the same way ([`contents_skipped`]).
|
||||
pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result<Vec<NodeId>> {
|
||||
Ok(self.targets_and_skipped(s, p, fill)?.0)
|
||||
}
|
||||
@@ -290,13 +292,16 @@ impl ItemTarget {
|
||||
/// to new art.
|
||||
pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec<NodeId>, bool)> {
|
||||
let mut ids = self.targets(s, p)?;
|
||||
let mut skipped_any = false;
|
||||
if self == ItemTarget::Top {
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
|
||||
let before = ids.len();
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
skipped_any = ids.len() != before;
|
||||
}
|
||||
// An item edit of the contents of a Live Paint group goes to its parts of the edited kind too.
|
||||
let skipped = if self == ItemTarget::Top {
|
||||
super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill)
|
||||
} else {
|
||||
contents_skipped(s, p, fill)?
|
||||
};
|
||||
let before = ids.len();
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
// A contents edit already leaves hidden source paths out of `ids`, so `skipped` is checked on its own too.
|
||||
let skipped_any = ids.len() != before || !skipped.is_empty();
|
||||
Ok((ids, skipped_any))
|
||||
}
|
||||
|
||||
@@ -491,15 +496,37 @@ pub(crate) fn subject_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
|
||||
/// Objects whose own appearance stack a command edits: `ids`/`id` (layers too; an id inside
|
||||
/// another given one is dropped), else the [`subject_roots`]; with `target: "contents"` the painted
|
||||
/// objects inside the groups and layers among them ([`leaf_targets`]).
|
||||
/// objects inside the groups and layers among them ([`leaf_targets`]), without the hidden source paths
|
||||
/// of Live Paint groups.
|
||||
pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let roots = if p.get("ids").is_none() && p.get("id").is_none() {
|
||||
subject_roots(s)?
|
||||
let roots = appearance_roots(s, p)?;
|
||||
if !targets_contents(p)? {
|
||||
return Ok(roots);
|
||||
}
|
||||
let (_, _, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
|
||||
let mut ids = leaf_targets(s, &roots)?;
|
||||
ids.retain(|id| !hidden.contains(id));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The objects [`appearance_targets`] starts from: `ids`/`id`, else the [`subject_roots`].
|
||||
fn appearance_roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
if p.get("ids").is_none() && p.get("id").is_none() {
|
||||
subject_roots(s)
|
||||
} else {
|
||||
let d = &s.doc()?.doc;
|
||||
outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect())
|
||||
};
|
||||
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
|
||||
Ok(outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of the Live Paint groups whose contents `p` targets (`target: "contents"`) that a fill
|
||||
/// (`fill`) or stroke edit of those contents leaves as they are: their edges or faces. Empty without
|
||||
/// `target: "contents"`.
|
||||
pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<HashSet<NodeId>> {
|
||||
if !targets_contents(p)? {
|
||||
return Ok(HashSet::new());
|
||||
}
|
||||
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
|
||||
}
|
||||
|
||||
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
|
||||
@@ -897,7 +924,26 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
|
||||
let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" };
|
||||
let mut ids = row_targets(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
// A selected Live Paint group left with only its hidden source paths has nothing to edit: it is
|
||||
// still a selection, so the edit changes nothing.
|
||||
let roots = appearance_roots(s, p)?;
|
||||
if targets_contents(p)? && !roots.is_empty() && !super::paint::live_paint_split(&s.doc()?.doc, &roots).2.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
// In the contents of a Live Paint group, a new fill goes on its faces and a new stroke on its edges;
|
||||
// with no part of that kind, nothing changes.
|
||||
let skipped = contents_skipped(s, p, fill)?;
|
||||
if !skipped.is_empty() {
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
if ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
let defaults = s.paint.clone();
|
||||
// The panel's active Fill row, when the new fill goes on the selection: the new fill takes that
|
||||
// row's paint, right above it in each target that has it (others take their top fill's paint).
|
||||
@@ -1779,7 +1825,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Reversed, the first selected object's attributes go onto the clicked object; with nothing
|
||||
// selected, what the Eyedropper picked up last does (#4382).
|
||||
let (source, mut targets) = if reverse {
|
||||
let source = match leaf_targets(s, &selected)?.into_iter().next() {
|
||||
// The selected objects are tried in order: a Live Paint group with a look is picked up as a whole
|
||||
// ([`live_paint_look`]), any other object gives its first painted leaf, and a group with nothing to pick
|
||||
// up (its hidden source paths are not what it draws) passes to the next object.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut first = None;
|
||||
for root in &selected {
|
||||
if d.node(*root).and_then(live_paint_look).is_some() {
|
||||
first = Some(*root);
|
||||
break;
|
||||
}
|
||||
let (_, _, hidden) = super::paint::live_paint_split(d, &[*root]);
|
||||
if let Some(leaf) = leaf_targets(s, &[*root])?.into_iter().find(|id| !hidden.contains(id)) {
|
||||
first = Some(leaf);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let source = match first {
|
||||
Some(first) => Some(first),
|
||||
None if s.eyedropper_sample.is_some() => None,
|
||||
None => return Err(bad(C, "select the object to copy from")),
|
||||
@@ -1788,10 +1850,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
(Some(clicked), leaf_targets(s, &selected)?)
|
||||
};
|
||||
targets.retain(|id| Some(*id) != source);
|
||||
// A whole Live Paint group takes the fill attributes on its faces and the stroke attributes on its edges, and its
|
||||
// hidden source paths keep their paint.
|
||||
let roots = if reverse { vec![clicked] } else { selected };
|
||||
let (faces, edges, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
|
||||
// Some(true) for a face, Some(false) for an edge.
|
||||
let part_of = |id: &NodeId| {
|
||||
if faces.contains(id) {
|
||||
Some(true)
|
||||
} else if edges.contains(id) {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let attrs_for = |id: &NodeId| {
|
||||
let mut a = attrs;
|
||||
match part_of(id) {
|
||||
Some(true) => a.appearance.stroke = StrokeAttrs::NONE,
|
||||
Some(false) => a.appearance.fill = FillAttrs::NONE,
|
||||
None => {}
|
||||
}
|
||||
a
|
||||
};
|
||||
// A pick of the whole appearance gives a face every fill row and an edge every stroke row.
|
||||
let whole = attrs.appearance.fill == FillAttrs::ALL && attrs.appearance.stroke == StrokeAttrs::ALL;
|
||||
// A source that is a Live Paint group is not one of its own targets: neither are its faces and edges.
|
||||
let mut inside_source = HashSet::new();
|
||||
if let Some(n) = source.and_then(|id| s.doc().ok()?.doc.node(id)).filter(|n| is_live_paint(n)) {
|
||||
n.walk(&mut |c| {
|
||||
inside_source.insert(c.id);
|
||||
});
|
||||
}
|
||||
targets.retain(|id| Some(*id) != source && !hidden.contains(id) && !inside_source.contains(id));
|
||||
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
|
||||
let node = match source {
|
||||
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
|
||||
Some(id) => {
|
||||
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
Arc::new(live_paint_look(n).unwrap_or_else(|| n.clone()))
|
||||
}
|
||||
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
|
||||
};
|
||||
let picked = Picked::of(&node);
|
||||
@@ -1919,7 +2016,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::overprint::edit_counted(s, "Eyedropper", |d| {
|
||||
for id in &targets {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
picked.apply(n, &attrs, append, characters.get(id));
|
||||
match part_of(id) {
|
||||
Some(fill) if whole && !append => picked.apply_rows(n, &attrs, fill),
|
||||
// `append` does not add the picked object effects to a face or edge, as a whole pick keeps the part's
|
||||
// own; a row's effects go with the row.
|
||||
Some(_) => {
|
||||
let effects = n.appearance.effects.len();
|
||||
picked.apply(n, &attrs_for(id), append, characters.get(id));
|
||||
n.appearance.effects.truncate(effects);
|
||||
}
|
||||
None => picked.apply(n, &attrs_for(id), append, characters.get(id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
check_text_bounds(d)?;
|
||||
@@ -2170,6 +2277,52 @@ impl Picked {
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
|
||||
/// A whole pick ([`Self::apply`] with every fill and stroke attribute) onto a Live Paint face
|
||||
/// (`fill`) or edge: the face's fills (the edge's strokes) become the picked ones, and its rows of
|
||||
/// the other kind and its effects stay as they are.
|
||||
fn apply_rows(&self, n: &mut Node, a: &EyedropperAttrs, fill: bool) {
|
||||
if a.appearance.transparency {
|
||||
n.opacity = self.opacity;
|
||||
n.blend = self.blend;
|
||||
}
|
||||
let taken: Vec<AppearanceItem> = self.placed(n.geometric_bounds()).items.into_iter().filter(|it| it.is_fill() == fill).collect();
|
||||
// The picked rows go where the part's first row of that kind was, the other rows keep their order; without
|
||||
// such a row, fills go to the bottom and strokes to the top.
|
||||
let items = &n.appearance.items;
|
||||
let at = items.iter().position(|it| it.is_fill() == fill);
|
||||
let at = at.map_or(if fill { 0 } else { items.iter().filter(|it| it.is_fill() != fill).count() }, |i| {
|
||||
items.iter().take(i).filter(|it| it.is_fill() != fill).count()
|
||||
});
|
||||
let mut kept: Vec<AppearanceItem> = items.iter().filter(|it| it.is_fill() != fill).cloned().collect();
|
||||
kept.splice(at..at, taken);
|
||||
n.appearance.items = kept;
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Eyedropper picks up from a whole Live Paint group `n`: its first face (else its first edge) with that
|
||||
/// face's fills and the first edge's strokes above them, their gradients placed as on those parts, and the group's
|
||||
/// own opacity, blend mode and effects. None for any other object, and for a group with no face and no edge.
|
||||
fn live_paint_look(n: &Node) -> Option<Node> {
|
||||
if !is_live_paint(n) {
|
||||
return None;
|
||||
}
|
||||
let (face, edge) = (faces(n).first().copied(), edges(n).first().copied());
|
||||
let mut look = (**face.or(edge)?).clone();
|
||||
let rows = |part: Option<&Arc<Node>>, fill: bool| -> Vec<AppearanceItem> {
|
||||
part.map(|p| p.appearance.items.iter().filter(|it| it.is_fill() == fill).cloned().collect()).unwrap_or_default()
|
||||
};
|
||||
// The edge's stroke gradients, placed relative to the look's bounds as they are to the edge's.
|
||||
let mut strokes = Appearance { items: rows(edge, false), ..Default::default() };
|
||||
if let (Some(from), Some(to)) = (edge.and_then(|e| e.geometric_bounds()), look.geometric_bounds()) {
|
||||
strokes.rebase_gradients(from, to);
|
||||
}
|
||||
look.appearance.items = rows(face, true).into_iter().chain(strokes.items).collect();
|
||||
look.appearance.effects = n.appearance.effects.clone();
|
||||
look.opacity = n.opacity;
|
||||
look.blend = n.blend;
|
||||
Some(look)
|
||||
}
|
||||
|
||||
/// The focal (topmost) fill and stroke attributes `a` of `from` onto `to`. Taking a colour creates
|
||||
|
||||
@@ -188,6 +188,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
|
||||
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
|
||||
BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic },
|
||||
BuiltinBrushLibrary { id: "vector-packs", name: "Vector Packs", make: vector_packs },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -866,6 +867,38 @@ fn scatter_shapes() -> BrushLibrary {
|
||||
built("Scatter Shapes", doc, brushes)
|
||||
}
|
||||
|
||||
/// Vector Packs: four original, editable vector marks that follow the stroke color.
|
||||
fn vector_packs() -> BrushLibrary {
|
||||
let compass = group(vec![black(shapes::star(Point::ZERO, 10.0, 3.0, 8, 0.0)), black(shapes::ellipse(Rect::new(-1.5, -1.5, 1.5, 1.5)))]);
|
||||
let sprig = group(vec![
|
||||
black(polygon(&[(-0.7, 10.0), (0.7, 10.0), (0.7, -10.0), (-0.7, -10.0)])),
|
||||
black(polygon(&[(0.0, 5.0), (5.0, 2.0), (7.0, -1.0), (3.0, 0.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (-5.0, -3.0), (-7.0, -6.0), (-3.0, -5.0)])),
|
||||
black(polygon(&[(0.0, -5.0), (5.0, -8.0), (7.0, -10.0), (3.0, -9.0)])),
|
||||
]);
|
||||
let diamond = group(vec![
|
||||
black(polygon(&[(-9.0, 0.0), (-1.0, -9.0), (-1.0, -1.0)])),
|
||||
black(polygon(&[(1.0, -9.0), (9.0, 0.0), (1.0, -1.0)])),
|
||||
black(polygon(&[(9.0, 0.0), (1.0, 9.0), (1.0, 1.0)])),
|
||||
black(polygon(&[(-1.0, 9.0), (-9.0, 0.0), (-1.0, 1.0)])),
|
||||
]);
|
||||
let tide = group(vec![
|
||||
black(band(20.0, 1.2, 32, |x| -3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())),
|
||||
black(band(20.0, 1.2, 32, |x| 3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())),
|
||||
]);
|
||||
let settings = Scatter { size: (90.0, 110.0), spacing: (130.0, 160.0), colorization: Colorization::Tints, ..Default::default() };
|
||||
built(
|
||||
"Vector Packs",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
scatter("Compass Rose", compass, settings.clone()),
|
||||
scatter("Botanical Sprig", sprig, settings.clone()),
|
||||
scatter("Facet Diamond", diamond, settings.clone()),
|
||||
scatter("Tide Crest", tide, settings),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Stipple: original dot-based scatter brushes for fine and broad shading along a path.
|
||||
fn stipple() -> BrushLibrary {
|
||||
let dot = |x: f64, y: f64, r: f64, opacity: f32| {
|
||||
|
||||
@@ -42,8 +42,12 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target};
|
||||
use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view};
|
||||
pub use trace::{
|
||||
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
|
||||
};
|
||||
use trace::{
|
||||
trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view,
|
||||
};
|
||||
|
||||
/// Name of an Image Trace group.
|
||||
pub const TRACE_NAME: &str = "Image Trace";
|
||||
@@ -208,6 +212,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
trace_presets_delete
|
||||
),
|
||||
cmd!(
|
||||
query "imageTrace.presets.import",
|
||||
"Import Image Trace Presets",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, replace?: false (true: a preset whose name a saved preset has replaces that preset's settings; false: it is skipped)} add the presets of a .vctracepresets file (as imageTrace.presets.export writes, at most 4 MiB and 1,000 presets) to the saved ones → {imported: [names added], replaced: [names], skipped: [names]}; every preset is checked first, and a file with a built-in preset's or Custom's name, two presets of one name, a preset without a name or with settings imageTrace.presets.save refuses, or a newer version changes nothing",
|
||||
always,
|
||||
trace_presets_import
|
||||
),
|
||||
cmd!(
|
||||
query "imageTrace.presets.export",
|
||||
"Export Image Trace Presets",
|
||||
[],
|
||||
None,
|
||||
"{names?: [saved preset names] (default: every saved preset; built-in ones are refused), path?} write the saved tracing presets as a .vctracepresets file (JSON: format, version 1, presets: [{name, params}]) → {path, count}; without path → {data: the file's text, count}; more than 1,000 presets, or a file over 4 MiB, is refused, as imageTrace.presets.import would refuse it",
|
||||
always,
|
||||
trace_presets_export
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -168,6 +168,9 @@ pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if old.is_none() && new_name.is_some() {
|
||||
return Err(bad(C, format!("no saved preset named `{name}` to rename")));
|
||||
}
|
||||
if old.is_none() && s.prefs.trace_presets.len() >= TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("{TRACE_PRESET_MAX_COUNT} tracing presets are saved, the most there can be: delete one first")));
|
||||
}
|
||||
// A saved preset changes from its own settings unless `preset` says where to start.
|
||||
let mut q = p.clone();
|
||||
if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) {
|
||||
@@ -203,6 +206,162 @@ pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result<Value>
|
||||
Ok(json!({ "deleted": deleted }))
|
||||
}
|
||||
|
||||
/// The `format` of a tracing presets file, also its extension.
|
||||
pub const TRACE_PRESET_FORMAT: &str = "vctracepresets";
|
||||
|
||||
/// The extensions of tracing presets files (opening one imports it).
|
||||
pub const TRACE_PRESET_EXTS: &[&str] = &[TRACE_PRESET_FORMAT];
|
||||
|
||||
/// The `version` `imageTrace.presets.export` writes; `imageTrace.presets.import` reads files of
|
||||
/// this version and earlier ones.
|
||||
const TRACE_PRESET_VERSION: u64 = 1;
|
||||
|
||||
/// The largest tracing presets file `imageTrace.presets.import` reads.
|
||||
pub const TRACE_PRESET_MAX_BYTES: usize = 4 << 20;
|
||||
|
||||
/// The most presets one tracing presets file may hold, and the most tracing presets that can be
|
||||
/// saved (so every saved preset fits in one exported file).
|
||||
const TRACE_PRESET_MAX_COUNT: usize = 1000;
|
||||
|
||||
pub(super) fn trace_presets_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.presets.export";
|
||||
let presets: Vec<&TracePreset> = match p.get("names").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(names)) => {
|
||||
let mut out: Vec<&TracePreset> = vec![];
|
||||
for n in names {
|
||||
let n = n.as_str().ok_or_else(|| bad(C, "`names` must hold preset names"))?;
|
||||
if tr::preset(n).is_some() {
|
||||
return Err(bad(C, format!("`{n}` is a built-in preset: only saved presets are exported")));
|
||||
}
|
||||
let q = s.trace_preset(n).ok_or_else(|| bad(C, format!("no saved preset named `{n}`")))?;
|
||||
if !out.iter().any(|o| o.name == q.name) {
|
||||
out.push(q);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`names` must be an array of preset names")),
|
||||
None => s.prefs.trace_presets.iter().collect(),
|
||||
};
|
||||
if presets.is_empty() {
|
||||
return Err(bad(C, "no saved tracing presets to export"));
|
||||
}
|
||||
// A file is written only when `imageTrace.presets.import` can read it back.
|
||||
let count = presets.len();
|
||||
if count > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("{count} presets are more than one file holds ({TRACE_PRESET_MAX_COUNT}): export fewer with `names`")));
|
||||
}
|
||||
let rows: Vec<Value> = presets.iter().map(|q| json!({"name": q.name, "params": q.params})).collect();
|
||||
let file = json!({"format": TRACE_PRESET_FORMAT, "version": TRACE_PRESET_VERSION, "presets": rows});
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if text.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(bad(C, format!("the file would be larger than {} MiB: export fewer with `names`", TRACE_PRESET_MAX_BYTES >> 20)));
|
||||
}
|
||||
match opt_str(C, p, "path")? {
|
||||
Some(path) => {
|
||||
crate::cmd::fileio::write_file(path, text.as_bytes())?;
|
||||
Ok(json!({"path": path, "count": count}))
|
||||
}
|
||||
None => Ok(json!({"data": text, "count": count})),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of the tracing presets file `p` names (`path`, `data` or `dataBase64`), at most
|
||||
/// [`TRACE_PRESET_MAX_BYTES`] of them.
|
||||
fn trace_preset_file(c: &str, p: &Value) -> Result<Vec<u8>> {
|
||||
let too_big = || bad(c, format!("the file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20));
|
||||
let bytes = match (opt_str(c, p, "path")?, opt_str(c, p, "data")?, opt_str(c, p, "dataBase64")?) {
|
||||
(Some(path), ..) => crate::cmd::fileio::read_file_head(path, TRACE_PRESET_MAX_BYTES + 1)?,
|
||||
(None, Some(text), _) => {
|
||||
if text.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(too_big());
|
||||
}
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
(None, None, Some(b64)) => {
|
||||
if vectorcraft_format::base64_decoded_len(b64) > TRACE_PRESET_MAX_BYTES as u64 {
|
||||
return Err(too_big());
|
||||
}
|
||||
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?
|
||||
}
|
||||
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(too_big());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(super) fn trace_presets_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.presets.import";
|
||||
let replace = switch_or(p, "replace", false, C)?;
|
||||
let bytes = trace_preset_file(C, p)?;
|
||||
let not_file = |why: String| bad(C, format!("not a tracing presets file: {why}"));
|
||||
let file: Value = serde_json::from_slice(&bytes).map_err(|e| not_file(e.to_string()))?;
|
||||
if file["format"] != TRACE_PRESET_FORMAT {
|
||||
return Err(not_file(format!("format `{}`", file["format"].as_str().unwrap_or_default())));
|
||||
}
|
||||
match file["version"].as_u64() {
|
||||
Some(v) if (1..=TRACE_PRESET_VERSION).contains(&v) => {}
|
||||
Some(v) => return Err(bad(C, format!("the file's version {v} is newer than this version of VectorCraft reads ({TRACE_PRESET_VERSION})"))),
|
||||
None => return Err(not_file("no `version`".into())),
|
||||
}
|
||||
let rows = file["presets"].as_array().ok_or_else(|| not_file("no `presets` list".into()))?;
|
||||
if rows.len() > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("the file holds {} presets, more than {TRACE_PRESET_MAX_COUNT}", rows.len())));
|
||||
}
|
||||
// Every preset is checked before any is saved, so a file with a fault changes nothing.
|
||||
let mut presets: Vec<TracePreset> = Vec::with_capacity(rows.len());
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
let name = row["name"].as_str().map(str::trim).unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
return Err(bad(C, format!("preset {} has no name", i + 1)));
|
||||
}
|
||||
if tr::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") {
|
||||
return Err(bad(C, format!("`{name}` is the name of a built-in preset: rename it in the file")));
|
||||
}
|
||||
if presets.iter().any(|q| q.name.eq_ignore_ascii_case(name)) {
|
||||
return Err(bad(C, format!("the file holds two presets named `{name}`")));
|
||||
}
|
||||
let params = match row.get("params").filter(|v| v.is_object()) {
|
||||
Some(params) => trace_params(s, C, &json!({"preset": "Default", "params": params})).map_err(|e| match e {
|
||||
EngineError::BadParams { msg, .. } => bad(C, format!("`{name}`: {msg}")),
|
||||
e => e,
|
||||
})?,
|
||||
None => return Err(bad(C, format!("`{name}` has no `params`"))),
|
||||
};
|
||||
presets.push(TracePreset { name: name.to_string(), params });
|
||||
}
|
||||
let added = presets.iter().filter(|q| s.trace_preset_index(&q.name).is_none()).count();
|
||||
if s.prefs.trace_presets.len() + added > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("the file's {added} new presets would make more than {TRACE_PRESET_MAX_COUNT} saved tracing presets: delete some first"),
|
||||
));
|
||||
}
|
||||
let (mut imported, mut replaced, mut skipped) = (vec![], vec![], vec![]);
|
||||
for preset in presets {
|
||||
let name = preset.name.clone();
|
||||
match s.trace_preset_index(&name) {
|
||||
Some(i) if replace => {
|
||||
let Some(slot) = s.prefs.trace_presets.get_mut(i) else { continue };
|
||||
// The saved preset keeps its name as it was saved.
|
||||
let kept = slot.name.clone();
|
||||
*slot = TracePreset { name: kept.clone(), params: preset.params };
|
||||
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: kept.clone(), renamed_from: None, deleted: false });
|
||||
replaced.push(kept);
|
||||
}
|
||||
Some(_) => skipped.push(name),
|
||||
None => {
|
||||
s.prefs.trace_presets.push(preset);
|
||||
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: None, deleted: false });
|
||||
imported.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"imported": imported, "replaced": replaced, "skipped": skipped}))
|
||||
}
|
||||
|
||||
/// The string `key` of `p` (`None` when it is missing or null); any other type is an error of
|
||||
/// command `c`.
|
||||
fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result<Option<&'a str>> {
|
||||
|
||||
@@ -19,7 +19,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::Swatch;
|
||||
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
|
||||
use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
|
||||
use vectorcraft_geom::{PathData, Rect};
|
||||
|
||||
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
|
||||
@@ -94,6 +94,9 @@ pub struct Clipboard {
|
||||
pub para_styles: Vec<TextStyleDef>,
|
||||
/// Brushes the objects' strokes use.
|
||||
pub brushes: Vec<Brush>,
|
||||
/// Graph designs the copied graphs draw their columns, bars or markers with. Pasting adds the
|
||||
/// ones the document lacks; a design the document has under the same name stays as it is.
|
||||
pub graph_designs: Vec<GraphDesign>,
|
||||
/// The artboard the objects were copied from (none when they lie on no artboard; the first of
|
||||
/// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it.
|
||||
pub source_artboard: Option<Rect>,
|
||||
@@ -395,7 +398,7 @@ impl Clipboard {
|
||||
if self.source_doc == Some(st.uid) && !self.colors_converted {
|
||||
return vec![];
|
||||
}
|
||||
self.conflicts(&st.doc, &self.used())
|
||||
self.conflicts(&st.doc, &self.used(&st.doc))
|
||||
}
|
||||
|
||||
/// A standalone document holding the objects and their resources (SVG export).
|
||||
@@ -408,6 +411,7 @@ impl Clipboard {
|
||||
d.graphic_styles.extend(self.graphic_styles.iter().cloned());
|
||||
d.char_styles = self.char_styles.clone().into();
|
||||
d.para_styles = self.para_styles.clone().into();
|
||||
d.graph_designs = self.graph_designs.clone();
|
||||
if !self.brushes.is_empty() {
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
// Each brush's place in the library by name: finding it by scanning the growing list
|
||||
@@ -469,6 +473,7 @@ impl Clipboard {
|
||||
char_styles: d.char_styles.to_vec(),
|
||||
para_styles: d.para_styles.to_vec(),
|
||||
brushes: vectorcraft_brush::library(&d),
|
||||
graph_designs: d.graph_designs.clone(),
|
||||
images: self.images.clone(),
|
||||
symbol_options: self.symbol_options.clone(),
|
||||
source_artboard: self.source_artboard,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The document resources copied objects use, and adding them to the document they're pasted into.
|
||||
//!
|
||||
//! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and
|
||||
//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also
|
||||
//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to.
|
||||
//! paragraph styles, brushes, graph designs) and to graphic styles by id. Copy follows those
|
||||
//! references, also through the symbols, patterns, styles, brush art and graph design art it finds,
|
||||
//! and keeps what they lead to.
|
||||
//!
|
||||
//! Pasting matches each resource by name: an identical one in the document is used, a missing one
|
||||
//! is added, and a different one of the same name is added under a free name, which the pasted
|
||||
@@ -22,8 +23,8 @@ use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType,
|
||||
SymbolNineSlice, SymbolRegistration, TextStyleDef,
|
||||
Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol,
|
||||
SymbolExportType, SymbolNineSlice, SymbolRegistration, TextStyleDef,
|
||||
};
|
||||
|
||||
use super::super::brushsym::{set_natural_size, stored_natural_size};
|
||||
@@ -44,6 +45,7 @@ enum Res {
|
||||
ParaStyle,
|
||||
Brush,
|
||||
GraphicStyle,
|
||||
GraphDesign,
|
||||
}
|
||||
|
||||
impl Res {
|
||||
@@ -57,6 +59,7 @@ impl Res {
|
||||
Res::ParaStyle => "paraStyle",
|
||||
Res::Brush => "brush",
|
||||
Res::GraphicStyle => "graphicStyle",
|
||||
Res::GraphDesign => "graphDesign",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,6 +142,10 @@ fn node_refs(n: &Node, f: Visit) {
|
||||
for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) {
|
||||
f(Ref::Name(Res::ParaStyle, s));
|
||||
}
|
||||
// The designs its series draw their markers, columns or bars with.
|
||||
for d in g.series_markers.iter().flatten().chain(g.series_columns.iter().flatten().map(|c| &c.design)) {
|
||||
f(Ref::Name(Res::GraphDesign, d));
|
||||
}
|
||||
}
|
||||
match &m.kind {
|
||||
NodeKind::Text(t) => {
|
||||
@@ -217,6 +224,7 @@ struct Defs<'a> {
|
||||
char_styles: &'a [TextStyleDef],
|
||||
para_styles: &'a [TextStyleDef],
|
||||
brushes: Brushes<'a>,
|
||||
graph_designs: &'a [GraphDesign],
|
||||
/// Where each name is defined, built the first time a kind is followed.
|
||||
index: DefIndex,
|
||||
}
|
||||
@@ -236,6 +244,7 @@ struct DefIndex {
|
||||
char_styles: OnceCell<NameIndex>,
|
||||
para_styles: OnceCell<NameIndex>,
|
||||
brushes: OnceCell<NameIndex>,
|
||||
graph_designs: OnceCell<NameIndex>,
|
||||
}
|
||||
|
||||
/// The items of `list` named `name`, in order, `index` holding their positions (built from
|
||||
@@ -279,6 +288,7 @@ impl<'a> Defs<'a> {
|
||||
char_styles: &d.char_styles,
|
||||
para_styles: &d.para_styles,
|
||||
brushes: Brushes::Lazy(d, brushes),
|
||||
graph_designs: &d.graph_designs,
|
||||
index: DefIndex::default(),
|
||||
}
|
||||
}
|
||||
@@ -376,6 +386,7 @@ impl Used {
|
||||
Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))),
|
||||
// A scatter or art brush's art, a pattern brush's tiles.
|
||||
Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))),
|
||||
Res::GraphDesign => todo.extend(named(&ix.graph_designs, defs.graph_designs, |g| &g.name, name).map(|g| Source::Node(&g.art))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -406,7 +417,7 @@ pub struct ArtResources {
|
||||
/// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them
|
||||
/// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked
|
||||
/// colours, tints, gradient swatches; colour groups' included), character and paragraph styles,
|
||||
/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count
|
||||
/// brushes, graph designs and graphic styles, and the document's Spot Colors option. Art and image bytes count
|
||||
/// by identity, the other definitions by their saved form: working the key out walks `art` and
|
||||
/// the definitions it leads to, and never reads an image's bytes.
|
||||
pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a Node>) -> ArtResources {
|
||||
@@ -451,6 +462,7 @@ pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a No
|
||||
Res::CharStyle => doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)),
|
||||
Res::GraphDesign => doc.graph_designs.iter().filter(|g| g.name == *name).for_each(|g| node(&mut h, &mut kept.0, &g.art)),
|
||||
// Swatches below (tints count too); graphic styles go by id.
|
||||
Res::Swatch | Res::GraphicStyle => {}
|
||||
}
|
||||
@@ -824,6 +836,22 @@ fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
|
||||
ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b))
|
||||
}
|
||||
|
||||
/// `n` with the ids of its objects, those of opacity-mask art included, all 0: art drawn again
|
||||
/// compares equal to art drawn the same way, whatever ids each drawing gave it.
|
||||
fn without_ids(n: &Node) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = vectorcraft_doc::NodeId(0);
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
mask.art = Arc::new(without_ids(&mask.art));
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(without_ids(c));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by
|
||||
/// `r`? Graphic style links don't count, as in [`same_art`].
|
||||
fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
|
||||
@@ -1106,6 +1134,17 @@ pub(crate) struct Imported {
|
||||
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
|
||||
/// renamed, or a copy added renamed by an earlier paste.
|
||||
pub renamed: Vec<Value>,
|
||||
/// The graph designs the pasted graphs draw with that the document has under the same name
|
||||
/// and that would draw them otherwise than the art they were pasted with: the document keeps
|
||||
/// its own, and the pasted graphs are drawn again with it.
|
||||
pub kept_designs: BTreeSet<String>,
|
||||
/// The names of the symbols added to the document, whose art may hold graphs that draw with
|
||||
/// [`Self::kept_designs`].
|
||||
pub added_symbols: BTreeSet<String>,
|
||||
/// The names of the graph designs added to the document.
|
||||
pub added_designs: BTreeSet<String>,
|
||||
/// The global and spot colors that took the document's color (merged).
|
||||
merged_swatches: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Imported {
|
||||
@@ -1161,15 +1200,24 @@ impl Clipboard {
|
||||
char_styles: pick(Res::CharStyle, &src.char_styles),
|
||||
para_styles: pick(Res::ParaStyle, &src.para_styles),
|
||||
brushes,
|
||||
graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(),
|
||||
set_densities: src.set_densities_of(&nodes),
|
||||
nodes,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The resources the objects use now (Paste without Formatting leaves text styles behind).
|
||||
pub(super) fn used(&self) -> Used {
|
||||
let defs = Defs {
|
||||
/// The resources the objects use now (Paste without Formatting leaves text styles behind),
|
||||
/// pasted into `d`: the art of a graph design `d` has under the same name is not followed, as
|
||||
/// `d` keeps its own design.
|
||||
pub(super) fn used(&self, d: &Document) -> Used {
|
||||
let designs: Vec<GraphDesign> = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect();
|
||||
Used::of(&self.defs(&designs), &self.nodes)
|
||||
}
|
||||
|
||||
/// The clipboard's definitions, with graph designs `designs`.
|
||||
fn defs<'a>(&'a self, designs: &'a [GraphDesign]) -> Defs<'a> {
|
||||
Defs {
|
||||
swatches: self.swatches.iter().collect(),
|
||||
symbols: &self.symbols,
|
||||
patterns: &self.patterns,
|
||||
@@ -1177,9 +1225,9 @@ impl Clipboard {
|
||||
char_styles: &self.char_styles,
|
||||
para_styles: &self.para_styles,
|
||||
brushes: Brushes::Ready(&self.brushes),
|
||||
graph_designs: designs,
|
||||
index: DefIndex::default(),
|
||||
};
|
||||
Used::of(&defs, &self.nodes)
|
||||
}
|
||||
}
|
||||
|
||||
/// The used global and spot colours whose name `d` gives another one: (pasted, document).
|
||||
@@ -1200,7 +1248,8 @@ impl Clipboard {
|
||||
/// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another
|
||||
/// document's are, while its image blobs are still the document's own under their keys.
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
|
||||
self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc)
|
||||
let used = self.used(d);
|
||||
self.import_used_with_images(d, &used, choices, same_doc && !self.colors_converted, same_doc)
|
||||
}
|
||||
|
||||
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
|
||||
@@ -1211,7 +1260,7 @@ impl Clipboard {
|
||||
if same_doc {
|
||||
return;
|
||||
}
|
||||
let used = self.used();
|
||||
let used = self.used(d);
|
||||
let colors: BTreeMap<String, Color> = self
|
||||
.conflicts(d, &used)
|
||||
.into_iter()
|
||||
@@ -1248,6 +1297,11 @@ impl Clipboard {
|
||||
) -> Result<Imported> {
|
||||
let mut out = Imported::default();
|
||||
out.relink.filters = self.filter_links(d, same_doc)?;
|
||||
let held = |name: &str| d.graph_designs.iter().any(|x| x.name == name);
|
||||
let new_designs = self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name) && !held(&g.name)).count();
|
||||
if new_designs > 0 && d.graph_designs.len().saturating_add(new_designs) > GraphDesign::MAX {
|
||||
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
|
||||
}
|
||||
self.import_images(d, used, same_doc_images, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
self.import_kinsoku_sets(d, used, same_doc, &mut out);
|
||||
@@ -1331,11 +1385,18 @@ impl Clipboard {
|
||||
.collect(),
|
||||
None => HashMap::new(),
|
||||
};
|
||||
// A symbol whose graphs the paste draws again with the document's designs is
|
||||
// also the document's one that holds its art drawn that way (an earlier paste
|
||||
// added it).
|
||||
let redrawn = (!fresh && d.symbols.iter().any(|s| copy_of(&def.name, &s.name)))
|
||||
.then(|| self.redrawn_art(d, &def.art, &out.relink))
|
||||
.flatten();
|
||||
let r = &out.relink;
|
||||
let p = place(&mut d.symbols, def, same_doc, |a, b| {
|
||||
!fresh
|
||||
&& options.is_none_or(|o| theirs.get(&a.name) == Some(o))
|
||||
&& same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|
||||
&& (same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|
||||
|| redrawn.as_ref().is_some_and(|art| without_ids(&a.art) == *art))
|
||||
});
|
||||
if let Some(name) = p.new_name(&def.name) {
|
||||
if let Some(o) = options {
|
||||
@@ -1371,6 +1432,7 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
self.import_graphic_styles(d, used, same_doc, &mut out);
|
||||
self.import_graph_designs(d, used, same_doc, &mut out)?;
|
||||
for (r, name, def) in added_styles {
|
||||
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
|
||||
if let Some(s) = theirs.iter_mut().find(|s| s.name == name) {
|
||||
@@ -1381,6 +1443,7 @@ impl Clipboard {
|
||||
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
|
||||
out.relink.node(Arc::make_mut(&mut s.art));
|
||||
}
|
||||
out.added_symbols = added_symbols.into_iter().collect();
|
||||
for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) {
|
||||
for a in &mut p.art {
|
||||
out.relink.node(Arc::make_mut(a));
|
||||
@@ -1497,6 +1560,10 @@ impl Clipboard {
|
||||
for a in self.brushes.iter().flat_map(Brush::art) {
|
||||
node_filters(a, &mut found);
|
||||
}
|
||||
// A design the document has under the same name stays its own, so its art here is not pasted.
|
||||
for g in self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)) {
|
||||
node_filters(&g.art, &mut found);
|
||||
}
|
||||
for g in &self.graphic_styles {
|
||||
appearance_filters(&g.appearance, &mut found);
|
||||
}
|
||||
@@ -1575,6 +1642,7 @@ impl Clipboard {
|
||||
for w in &bases {
|
||||
let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge {
|
||||
out.merged += 1;
|
||||
out.merged_swatches.insert(w.name.clone());
|
||||
Placed::Existing
|
||||
} else {
|
||||
add_swatch(d, w, same_doc)
|
||||
@@ -1624,6 +1692,71 @@ impl Clipboard {
|
||||
out.relink.styles.insert(g.id, d.graphic_style_id(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol art `art` relinked by `relink` with its graphs drawn again with the designs `d` holds
|
||||
/// under a name whose design the clipboard lacks or holds with other art, as a paste that adds
|
||||
/// the symbol draws it, its ids left out ([`without_ids`]). `None` when no graph of it draws
|
||||
/// with such a design.
|
||||
fn redrawn_art(&self, d: &mut Document, art: &Arc<Node>, relink: &Relink) -> Option<Node> {
|
||||
let theirs = |n: &str| self.graph_designs.iter().find(|g| g.name == n);
|
||||
let differs: BTreeSet<String> = d
|
||||
.graph_designs
|
||||
.iter()
|
||||
.filter(|x| theirs(&x.name).is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art))
|
||||
.map(|x| x.name.clone())
|
||||
.collect();
|
||||
if differs.is_empty() || !crate::cmd::graph::holds_designs(art, &differs) {
|
||||
return None;
|
||||
}
|
||||
let mut n = (**art).clone();
|
||||
relink.node(&mut n);
|
||||
crate::cmd::graph::redraw_detached(d, &mut n, &differs);
|
||||
Some(without_ids(&n))
|
||||
}
|
||||
|
||||
/// Graph designs: the document's design of a name stays as it is and the pasted graphs draw
|
||||
/// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the
|
||||
/// resources placed above, with fresh ids. Called once every other resource is placed.
|
||||
fn import_graph_designs(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) -> Result<()> {
|
||||
// Every name the pasted graphs draw with whose design in the document would draw them
|
||||
// otherwise: another design of that name, one the clipboard holds no design for (deleted
|
||||
// and made again), or, from another document, the same art when a resource came in renamed
|
||||
// or a swatch took the document's color, that the design's art uses. (An SVG filter effect
|
||||
// carries its definition, so a filter that draws otherwise makes the art differ.)
|
||||
let defs = self.defs(&self.graph_designs);
|
||||
let moved = |n: &str| {
|
||||
if same_doc || (out.relink.renames.is_empty() && out.merged_swatches.is_empty()) {
|
||||
return false;
|
||||
}
|
||||
let uses = designs_used(&defs, &[n.to_string()]);
|
||||
out.relink.renames.iter().any(|(r, names)| names.keys().any(|from| uses.has(*r, from)))
|
||||
|| out.merged_swatches.iter().any(|w| uses.has(Res::Swatch, w))
|
||||
};
|
||||
let differs = |n: &str| {
|
||||
let ours = d.graph_designs.iter().find(|x| x.name == n);
|
||||
let theirs = self.graph_designs.iter().find(|g| g.name == n);
|
||||
ours.is_some_and(|x| theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art) || moved(n))
|
||||
};
|
||||
let named = used.names.get(&Res::GraphDesign).into_iter().flatten();
|
||||
let kept: Vec<String> = named.filter(|n| differs(n)).cloned().collect();
|
||||
out.kept_designs.extend(kept);
|
||||
for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) {
|
||||
if d.graph_designs.iter().any(|x| x.name == g.name) {
|
||||
out.placed(Res::GraphDesign, &g.name, &Placed::Existing);
|
||||
continue;
|
||||
}
|
||||
if d.graph_designs.len() >= GraphDesign::MAX {
|
||||
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
|
||||
}
|
||||
let mut art = (*g.art).clone();
|
||||
out.relink.node(&mut art);
|
||||
let art = d.reid(&art);
|
||||
d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) });
|
||||
out.placed(Res::GraphDesign, &g.name, &Placed::Added);
|
||||
out.added_designs.insert(g.name.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a loaded text style is in the document ([`import_text_styles`]).
|
||||
@@ -1663,6 +1796,72 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
Ok(placed)
|
||||
}
|
||||
|
||||
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
|
||||
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
|
||||
let mut used = Used::default();
|
||||
let mut todo = vec![];
|
||||
for n in names {
|
||||
used.note(defs, Ref::Name(Res::GraphDesign, n), &mut todo);
|
||||
}
|
||||
used.follow(defs, todo);
|
||||
used
|
||||
}
|
||||
|
||||
/// A document holding `src`'s graph designs and the swatches, patterns, symbols, styles, brushes
|
||||
/// and images their art uses, and nothing else: what a document opened as a library keeps for the
|
||||
/// Graph Column and Graph Marker dialogs. `None` when `src` has no graph designs.
|
||||
pub(crate) fn graph_design_library(src: &Document) -> Option<Document> {
|
||||
if src.graph_designs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let names: Vec<String> = src.graph_designs.iter().map(|g| g.name.clone()).collect();
|
||||
let library = OnceCell::new();
|
||||
let used = designs_used(&Defs::of(src, &library), &names);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let mut d = clip.to_document();
|
||||
// A new document's default swatches and graphic styles give way to the source's of the same
|
||||
// name or id, so a design draws with the source's.
|
||||
let defaults = d.swatches.len().saturating_sub(clip.swatches.len());
|
||||
let mut i = 0;
|
||||
d.swatches.retain(|s| {
|
||||
i += 1;
|
||||
i > defaults || !clip.swatches.iter().any(|c| c.name == s.name)
|
||||
});
|
||||
// The swatch groups are all a new document's.
|
||||
for g in d.swatch_groups.iter_mut() {
|
||||
g.swatches.retain(|s| !clip.swatches.iter().any(|c| c.name == s.name));
|
||||
}
|
||||
let defaults = d.graphic_styles.len().saturating_sub(clip.graphic_styles.len());
|
||||
let mut i = 0;
|
||||
d.graphic_styles.retain(|g| {
|
||||
i += 1;
|
||||
i > defaults || !clip.graphic_styles.iter().any(|c| (c.id != 0 && c.id == g.id) || c.name == g.name)
|
||||
});
|
||||
// The symbols keep their Symbol Options, which the document keeps by name.
|
||||
for (name, options) in &clip.symbol_options {
|
||||
options.give(&mut d, name);
|
||||
}
|
||||
d.title = src.title.clone();
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles,
|
||||
/// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a
|
||||
/// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the
|
||||
/// same name stays as it is, and the art of `src`'s design of that name is not followed. → the
|
||||
/// names of the designs added ([`Imported::added_designs`]): those of `names` `d` lacked, and those
|
||||
/// their art uses; with the symbols added and the designs `d` kept that their art draws with
|
||||
/// ([`Imported::added_symbols`], [`Imported::kept_designs`]). An error, with `d` unchanged, when `d`
|
||||
/// would hold more than [`GraphDesign::MAX`] designs.
|
||||
pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result<Imported> {
|
||||
let library = OnceCell::new();
|
||||
let held = |n: &str| d.graph_designs.iter().any(|x| x.name == n);
|
||||
let followed: Vec<GraphDesign> = src.graph_designs.iter().filter(|g| names.contains(&g.name) || !held(&g.name)).cloned().collect();
|
||||
let used = designs_used(&Defs { graph_designs: &followed, ..Defs::of(src, &library) }, names);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
clip.import_used(d, &used, &SwatchChoices::default(), false)
|
||||
}
|
||||
|
||||
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
|
||||
/// share one namespace).
|
||||
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
|
||||
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
@@ -443,20 +443,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
|
||||
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
|
||||
/// undo step, named as an Ellipse tool drag is.
|
||||
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With
|
||||
/// `anchors: "points"` the circle is a plain path with an anchor at each point
|
||||
/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an
|
||||
/// Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
|
||||
};
|
||||
let key = "anchors";
|
||||
let at_points = match p.get(key).map(Value::as_str) {
|
||||
None | Some(Some("standard")) => false,
|
||||
Some(Some("points")) => true,
|
||||
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))),
|
||||
};
|
||||
let (center, radius) = shapes::circle_through_points(&points)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays through the points.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
let mut out = if at_points {
|
||||
add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))?
|
||||
} else {
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?
|
||||
};
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
|
||||
@@ -1653,6 +1653,17 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for id in &new_ids {
|
||||
super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default());
|
||||
}
|
||||
// A pasted graph whose design the document has under the same name draws with the document's,
|
||||
// in the pasted objects and in the art of the symbols the paste added.
|
||||
if !imported.kept_designs.is_empty() {
|
||||
super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?;
|
||||
super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
|
||||
}
|
||||
// The graphs already in the document that draw with a design the paste added are drawn
|
||||
// again with it; the pasted ones already draw with it.
|
||||
if !imported.added_designs.is_empty() {
|
||||
super::graph::refresh_graphs(d, &imported.added_designs, &new_ids, &imported.added_symbols)?;
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
|
||||
// paste of guides alone keeps them where they were, but onto another artboard or every
|
||||
|
||||
@@ -804,7 +804,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke);
|
||||
leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect()
|
||||
}
|
||||
_ => item.targets(s, p)?,
|
||||
_ => item.targets_for(s, p, !stroke)?,
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Err(EngineError::Other("nothing selected".into()));
|
||||
|
||||
@@ -41,6 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph
|
||||
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, to_csv};
|
||||
pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs};
|
||||
pub use edit::{GraphTypeSubject, graph_type_subject};
|
||||
pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed};
|
||||
pub use generate::calculated_axes;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::data::fmt_value;
|
||||
use super::designs::design_names;
|
||||
use super::designs::{bring_in_for, design_names, from_library, libraries_json};
|
||||
use super::edit::{regenerate, spec_of, target};
|
||||
use super::generate::generate_with;
|
||||
use super::markers::{design_frame, fit_affine};
|
||||
@@ -437,7 +437,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let picked = picked_series(s, p, id, count, C)?;
|
||||
let names = design_names(&s.doc()?.doc);
|
||||
let mut names = design_names(&s.doc()?.doc);
|
||||
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked.clone() };
|
||||
// The column design the picked series (all of them with none picked) share; a design deleted since doesn't count,
|
||||
// as those series draw plain columns.
|
||||
@@ -446,14 +446,21 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let shared = used.first().copied().flatten().filter(|c| used.iter().all(|x| *x == Some(*c))).cloned();
|
||||
let Some(v) = p.get("design") else {
|
||||
let options = shared.clone().unwrap_or_default();
|
||||
return Ok(json!({
|
||||
let mut out = json!({
|
||||
"designs": names,
|
||||
"design": shared.map(|c| c.design),
|
||||
"columnType": options.column_type.id(),
|
||||
"each": options.each,
|
||||
"fractions": options.fractions.id(),
|
||||
}));
|
||||
});
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
return Ok(out);
|
||||
};
|
||||
// A design of a loaded library comes into the document in the same undo step.
|
||||
let library = from_library(s, p, C)?;
|
||||
names.extend(library.as_ref().map(|(_, n)| n.clone()));
|
||||
let design = match v {
|
||||
Value::Null => None,
|
||||
Value::String(n) if names.contains(n) => Some(n.clone()),
|
||||
@@ -485,11 +492,17 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Drawn once on a copy of the document, to refuse designs past the budget before the edit.
|
||||
let mut probe = (*s.doc()?.doc).clone();
|
||||
if let Some((lib, name)) = &library {
|
||||
bring_in_for(&mut probe, lib, name, id, &mut spec)?;
|
||||
}
|
||||
let looks = column_designs(&probe, &spec);
|
||||
if generate_with(&mut probe, &spec, &looks).is_none() {
|
||||
return Err(bad(C, "the design is too big to draw in every column of this graph"));
|
||||
}
|
||||
s.edit("Graph Column", |d, sel| {
|
||||
if let Some((lib, name)) = &library {
|
||||
bring_in_for(d, lib, name, id, &mut spec)?;
|
||||
}
|
||||
regenerate(d, id, spec)?;
|
||||
if !reselect.is_empty() {
|
||||
reselect_series(d, sel, id, &reselect);
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Design…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list)}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with]}",
|
||||
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list), library?: the id or name of a document loaded with swatch.library.load (Other Library…) that holds graph designs, add?: name|[names] of that library's designs (copy them into the document as one undo step, with the swatches, patterns, symbols, styles, brushes and images their art uses, as pasting brings them; a design the document already has under the same name stays as it is) → {added: [names], existing: [names the document already had]}}; library alone → {designs: [the library's names]}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with], libraries?: [{library, name, designs}] (the loaded libraries that hold graph designs)}",
|
||||
has_doc,
|
||||
design
|
||||
),
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Column…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions}",
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used), columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions, libraries?: [{library, name, designs}]}",
|
||||
has_selection,
|
||||
set_column
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Marker…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, seriesIndexes?: [index], design?: name|null} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null}",
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used)} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null, libraries?: [{library, name, designs}]}",
|
||||
has_selection,
|
||||
set_marker
|
||||
),
|
||||
|
||||
@@ -1,44 +1,291 @@
|
||||
use super::edit::regenerate;
|
||||
use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param};
|
||||
use super::edit::{regenerate, regenerate_detached};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::{Arc, Document, GraphDesign, GraphKind, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param};
|
||||
use crate::cmd::clipboard::resources::import_graph_designs;
|
||||
use crate::cmd::swatchlib::{concealed_library_id, shown_library_id};
|
||||
|
||||
/// The document's graph design names, in order.
|
||||
pub(super) fn design_names(d: &Document) -> Vec<String> {
|
||||
d.graph_designs.iter().map(|x| x.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// Whether graph `g` draws a series with design `name`, as its marker or its columns.
|
||||
/// The library param `library` names: a document Other Library… loaded (`swatch.library.load`)
|
||||
/// that holds graph designs, by its id, the id a reply showed for it, or its name (in any case, as
|
||||
/// swatch library names are matched). `None` without
|
||||
/// `library`.
|
||||
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Arc<Document>>> {
|
||||
let key = match p.get("library") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::String(k)) => k.as_str(),
|
||||
Some(_) => {
|
||||
let list = "graph.design";
|
||||
return Err(bad(cmd, format!("`library` is a library id or name (see {list})")));
|
||||
}
|
||||
};
|
||||
let libs = &s.graph_design_libraries;
|
||||
let own = concealed_library_id(s, key);
|
||||
libs.get(key)
|
||||
.or_else(|| own.as_deref().and_then(|id| libs.get(id)))
|
||||
.or_else(|| libs.iter().find(|l| l.name.eq_ignore_ascii_case(key)))
|
||||
.map(|l| Some(l.doc.clone()))
|
||||
.ok_or_else(|| bad(cmd, format!("no library `{key}`")))
|
||||
}
|
||||
|
||||
/// The loaded libraries' designs, as lists show them: `[{library, name, designs}]`; `None` when no
|
||||
/// loaded library holds graph designs.
|
||||
pub(super) fn libraries_json(s: &Session) -> Option<Value> {
|
||||
let libs: Vec<Value> = s
|
||||
.graph_design_libraries
|
||||
.iter()
|
||||
.map(|l| json!({ "library": shown_library_id(s, &l.id), "name": l.name, "designs": design_names(&l.doc) }))
|
||||
.collect();
|
||||
(!libs.is_empty()).then(|| json!(libs))
|
||||
}
|
||||
|
||||
/// The library design `p`'s `design` names, with the library to bring it in from, when `p` gives a
|
||||
/// `library` and the document has no design of that name: the document's own design of a name is
|
||||
/// the one a graph draws with.
|
||||
pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result<Option<(Arc<Document>, String)>> {
|
||||
let Some(lib) = library_param(s, p, cmd)? else { return Ok(None) };
|
||||
let Some(Value::String(n)) = p.get("design") else { return Ok(None) };
|
||||
if s.doc()?.doc.graph_designs.iter().any(|x| x.name == *n) {
|
||||
return Ok(None);
|
||||
}
|
||||
if !lib.graph_designs.iter().any(|x| x.name == *n) {
|
||||
return Err(bad(cmd, format!("no design named `{n}`")));
|
||||
}
|
||||
Ok(Some((lib, n.clone())))
|
||||
}
|
||||
|
||||
/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the
|
||||
/// graphs that already name a design the document lacked: one of `names`, or one their art uses.
|
||||
/// The graphs in the art of the symbols that came in are drawn with the designs the document kept.
|
||||
pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> {
|
||||
let imported = import_graph_designs(lib, d, names)?;
|
||||
if !imported.kept_designs.is_empty() {
|
||||
redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
|
||||
}
|
||||
if !imported.added_designs.is_empty() {
|
||||
refresh_graphs(d, &imported.added_designs, &[], &BTreeSet::new())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`bring_in`] library design `name` for graph `id`, whose new spec is `spec`: when that redraws
|
||||
/// the graph, `spec` takes the rectangle the redraw gave it, so a graph moved or resized since it
|
||||
/// was last drawn stays where it is.
|
||||
pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: super::NodeId, spec: &mut GraphSpec) -> Result<()> {
|
||||
bring_in(d, lib, &[name.to_string()])?;
|
||||
if let Some(g) = d.node(id).and_then(|n| n.extras().graph.as_deref()) {
|
||||
spec.rect = g.rect;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether graph `g` draws a series with design `name`: as the marker of a series drawn with
|
||||
/// markers (every series of a scatter or radar graph, and line series) while Mark Data Points is
|
||||
/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or
|
||||
/// bars.
|
||||
fn draws_with(g: &GraphSpec, name: &str) -> bool {
|
||||
let scatter = g.kind == GraphKind::Scatter;
|
||||
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
// The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank
|
||||
// (a scatter graph's entries are its pairs of series, labeled by the first of each pair).
|
||||
let in_legend = |s: usize| {
|
||||
let entries = if scatter { nser.div_ceil(2) } else { nser };
|
||||
let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str);
|
||||
g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label)
|
||||
};
|
||||
// Point markers use the same range of designs: a scatter graph plots a pair of series for each.
|
||||
let plotted = if scatter { nser.div_ceil(2) } else { nser };
|
||||
let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s));
|
||||
let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line);
|
||||
let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar);
|
||||
g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s))
|
||||
|| g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s))
|
||||
}
|
||||
|
||||
/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or
|
||||
/// not the series draws with it.
|
||||
fn names_design(g: &GraphSpec, name: &str) -> bool {
|
||||
g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name)
|
||||
}
|
||||
|
||||
/// Regenerate the graphs whose series use design `name` (it was added or removed).
|
||||
/// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers,
|
||||
/// in opacity-mask art and in symbols' art.
|
||||
fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> {
|
||||
let mut ids = vec![];
|
||||
refresh_graphs(d, &BTreeSet::from([name.to_string()]), &[], &BTreeSet::new())
|
||||
}
|
||||
|
||||
/// Regenerate the graphs that draw a series with one of the designs `names`, in the layers, in
|
||||
/// opacity-mask art and in symbols' art, except those in the subtrees of `skip` and in the art of
|
||||
/// symbols `skip_symbols`.
|
||||
pub(crate) fn refresh_graphs(d: &mut Document, names: &BTreeSet<String>, skip: &[super::NodeId], skip_symbols: &BTreeSet<String>) -> Result<()> {
|
||||
let mut skipped = std::collections::HashSet::new();
|
||||
for n in skip.iter().filter_map(|id| d.node(*id)) {
|
||||
n.walk(&mut |m| {
|
||||
skipped.insert(m.id);
|
||||
});
|
||||
}
|
||||
let (mut ids, mut masked) = (vec![], vec![]);
|
||||
d.walk(|n| {
|
||||
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) {
|
||||
if skipped.contains(&n.id) {
|
||||
return;
|
||||
}
|
||||
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, names)) {
|
||||
masked.push(n.id);
|
||||
}
|
||||
});
|
||||
for id in ids {
|
||||
if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) {
|
||||
regenerate(d, id, spec)?;
|
||||
}
|
||||
}
|
||||
// The graphs in objects' opacity-mask art.
|
||||
for id in masked {
|
||||
let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue };
|
||||
redraw_in(d, &mut art, names);
|
||||
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
|
||||
mask.art = Arc::new(art);
|
||||
}
|
||||
}
|
||||
// And the graphs in symbols' art, which instances draw.
|
||||
let symbols: BTreeSet<String> = d.symbols.iter().map(|s| s.name.clone()).filter(|s| !skip_symbols.contains(s)).collect();
|
||||
redraw_symbols_with_designs(d, &symbols, names);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The designs no graph's series draw with (Select Unused).
|
||||
/// [`redraw_in`] for the clipboard: graph art `n`, outside the document, drawn again with `d`'s
|
||||
/// designs `names`.
|
||||
pub(crate) fn redraw_detached(d: &mut Document, n: &mut Node, names: &BTreeSet<String>) {
|
||||
if holds(n, names) {
|
||||
redraw_in(d, n, names);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
|
||||
/// with one of the designs `names`.
|
||||
pub(crate) fn holds_designs(n: &Node, names: &BTreeSet<String>) -> bool {
|
||||
holds(n, names)
|
||||
}
|
||||
|
||||
/// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs
|
||||
/// `names`: pasted graphs, after the paste kept the document's own designs of those names.
|
||||
pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet<String>) -> Result<()> {
|
||||
for id in ids {
|
||||
let Some(mut n) = d.node(*id).filter(|n| holds(n, names)).cloned() else { continue };
|
||||
redraw_in(d, &mut n, names);
|
||||
*d.node_mut(*id).ok_or(super::EngineError::NoNode(*id))? = n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Draw the graphs in the art of symbols `symbols` again that draw a series with one of the
|
||||
/// designs `names`: graphs of the symbols a paste added, after the paste kept the document's own
|
||||
/// designs of those names.
|
||||
pub(crate) fn redraw_symbols_with_designs(
|
||||
d: &mut Document,
|
||||
symbols: &std::collections::BTreeSet<String>,
|
||||
names: &std::collections::BTreeSet<String>,
|
||||
) {
|
||||
for i in 0..d.symbols.len() {
|
||||
let Some(s) = d.symbols.get(i).filter(|s| symbols.contains(&s.name) && holds(&s.art, names)) else { continue };
|
||||
let old = s.art.clone();
|
||||
let mut art = (*old).clone();
|
||||
redraw_in(d, &mut art, names);
|
||||
let Some(s) = d.symbols.get_mut(i) else { continue };
|
||||
s.art = Arc::new(art);
|
||||
// Instances' changes to parts the redraw replaced are dropped.
|
||||
let name = s.name.clone();
|
||||
crate::cmd::symboledit::follow_art_change(d, &name, &old);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
|
||||
/// with one of the designs `names`.
|
||||
fn holds(n: &Node, names: &std::collections::BTreeSet<String>) -> bool {
|
||||
let mut found = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
found |= m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name)));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Redraw the graphs of `n`'s subtree, the art of opacity masks included, that draw a series with
|
||||
/// one of the designs `names`.
|
||||
fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet<String>) {
|
||||
if let Some(mut art) = n.extras().mask.as_deref().filter(|m| holds(&m.art, names)).map(|m| (*m.art).clone()) {
|
||||
redraw_in(d, &mut art, names);
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
mask.art = Arc::new(art);
|
||||
}
|
||||
}
|
||||
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
|
||||
regenerate_detached(d, n);
|
||||
return;
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut().filter(|c| holds(c, names)) {
|
||||
redraw_in(d, Arc::make_mut(c), names);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The designs no graph's series draw with (Select Unused): graphs in the layers, in opacity-mask
|
||||
/// art and in symbols' art count.
|
||||
fn unused_designs(d: &Document) -> Vec<String> {
|
||||
let mut used = std::collections::HashSet::new();
|
||||
d.walk(|n| {
|
||||
let mut note = |n: &Node| {
|
||||
if let Some(g) = n.extras().graph.as_deref() {
|
||||
used.extend(g.series_markers.iter().flatten().cloned());
|
||||
used.extend(g.series_columns.iter().flatten().map(|c| c.design.clone()));
|
||||
}
|
||||
});
|
||||
};
|
||||
for art in d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(art, &mut note);
|
||||
}
|
||||
d.graph_designs.iter().map(|x| x.name.clone()).filter(|n| !used.contains(n)).collect()
|
||||
}
|
||||
|
||||
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that names design
|
||||
/// `name` for a series ([`names_design`]).
|
||||
fn names_in(n: &Node, name: &str) -> bool {
|
||||
let mut found = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
found |= m.extras().graph.as_deref().is_some_and(|g| names_design(g, name));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Graph `g`'s series that name design `old` name `new` instead.
|
||||
fn rename_series(g: &mut GraphSpec, old: &str, new: &str) {
|
||||
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
|
||||
*m = new.to_string();
|
||||
}
|
||||
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
|
||||
c.design = new.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// [`rename_series`] for the graphs of `n`'s subtree, the art of opacity masks included.
|
||||
fn rename_in(n: &mut Node, old: &str, new: &str) {
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()).filter(|m| names_in(&m.art, old)) {
|
||||
rename_in(Arc::make_mut(&mut mask.art), old, new);
|
||||
}
|
||||
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
|
||||
rename_series(g, old, new);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut().filter(|c| names_in(c, old)) {
|
||||
rename_in(Arc::make_mut(c), old, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Design names from param `key`: one name or a list of names.
|
||||
fn names_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Vec<String>>> {
|
||||
match p.get(key) {
|
||||
@@ -105,22 +352,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(x) = d.graph_designs.iter_mut().find(|x| x.name == old) {
|
||||
x.name = new.clone();
|
||||
}
|
||||
let mut graphs = vec![];
|
||||
let (mut graphs, mut masked) = (vec![], vec![]);
|
||||
d.walk(|n| {
|
||||
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, &old)) {
|
||||
if n.extras().graph.as_deref().is_some_and(|g| names_design(g, &old)) {
|
||||
graphs.push(n.id);
|
||||
}
|
||||
if n.extras().mask.as_deref().is_some_and(|m| names_in(&m.art, &old)) {
|
||||
masked.push(n.id);
|
||||
}
|
||||
});
|
||||
for id in graphs {
|
||||
if let Some(g) = d.node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) {
|
||||
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
|
||||
*m = new.clone();
|
||||
}
|
||||
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
|
||||
c.design = new.clone();
|
||||
}
|
||||
rename_series(g, &old, &new);
|
||||
}
|
||||
}
|
||||
// The graphs in opacity-mask art and in symbols' art follow too, their art as it is.
|
||||
for id in masked {
|
||||
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
|
||||
rename_in(Arc::make_mut(&mut mask.art), &old, &new);
|
||||
}
|
||||
}
|
||||
for s in d.symbols.iter_mut().filter(|s| names_in(&s.art, &old)) {
|
||||
rename_in(Arc::make_mut(&mut s.art), &old, &new);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({ "name": to }));
|
||||
@@ -159,7 +413,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
// Designs from a document loaded as a library: those the document has under the same name stay
|
||||
// as they are.
|
||||
if let Some(mut wanted) = names_param(p, "add", C)? {
|
||||
let lib = library_param(s, p, C)?.ok_or_else(|| bad(C, "missing `library`"))?;
|
||||
if let Some(n) = wanted.iter().find(|n| !lib.graph_designs.iter().any(|x| x.name == **n)) {
|
||||
return Err(bad(C, format!("no design named `{n}`")));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
wanted.retain(|n| seen.insert(n.clone()));
|
||||
let (existing, added): (Vec<String>, Vec<String>) = wanted.into_iter().partition(|n| taken(s, n));
|
||||
if !added.is_empty() {
|
||||
s.edit("New Design", |d, _| bring_in(d, &lib, &added))?;
|
||||
}
|
||||
return Ok(json!({ "added": added, "existing": existing }));
|
||||
}
|
||||
if let Some(lib) = library_param(s, p, C)? {
|
||||
return Ok(json!({ "designs": design_names(&lib) }));
|
||||
}
|
||||
// The list, with the designs no graph draws with (Select Unused picks those).
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(json!({ "designs": design_names(d), "unused": unused_designs(d) }))
|
||||
let mut out = json!({ "designs": design_names(d), "unused": unused_designs(d) });
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -109,6 +109,33 @@ pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) {
|
||||
/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them).
|
||||
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
carry_moves(n, &mut spec);
|
||||
let children = generate(d, &spec);
|
||||
spec.placed = children_bounds(&children);
|
||||
spec.placed_art = art_bounds(&children);
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
n.extras_mut().graph = Some(Box::new(spec));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`regenerate`] graph `n` from its own spec, where `n` is outside `d`'s layers (in a symbol's art).
|
||||
pub(super) fn regenerate_detached(d: &mut Document, n: &mut Node) {
|
||||
let Some(mut spec) = n.extras().graph.as_deref().cloned() else { return };
|
||||
carry_moves(n, &mut spec);
|
||||
let children = generate(d, &spec);
|
||||
spec.placed = children_bounds(&children);
|
||||
spec.placed_art = art_bounds(&children);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
n.extras_mut().graph = Some(Box::new(spec));
|
||||
}
|
||||
|
||||
/// Adjust `spec`'s plot rect for any move or scale of graph `n` since its last generation.
|
||||
fn carry_moves(n: &Node, spec: &mut GraphSpec) {
|
||||
if let Some((placed, now)) = measured(n)
|
||||
&& placed.width() > 1e-9
|
||||
&& placed.height() > 1e-9
|
||||
@@ -119,15 +146,6 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
|
||||
* Affine::translate(-placed.origin().to_vec2());
|
||||
spec.rect = a.transform_rect_bbox(spec.rect);
|
||||
}
|
||||
let children = generate(d, &spec);
|
||||
spec.placed = children_bounds(&children);
|
||||
spec.placed_art = art_bounds(&children);
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
n.extras_mut().graph = Some(Box::new(spec));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::designs::design_names;
|
||||
use super::designs::{bring_in_for, design_names, from_library, libraries_json};
|
||||
use super::edit::{regenerate, spec_of, target};
|
||||
use super::series::{picked_series, reselect_series};
|
||||
use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json};
|
||||
@@ -55,7 +55,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let picked = picked_series(s, p, id, count, C)?;
|
||||
let names = design_names(&s.doc()?.doc);
|
||||
let mut names = design_names(&s.doc()?.doc);
|
||||
let Some(v) = p.get("design") else {
|
||||
// The design the picked series (all of them with none picked) share, or null.
|
||||
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked };
|
||||
@@ -63,8 +63,15 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let used: Vec<Option<&String>> =
|
||||
all.iter().map(|i| spec.series_markers.get(*i).and_then(Option::as_ref).filter(|n| names.contains(n))).collect();
|
||||
let shared = used.first().copied().flatten().filter(|d| used.iter().all(|x| *x == Some(*d)));
|
||||
return Ok(json!({ "designs": names, "design": shared }));
|
||||
let mut out = json!({ "designs": names, "design": shared });
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
return Ok(out);
|
||||
};
|
||||
// A design of a loaded library comes into the document in the same undo step.
|
||||
let library = from_library(s, p, C)?;
|
||||
names.extend(library.as_ref().map(|(_, n)| n.clone()));
|
||||
let design = match v {
|
||||
Value::Null => None,
|
||||
Value::String(n) if names.contains(n) => Some(n.clone()),
|
||||
@@ -83,10 +90,21 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
while spec.series_markers.last().is_some_and(Option::is_none) {
|
||||
spec.series_markers.pop();
|
||||
}
|
||||
if marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)) > MARKER_BUDGET {
|
||||
let cost = match &library {
|
||||
Some((lib, name)) => {
|
||||
let mut probe = (*s.doc()?.doc).clone();
|
||||
bring_in_for(&mut probe, lib, name, id, &mut spec)?;
|
||||
marker_cost(&spec, &marker_designs(&probe, &spec))
|
||||
}
|
||||
None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)),
|
||||
};
|
||||
if cost > MARKER_BUDGET {
|
||||
return Err(bad(C, "the design is too big to draw at every data point of this graph"));
|
||||
}
|
||||
s.edit("Graph Marker", |d, sel| {
|
||||
if let Some((lib, name)) = &library {
|
||||
bring_in_for(d, lib, name, id, &mut spec)?;
|
||||
}
|
||||
regenerate(d, id, spec)?;
|
||||
if !reselect.is_empty() {
|
||||
reselect_series(d, sel, id, &reselect);
|
||||
|
||||
@@ -5469,6 +5469,964 @@ fn graph_designs_are_saved_pasted_and_deleted() {
|
||||
assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
}
|
||||
|
||||
/// Graph design "Coin" in the active document: a 10 × 10 rectangle filled with global swatch "Gold".
|
||||
fn save_coin_design(s: &mut Session) {
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": "#d4a017", "global": true})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Gold", "ids": [r]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
|
||||
}
|
||||
|
||||
/// Load a saved document holding [`save_coin_design`]'s design as a swatch library (Other
|
||||
/// Library…) → its id.
|
||||
fn load_coin_library(s: &mut Session) -> String {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut src);
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Coins.vectorcraft"});
|
||||
let r = s.execute("swatch.library.load", &p).unwrap();
|
||||
assert_eq!(r["graphDesigns"], 1);
|
||||
r["library"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Whether some object of `n` is filled with a colour linked to swatch `name`.
|
||||
fn paints_with_swatch(n: &vectorcraft_doc::Node, name: &str) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |m| found |= m.appearance.items.iter().any(|it| matches!(it.paint(), Paint::Solid { swatch: Some(w), .. } if w == name)));
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// The Column dialog's list: none of the document's, Coin from the library.
|
||||
let q = s.execute("graph.column", &json!({})).unwrap();
|
||||
assert_eq!((q["designs"].clone(), q["libraries"][0]["library"].clone()), (json!([]), json!(lib)));
|
||||
assert_eq!(q["libraries"][0]["designs"], json!(["Coin"]));
|
||||
assert!(s.execute("graph.column", &json!({"design": "Coin"})).is_err(), "not the document's");
|
||||
let steps = undo_len(&s);
|
||||
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
assert_eq!(undo_len(&s), steps + 1, "one undo step");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
|
||||
assert!(d.swatch("Gold").is_some_and(|w| w.global), "the swatch the design's art uses comes along");
|
||||
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold"));
|
||||
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "the columns draw the design");
|
||||
// Undo takes the design, its swatch and the columns' design out together.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.is_empty() && d.swatch("Gold").is_none() && spec(&s, id).series_columns.is_empty());
|
||||
// Marker takes them too.
|
||||
let line = graph(&mut s, "line");
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
assert_eq!(spec(&s, line).series_markers, [Some("Coin".to_string()), Some("Coin".to_string())]);
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
// An unknown library or design, and a library that is not a string, are refused.
|
||||
for p in [json!({"design": "Coin", "library": "Nope"}), json!({"design": "Nope", "library": lib}), json!({"design": "Coin", "library": 3})] {
|
||||
assert!(s.execute("graph.column", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_design_applied_to_a_moved_graph_that_names_it_keeps_the_graph_in_place() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// A library's name works in any case, as swatch library names do.
|
||||
assert_eq!(s.execute("graph.design", &json!({"library": "COINS"})).unwrap(), json!({"designs": ["Coin"]}));
|
||||
for (kind, cmd) in [("line", "graph.marker"), ("column", "graph.column")] {
|
||||
// The graph names design "Coin", which the document no longer has, and is moved after.
|
||||
save_design(&mut s, "Coin");
|
||||
let id = graph(&mut s, kind);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute(cmd, &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
let rect = spec(&s, id).rect;
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap();
|
||||
s.execute(cmd, &json!({"id": id.0, "design": "Coin", "library": lib})).unwrap();
|
||||
let now = spec(&s, id).rect;
|
||||
assert!((now.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (now.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{cmd}: {now:?}");
|
||||
assert!((now.width() - rect.width()).abs() < 1e-6 && (now.height() - rect.height()).abs() < 1e-6, "{cmd}: {now:?}");
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_the_document_has_under_the_same_name_stays_as_it_is() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
|
||||
assert_eq!(s.execute("graph.design", &json!({"library": lib})).unwrap(), json!({"designs": ["Coin"]}));
|
||||
let steps = undo_len(&s);
|
||||
let r = s.execute("graph.design", &json!({"library": lib, "add": ["Coin", "Coin"]})).unwrap();
|
||||
assert_eq!(r, json!({"added": [], "existing": ["Coin"]}));
|
||||
assert_eq!(undo_len(&s), steps, "nothing changed: no undo step");
|
||||
// Applying it with the library draws with the document's own design.
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
|
||||
assert!(d.swatch("Gold").is_none());
|
||||
assert!(s.execute("graph.design", &json!({"add": "Coin"})).is_err(), "no library");
|
||||
assert!(s.execute("graph.design", &json!({"library": lib, "add": "Nope"})).is_err());
|
||||
assert!(s.execute("graph.design", &json!({"library": lib, "add": 4})).is_err());
|
||||
// The document without it takes it as one undo step.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let r = s.execute("graph.design", &json!({"library": "Coins", "add": "Coin"})).unwrap();
|
||||
assert_eq!(r, json!({"added": ["Coin"], "existing": []}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.graph_designs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_brings_the_designs_its_series_draw_with() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
|
||||
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold") && d.swatch("Gold").is_some());
|
||||
// A data edit redraws the pasted graph with the design.
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
s.execute("graph.setData", &json!({"id": pasted.0, "csv": ",A\nQ1,4\nQ2,6"})).unwrap();
|
||||
assert!(paints_with_swatch(series(s.doc().unwrap().doc.node(pasted).unwrap(), 0), "Gold"));
|
||||
// A document with its own design of that name keeps it.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
|
||||
// The pasted graph is drawn with that design straight away.
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
// The document's design is a rectangle and an ellipse, the pasted one a rectangle alone: each
|
||||
// column and the legend swatch hold two paths.
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_the_document_keeps_brings_none_of_the_pasted_designs_resources() {
|
||||
// A column graph whose spec names marker design "Coin", which only line series draw: the
|
||||
// graph's own art does not use the design's swatch.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
|
||||
assert!(spec(&s, id).series_markers.iter().any(|m| m.as_deref() == Some("Coin")));
|
||||
assert!(!paints_with_swatch(s.doc().unwrap().doc.node(id).unwrap(), "Gold"));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document with its own "Coin" keeps it and takes nothing the pasted design's art uses.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_none());
|
||||
// A document without one takes the design and its swatch.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_that_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
assert!(spec(&s, id).series_columns.iter().flatten().any(|c| c.design == "Coin"), "the graph still names it");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_comes_in_renamed() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff0000", "global": true})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [r]})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
// An edit of the graph's art that drawing the graph again would not keep.
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A copy of the document holds the same design; its "Ink" is another color, so the pasted
|
||||
// rectangle's swatch takes the document's color, or with "add" comes in renamed.
|
||||
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
|
||||
s.execute("select.set", &json!({"ids": [id.0, r]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap();
|
||||
for conflict in ["merge", "add"] {
|
||||
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
|
||||
let ink_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Ink"));
|
||||
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
|
||||
assert_eq!((r["merged"].clone(), ink_renamed), expected, "{conflict}: {r}");
|
||||
let st = s.doc().unwrap();
|
||||
let d = &st.doc;
|
||||
let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap();
|
||||
let names: Vec<Option<String>> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
|
||||
assert_eq!(names[0].as_deref(), Some("Mine"), "{conflict}: not drawn again: {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_is_drawn_again_when_its_designs_svg_filter_comes_in_under_another_name() {
|
||||
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3" dy="3"/></filter>"#;
|
||||
const SHIFT_MORE: &str = r#"<filter id="Shift"><feOffset dx="9" dy="9"/></filter>"#;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("svgFilter.apply", &json!({"name": "Shift", "ids": [r]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A copy of the document holds the same design, but its "Shift" filter draws otherwise, so the
|
||||
// pasted graph's filter keeps its own definition under another name.
|
||||
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap();
|
||||
s.execute("svgFilter.define", &json!({"xml": SHIFT_MORE, "replace": "Shift"})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let pasted = st.selection.objects.to_vec()[0];
|
||||
let names: Vec<Option<String>> = series(st.doc.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
|
||||
assert_ne!(names[0].as_deref(), Some("Mine"), "drawn again with the document's design: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_that_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document whose "Coin" is a rectangle and an ellipse: the symbol's graph draws with it.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
|
||||
let mut graphs = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let columns: Vec<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// A graph that names "Coin", which the document no longer has, kept as a symbol's art.
|
||||
save_design(&mut s, "Coin");
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Chart").unwrap().art;
|
||||
let mut graphs = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_brought_in_from_a_library_leaves_a_scatter_graph_that_names_it_for_a_slot_it_does_not_plot() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// Four data columns plot two series, so marker slot 2 is never drawn.
|
||||
let id = make(&mut s, "scatter", ",y1,x1,y2,x2\nP,1,10,2,20\nQ,3,11,4,22");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(spec(&s, id).mark_points, "Mark Data Points is on");
|
||||
s.execute("graph.marker", &json!({"design": "Coin", "library": lib, "seriesIndexes": [2]})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_markers.get(2).cloned().flatten().as_deref(), Some("Coin"));
|
||||
// An edit of the graph's art that drawing the graph again would not keep.
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let names: Vec<Option<String>> = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
|
||||
assert_eq!(names[0].as_deref(), Some("Mine"), "not drawn again: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_a_library_design_brings_draws_its_graph_with_the_documents_design_it_keeps() {
|
||||
// The library's design "A" holds an instance of symbol "Chart", whose graph draws columns with
|
||||
// the library's "B": a rectangle and an ellipse.
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut src, "B");
|
||||
let id = graph(&mut src, "column");
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
src.execute("graph.column", &json!({"design": "B"})).unwrap();
|
||||
let instance = src.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "A"})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Lib.vectorcraft"});
|
||||
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
|
||||
// The document's own "B" is a single rectangle, and stays.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "B"})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "A"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.len(), 2, "A came in and B stayed");
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
|
||||
let mut graphs = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let columns: Vec<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [1, 1, 1, 1], "drawn with the document's B");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_brought_in_from_a_library_redraws_a_graph_in_an_opacity_mask() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let mut graphs = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(s.doc().unwrap().doc.node(NodeId(r)).unwrap(), &mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_drops_its_changes_to_graph_parts_a_design_change_redraws() {
|
||||
use vectorcraft_doc::symbol_overrides::SymbolOverride;
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap();
|
||||
let instance = NodeId(instance);
|
||||
// A change to the graph itself, and one to a part of it that drawing it again replaces.
|
||||
let changes = vec![
|
||||
SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() },
|
||||
SymbolOverride { path: vec![0], opacity: Some(0.25), ..Default::default() },
|
||||
];
|
||||
s.edit("Change", |d, _| {
|
||||
if let Some(n) = d.node_mut(instance) {
|
||||
n.extras_mut().symbol_overrides = changes;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let kept = s.doc().unwrap().doc.node(instance).unwrap().extras().symbol_overrides.clone();
|
||||
assert_eq!(kept.iter().map(|o| o.path.clone()).collect::<Vec<_>>(), [Vec::<u32>::new()], "{kept:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_in_an_opacity_mask_draws_with_the_documents_design_when_pasted() {
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let mask_graph = |n: &vectorcraft_doc::Node| {
|
||||
let mut graphs = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
graphs.into_iter().next().expect("the masked graph")
|
||||
};
|
||||
// In a symbol's art and among the pasted objects.
|
||||
for in_symbol in [true, false] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let copied = if in_symbol { s.execute("symbol.new", &json!({"name": "Masked", "ids": [r]})).unwrap()["id"].as_u64().unwrap() } else { r };
|
||||
s.execute("select.set", &json!({"ids": [copied]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let g = if in_symbol {
|
||||
mask_graph(&st.doc.symbols.iter().find(|x| x.name == "Masked").expect("the symbol came in").art)
|
||||
} else {
|
||||
mask_graph(st.doc.node(st.selection.objects.to_vec()[0]).unwrap())
|
||||
};
|
||||
let columns: Vec<usize> = series(&g, 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "in a symbol: {in_symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// Made again under the same name as a rectangle and an ellipse.
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now");
|
||||
}
|
||||
|
||||
/// The graphs in `n`'s subtree, those in opacity-mask art included.
|
||||
fn graphs_in(n: &vectorcraft_doc::Node) -> Vec<vectorcraft_doc::Node> {
|
||||
let mut graphs = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
graphs
|
||||
}
|
||||
|
||||
/// Load a saved document holding [`save_coin_design`]'s "Coin" and design "Chart", an instance of
|
||||
/// symbol "Plot" whose column graph names "Coin" as its columns (`columns`) or only as a marker
|
||||
/// its columns do not draw, as a swatch library → its id.
|
||||
fn load_chart_library(s: &mut Session, columns: bool) -> String {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut src);
|
||||
let id = graph(&mut src, "column");
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
src.execute(if columns { "graph.column" } else { "graph.marker" }, &json!({"design": "Coin"})).unwrap();
|
||||
let instance = src.execute("symbol.new", &json!({"name": "Plot", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Chart"})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Charts.vectorcraft"});
|
||||
s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_design_brings_none_of_the_resources_of_a_design_the_document_keeps() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_chart_library(&mut s, false);
|
||||
// The document keeps its own "Coin": nothing the library's "Coin" uses comes in.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.symbols.iter().any(|x| x.name == "Plot"), "the design's symbol came in");
|
||||
assert!(d.swatch("Gold").is_none());
|
||||
// A document without one takes the design and its swatch.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.iter().any(|x| x.name == "Coin") && d.swatch("Gold").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_a_library_design_brings_along_redraws_the_graphs_that_name_it() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_chart_library(&mut s, true);
|
||||
// A graph that names "Coin", which the document no longer has.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
let r = s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
|
||||
assert_eq!(r, json!({"added": ["Chart"], "existing": []}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "drawn with the library's Coin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_that_adds_a_design_redraws_the_documents_graphs_that_name_it_and_not_the_pasted_ones() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
// An edit of the copied graph's art that drawing it again would not keep.
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document whose graph names "Coin", which it no longer has.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let own = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert!(paints_with_swatch(series(st.doc.node(own).unwrap(), 0), "Gold"), "drawn with the pasted Coin");
|
||||
let pasted = st.selection.objects.to_vec()[0];
|
||||
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
|
||||
assert_eq!(first.as_deref(), Some("Mine"), "the pasted graph is not drawn again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_that_adds_a_marker_design_a_graph_does_not_show_leaves_that_graph_as_it_is() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A line graph whose series name "Coin", which the document no longer has, as a marker that
|
||||
// Mark Data Points does not show, with no legend or with a legend that has no entry for them.
|
||||
for (legend, csv) in [(false, ",2024,2025\nQ1,3,2\nQ2,5,4"), (true, ",,\nQ1,3,2\nQ2,5,4")] {
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let p = json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv});
|
||||
let own = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.setType", &json!({"id": own.0, "markPoints": false, "legend": legend})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
let mark = series(s.doc().unwrap().doc.node(own).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.iter().any(|x| x.name == "Coin"), "legend {legend}: the paste added Coin");
|
||||
let first = series(d.node(own).unwrap(), 0).children().unwrap()[0].name.clone();
|
||||
assert_eq!(first.as_deref(), Some("Mine"), "legend {legend}: not drawn again");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_pasted_twice_with_a_graph_the_document_draws_again_is_added_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document whose "Coin" is other art: the first paste draws the symbol's graph with it.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
// The paths of each column of the symbol's graph: 2 for the document's Coin, 1 for the copied one.
|
||||
let columns = |s: &Session| {
|
||||
let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone();
|
||||
let graph = graphs_in(&art).remove(0);
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
series(&graph, 0).children().unwrap().iter().map(|n| paths(n)).collect::<Vec<usize>>()
|
||||
};
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(columns(&s), [2, 2, 2, 2], "the first paste draws with the document's Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
|
||||
assert_eq!(names, ["Chart"]);
|
||||
assert_eq!(columns(&s), [2, 2, 2, 2], "drawn with the document's Coin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_pasted_twice_whose_designs_swatch_takes_the_documents_color_is_added_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
// A copy of the document holds the same "Coin"; its "Gold" is another color.
|
||||
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
for conflict in ["merge", "add"] {
|
||||
s.execute("document.open", &json!({"name": format!("{conflict}.vectorcraft"), "dataBase64": saved})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Gold", "color": "#0000ff"})).unwrap();
|
||||
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
|
||||
let gold_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Gold"));
|
||||
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
|
||||
assert_eq!((r["merged"].clone(), gold_renamed), expected, "{conflict}: {r}");
|
||||
s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
|
||||
assert_eq!(names, ["Chart"], "{conflict}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_that_only_names_a_kept_design_as_an_undrawn_marker_keeps_its_art() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
// A column graph whose series name "Coin" as a marker, which columns do not draw.
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let pasted = st.selection.objects.to_vec()[0];
|
||||
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
|
||||
assert_eq!(first.as_deref(), Some("Mine"), "not drawn again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_design_renames_it_in_the_graphs_of_symbols_and_opacity_masks() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let in_symbol = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [in_symbol.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol.0]})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
let masked = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let before = graphs_in(&s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
|
||||
s.execute("graph.design", &json!({"rename": "Coin", "to": "Medal"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let symbol = graphs_in(&d.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
|
||||
let mask = graphs_in(d.node(NodeId(r)).unwrap());
|
||||
for (where_, g) in [("symbol", &symbol[0]), ("mask", &mask[0])] {
|
||||
let designs: Vec<String> = g.extras().graph.as_deref().unwrap().series_columns.iter().flatten().map(|c| c.design.clone()).collect();
|
||||
assert!(!designs.is_empty() && designs.iter().all(|n| n == "Medal"), "{where_}: {designs:?}");
|
||||
}
|
||||
assert_eq!(symbol[0].children(), before[0].children(), "the symbol's graph keeps its art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_only_a_graph_in_a_symbol_or_a_mask_draws_with_is_not_unused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
save_design(&mut s, "Pill");
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
let masked = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Pill"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("graph.design", &json!({})).unwrap()["unused"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user");
|
||||
let mut s = Session::new();
|
||||
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let loaded = load_coin_library(&mut s);
|
||||
// The User Defined copy is a swatch file: it holds the swatches alone.
|
||||
let copy = s.execute("swatch.library.copyToUser", &json!({"library": loaded})).unwrap()["library"].as_str().unwrap().to_string();
|
||||
assert_ne!(copy, loaded);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let libraries = s.execute("graph.design", &json!({})).unwrap()["libraries"].clone();
|
||||
assert_eq!(libraries, json!([{"library": loaded, "name": libraries[0]["name"], "designs": ["Coin"]}]));
|
||||
assert_eq!(s.execute("graph.design", &json!({"library": loaded})).unwrap(), json!({"designs": ["Coin"]}));
|
||||
assert!(s.execute("graph.design", &json!({"library": copy})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-size");
|
||||
let path = dir.join("big.vectorcraft");
|
||||
let f = std::fs::File::create(&path).unwrap();
|
||||
f.set_len(((256 << 20) + 1) as u64).unwrap();
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("swatch.library.load", &json!({"path": path})).unwrap_err().to_string();
|
||||
assert!(e.contains("larger than 256 MB"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_with_graph_designs_and_no_swatches_loads_for_its_designs() {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut src, "Pill");
|
||||
let mut d = (*src.doc().unwrap().doc).clone();
|
||||
d.swatches.clear();
|
||||
d.swatch_groups.clear();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Pills.vectorcraft"});
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("swatch.library.load", &p).unwrap();
|
||||
assert_eq!((r["count"].clone(), r["graphDesigns"].clone()), (json!(0), json!(1)));
|
||||
// Without graph designs it has nothing to offer.
|
||||
d.graph_designs.clear();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Bare.vectorcraft"});
|
||||
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("has no swatches of its own"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// A default swatch the source made global and gave another color, used by a design.
|
||||
let name = src.doc().unwrap().doc.swatches.iter().find(|w| !w.name.starts_with('[')).unwrap().name.clone();
|
||||
let mine = Paint::solid(vectorcraft_color::Color::rgb(0.1, 0.7, 0.3));
|
||||
let (n, p) = (name.clone(), mine.clone());
|
||||
src.edit("Change", move |d, _| {
|
||||
if let Some(w) = d.swatches.iter_mut().find(|w| w.name == n) {
|
||||
w.paint = p;
|
||||
w.global = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("paint.setFill", &json!({"swatch": name, "ids": [r]})).unwrap();
|
||||
src.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Green"})).unwrap();
|
||||
let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap();
|
||||
let named: Vec<_> = lib.swatches.iter().filter(|w| w.name == name).collect();
|
||||
assert_eq!(named.len(), 1, "one swatch named {name}");
|
||||
assert_eq!(named[0].paint, mine);
|
||||
// And one named like a swatch in a default group.
|
||||
let grouped = src.doc().unwrap().doc.swatch_groups.iter().flat_map(|g| g.swatches.iter()).next().unwrap().name.clone();
|
||||
let (n, p) = (grouped.clone(), mine.clone());
|
||||
src.edit("Change", move |d, _| {
|
||||
if let Some(w) = d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()).find(|w| w.name == n) {
|
||||
w.paint = p;
|
||||
w.global = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = src.execute("shape.rectangle", &json!({"x": 650, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("paint.setFill", &json!({"swatch": grouped, "ids": [r]})).unwrap();
|
||||
src.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Grouped"})).unwrap();
|
||||
let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap();
|
||||
let all: Vec<_> = lib.swatches.iter().chain(lib.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter(|w| w.name == grouped).collect();
|
||||
assert_eq!(all.len(), 1, "one swatch named {grouped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() {
|
||||
// With a limit of 3 bytes: text and base64 of 3 bytes pass, and of 4 bytes are refused.
|
||||
let too_big = |p: serde_json::Value| crate::cmd::swatchlib::library_too_big(&p, "swatch.library.load", 3).unwrap();
|
||||
assert!(!too_big(json!({"data": "abc"})));
|
||||
assert!(too_big(json!({"data": "abcd"})));
|
||||
let b64 = |n: usize| vectorcraft_format::base64_encode(&vec![7u8; n]);
|
||||
assert!(!too_big(json!({"dataBase64": b64(3)})));
|
||||
assert!(too_big(json!({"dataBase64": b64(4)})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_library_file_is_read_no_further_than_the_size_limit() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-bound");
|
||||
let path = dir.join("grown.gpl");
|
||||
std::fs::write(&path, [b'a'; 9]).unwrap();
|
||||
let mut s = Session::new();
|
||||
let p = json!({"path": path});
|
||||
let parsed = |_: &[u8], _: &str| Err(crate::EngineError::Other("parsed".into()));
|
||||
// A file that grew past the limit after the size check is refused when it is read.
|
||||
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(8), parsed).unwrap_err().to_string();
|
||||
assert!(e.contains("larger than"), "{e}");
|
||||
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(9), parsed).unwrap_err().to_string();
|
||||
assert!(e.contains("parsed"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_the_head_of_a_swatch_library_file_stops_at_the_limit() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-head");
|
||||
let path = dir.join("long.gpl");
|
||||
std::fs::write(&path, vec![b'a'; 1 << 20]).unwrap();
|
||||
// The read the limit check relies on returns the bytes up to one past the limit, not the file.
|
||||
let head = crate::cmd::fileio::read_file_head(&path.to_string_lossy(), 9).unwrap();
|
||||
assert_eq!(head.len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_design_brings_its_symbols_with_their_symbol_options() {
|
||||
// The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left
|
||||
// registration point and the Graphic export type.
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap();
|
||||
src.execute("select.all", &json!({})).unwrap();
|
||||
let opts = json!({"name": "Corner", "nineSlice": true, "registration": 0, "exportType": "graphic"});
|
||||
let inst = src.execute("symbol.new", &opts).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("select.set", &json!({"ids": [inst]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Corner Mark"})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Corners.vectorcraft"});
|
||||
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Corner Mark"})).unwrap();
|
||||
let (from, to) = (&src.doc().unwrap().doc, &s.doc().unwrap().doc);
|
||||
assert!(from.symbol_nine_slice("Corner").is_some());
|
||||
assert_eq!(to.symbol_nine_slice("Corner"), from.symbol_nine_slice("Corner"));
|
||||
assert_eq!(to.symbol_registration("Corner"), from.symbol_registration("Corner"));
|
||||
assert_eq!(to.symbol_export_type("Corner"), from.symbol_export_type("Corner"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designs_and_markers_survive_save_and_open() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Overprint",
|
||||
[],
|
||||
None,
|
||||
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind → {changed: objects}",
|
||||
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
|
||||
has_doc,
|
||||
set_overprint
|
||||
),
|
||||
@@ -135,7 +135,7 @@ fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>
|
||||
.into_iter()
|
||||
.map(|fill| {
|
||||
let it = item.of_kind(s, fill);
|
||||
let ids = it.targets(s, p)?;
|
||||
let ids = it.targets_for(s, p, fill)?;
|
||||
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
|
||||
Ok((fill, it, ids))
|
||||
})
|
||||
|
||||
@@ -216,12 +216,15 @@ impl Session {
|
||||
}
|
||||
let first = st.doc.node(*st.selection.subjects().first()?)?;
|
||||
let item = self.appearance_item();
|
||||
// Only an active Appearance row is shown here: it is a row of the first selected object.
|
||||
if first.appearance.item_of_kind(item, !stroke).is_some() {
|
||||
return Some((Cow::Borrowed(first), item));
|
||||
}
|
||||
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
|
||||
// object without a painted object shows the defaults for new art.
|
||||
for id in st.selection.subjects() {
|
||||
// object without a painted object shows the defaults for new art. A face or edge selected with
|
||||
// its Live Paint group counts with the group, wherever it is in the selection.
|
||||
let covered = live_paint_covered(&st.doc, st.selection.subjects());
|
||||
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, stroke, &mut nodes);
|
||||
@@ -273,14 +276,6 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the faces and edges of `n` when it is a Live Paint group, else none.
|
||||
pub(crate) fn live_paint_parts(n: &Node) -> Vec<NodeId> {
|
||||
if !is_live_paint(n) {
|
||||
return vec![];
|
||||
}
|
||||
faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect()
|
||||
}
|
||||
|
||||
/// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
|
||||
/// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
|
||||
/// other containers inside them), a compound path for its parts. A Live Paint group stands for its
|
||||
@@ -331,8 +326,9 @@ impl DocState {
|
||||
// Looking the first object up builds the id cache when there is none.
|
||||
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
|
||||
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let mut covered = std::collections::HashSet::new();
|
||||
// The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well,
|
||||
// they count with their group's.
|
||||
let covered = live_paint_covered(&self.doc, &self.selection.objects);
|
||||
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
|
||||
// place it appears.
|
||||
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
|
||||
@@ -342,7 +338,6 @@ impl DocState {
|
||||
if covered.contains(&n.id) {
|
||||
continue;
|
||||
}
|
||||
covered.extend(live_paint_parts(n));
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
@@ -839,6 +834,36 @@ pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: boo
|
||||
out
|
||||
}
|
||||
|
||||
/// Faces, edges and the other objects (the hidden source paths) of Live Paint groups.
|
||||
pub(crate) type LivePaintParts = (std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>);
|
||||
|
||||
/// The faces, the edges and the hidden source paths of the Live Paint groups in `roots` (or inside them),
|
||||
/// found as [`live_paint_parts_skipped`] finds them.
|
||||
pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts {
|
||||
let groups = live_paint_groups(d, roots);
|
||||
let mut hidden = inside_live_paint(d, &groups);
|
||||
let (mut faces, mut edges) = (std::collections::HashSet::new(), std::collections::HashSet::new());
|
||||
for (_, f, e) in &groups {
|
||||
faces.extend(f.iter().copied());
|
||||
edges.extend(e.iter().copied());
|
||||
}
|
||||
hidden.retain(|id| !faces.contains(id) && !edges.contains(id));
|
||||
(faces, edges, hidden)
|
||||
}
|
||||
|
||||
/// The faces and edges in `selected` whose Live Paint group is selected too, itself or inside another selected
|
||||
/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an
|
||||
/// object in `selected` is inside a Live Paint group.
|
||||
pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint));
|
||||
if !selected.iter().any(inside) {
|
||||
return std::collections::HashSet::new();
|
||||
}
|
||||
let (mut parts, edges, _) = live_paint_split(d, selected);
|
||||
parts.extend(edges);
|
||||
parts
|
||||
}
|
||||
|
||||
/// The instance whose object is selected with Direct Selection, and that object's path
|
||||
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
|
||||
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
|
||||
@@ -1356,7 +1381,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
|
||||
// no row for) is still an error.
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?;
|
||||
let of = match item {
|
||||
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
|
||||
ItemTarget::Top => None,
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use super::{live_paint_covered, painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use crate::{DocState, Session};
|
||||
|
||||
thread_local! {
|
||||
@@ -39,12 +39,11 @@ fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -
|
||||
}
|
||||
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
|
||||
let mut covered = HashSet::new();
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
st.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
if !covered.contains(&n.id) {
|
||||
covered.extend(live_paint_parts(n));
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
|
||||
@@ -153,6 +153,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"color.gamutCheck",
|
||||
"color.harmony",
|
||||
"color.plates",
|
||||
"color.used",
|
||||
"dataset.capture",
|
||||
"dataset.delete",
|
||||
"dataset.list",
|
||||
|
||||
@@ -29,6 +29,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
colors
|
||||
),
|
||||
cmd!(
|
||||
query "color.used",
|
||||
"Document Colors",
|
||||
[],
|
||||
None,
|
||||
"{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is",
|
||||
has_doc,
|
||||
used
|
||||
),
|
||||
cmd!(
|
||||
"recolor.apply",
|
||||
"Recolor Artwork",
|
||||
@@ -952,16 +961,19 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects}))
|
||||
}
|
||||
|
||||
/// A colour the art uses: how often, and the global swatch it is linked to.
|
||||
/// A color the art uses: how often, and the global swatch of its first linked use in paint order.
|
||||
struct Used {
|
||||
color: Color,
|
||||
count: usize,
|
||||
swatch: Option<String>,
|
||||
/// The global swatch of the first linked use that is not a gradient stop mixing the swatch's
|
||||
/// ink with process inks, with the tint (0..1) its paint stores when the paint gives one.
|
||||
plain: Option<(String, Option<f32>)>,
|
||||
}
|
||||
|
||||
/// The unique colours of the objects `ids` and the objects inside them, most used first (ties by
|
||||
/// key): fills, strokes, gradient stops, text, mesh points and the tiles of the patterns used as
|
||||
/// fills or strokes. With `only`, an object not in it is left out with everything it holds.
|
||||
/// key): fills, strokes, gradient stops, text, mesh points, the tiles of the patterns used as
|
||||
/// fills or strokes, and the tiles of the patterns those tiles use. With `only`, an object not in it is left out with everything it holds.
|
||||
fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> Vec<Used> {
|
||||
fn read<'a>(n: &'a Node, only: Option<&BTreeSet<NodeId>>, out: &mut Vec<&'a Node>) {
|
||||
if only.is_some_and(|o| !o.contains(&n.id)) {
|
||||
@@ -974,44 +986,64 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
|
||||
}
|
||||
let mut index: HashMap<ColorKey, usize> = HashMap::new();
|
||||
let mut used: Vec<(ColorKey, Used)> = vec![];
|
||||
let mut count = |c: &Color, link: Option<&str>| {
|
||||
let mut count_tint = |c: &Color, link: Option<&str>, tint: Option<f32>, mixed: bool| {
|
||||
let k = ColorKey::of(c);
|
||||
let i = *index.entry(k).or_insert_with(|| {
|
||||
used.push((k, Used { color: *c, count: 0, swatch: None }));
|
||||
used.push((k, Used { color: *c, count: 0, swatch: None, plain: None }));
|
||||
used.len() - 1
|
||||
});
|
||||
let u = &mut used[i].1;
|
||||
u.count += 1;
|
||||
if u.swatch.is_none() {
|
||||
u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string);
|
||||
if u.swatch.is_some() && (u.plain.is_some() || mixed) {
|
||||
return;
|
||||
}
|
||||
if let Some(l) = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())) {
|
||||
if u.swatch.is_none() {
|
||||
u.swatch = Some(l.to_string());
|
||||
}
|
||||
if u.plain.is_none() && !mixed {
|
||||
u.plain = Some((l.to_string(), tint));
|
||||
}
|
||||
}
|
||||
};
|
||||
// The patterns used as fills or strokes: their tiles count once each.
|
||||
// The patterns used as fills or strokes, and the patterns their tiles use: each tile counts
|
||||
// once, and a pattern whose tile uses itself, directly or through other patterns, counts once.
|
||||
let mut patterns: Vec<&str> = vec![];
|
||||
let mut nodes = vec![];
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
read(n, only, &mut nodes);
|
||||
}
|
||||
for m in nodes {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())),
|
||||
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| count(&p.color, None));
|
||||
}
|
||||
paints(m, &mut count_tint, &mut patterns);
|
||||
}
|
||||
for def in patterns.iter().filter_map(|p| d.pattern(p)) {
|
||||
def.art.iter().for_each(|n| node_colors(n, &mut count));
|
||||
let mut next = 0;
|
||||
while let Some(&name) = patterns.get(next) {
|
||||
next += 1;
|
||||
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
|
||||
a.walk(&mut |m| paints(m, &mut count_tint, &mut patterns));
|
||||
}
|
||||
}
|
||||
used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0)));
|
||||
used.into_iter().map(|(_, u)| u).collect()
|
||||
}
|
||||
|
||||
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
|
||||
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
|
||||
/// add the patterns it is painted with to `patterns`.
|
||||
fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option<f32>, bool), patterns: &mut Vec<&'a str>) {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())),
|
||||
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| count(&p.color, None, None, false));
|
||||
}
|
||||
}
|
||||
|
||||
/// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the
|
||||
/// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once).
|
||||
fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec<Color> {
|
||||
@@ -1054,30 +1086,61 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<NodeId>, Option<B
|
||||
let st = s.doc()?;
|
||||
let ids = match p.get("ids") {
|
||||
Some(_) => checked_ids_param(s, p, "ids", cmd)?,
|
||||
None if st.selection.is_empty() => {
|
||||
let only = super::select::selectable_ids(&st.doc, st.isolation);
|
||||
return Ok((super::select::selectable(&st.doc, st.isolation), Some(only)));
|
||||
}
|
||||
None if st.selection.is_empty() => return Ok(all_art(st)),
|
||||
None => st.selection.objects.clone(),
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None))
|
||||
}
|
||||
|
||||
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
|
||||
let st = s.doc()?;
|
||||
let v: Vec<Value> = used_colors(&st.doc, &ids, only.as_ref())
|
||||
.iter()
|
||||
/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing
|
||||
/// selected).
|
||||
fn all_art(st: &crate::DocState) -> (Vec<NodeId>, Option<BTreeSet<NodeId>>) {
|
||||
let only = super::select::selectable_ids(&st.doc, st.isolation);
|
||||
(super::select::selectable(&st.doc, st.isolation), Some(only))
|
||||
}
|
||||
|
||||
/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see
|
||||
/// [`used_colors`]). Each names the swatch of its first linked use. With `with_color`, each has its
|
||||
/// color in its own model, and the swatch and tint come from its first linked use that is not a
|
||||
/// gradient stop mixing the swatch's ink with process inks (none when every linked use is one).
|
||||
fn colors_json(used: &[Used], with_color: bool) -> Vec<Value> {
|
||||
used.iter()
|
||||
.map(|u| {
|
||||
let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count});
|
||||
if let Some(w) = &u.swatch {
|
||||
if with_color {
|
||||
v["color"] = json!(u.color);
|
||||
if let Some((w, tint)) = &u.plain {
|
||||
v["swatch"] = json!(w);
|
||||
if let Some(t) = tint {
|
||||
v["tint"] = json!((f64::from(*t) * 100_000.0).round() / 1000.0);
|
||||
}
|
||||
}
|
||||
} else if let Some(w) = &u.swatch {
|
||||
v["swatch"] = json!(w);
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "colors": v }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
|
||||
let st = s.doc()?;
|
||||
Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) }))
|
||||
}
|
||||
|
||||
/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes.
|
||||
fn used(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.used";
|
||||
let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX);
|
||||
let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty();
|
||||
let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) };
|
||||
let st = s.doc()?;
|
||||
let used = used_colors(&st.doc, &ids, only.as_ref());
|
||||
let uses: usize = used.iter().map(|u| u.count).sum();
|
||||
let shown = used.get(..limit.min(used.len())).unwrap_or_default();
|
||||
Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses }))
|
||||
}
|
||||
|
||||
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
|
||||
|
||||
+379
-21
@@ -11,9 +11,10 @@
|
||||
//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched
|
||||
//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object
|
||||
//! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced
|
||||
//! apart takes that spacing as its tracking ([`Line::tracked`]). Shapes that match no font stay as
|
||||
//! they are and are reported. Near matches (another version of the font, simplified outlines,
|
||||
//! merged glyphs) and images are phase 2.
|
||||
//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading
|
||||
//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). Shapes
|
||||
//! that match no font stay as they are and are reported. Near matches (another version of the
|
||||
//! font, simplified outlines, merged glyphs) and images are phase 2.
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
use std::sync::Arc;
|
||||
@@ -40,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Retype",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, tracking (1/1000 em)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
has_selected_path,
|
||||
retype
|
||||
)]
|
||||
@@ -369,18 +370,15 @@ impl Line {
|
||||
/// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(&self, t: &TextObject) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01);
|
||||
for (k, m) in self.matches.iter().enumerate() {
|
||||
let Some(g) = drawn.next() else { return Some(k) };
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
|
||||
return Some(k);
|
||||
}
|
||||
}
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| self.matches.len().saturating_sub(1))
|
||||
first_mismatch(t, &self.matches, self.size())
|
||||
}
|
||||
|
||||
/// Along the line, where its first glyph starts and its last glyph's advance ends, from
|
||||
/// `from` (the tracking after the last glyph left out).
|
||||
fn span_from(&self, from: Point) -> (f64, f64) {
|
||||
let dir = self.dir();
|
||||
let last = self.matches.last().map_or(self.end, |m| m.origin + dir * (m.face.advance(m.gid) * m.scale));
|
||||
((self.origin - from).dot(dir), (last - from).dot(dir))
|
||||
}
|
||||
|
||||
/// This line with the tracking its glyphs are spaced by, when it has at least three glyphs.
|
||||
@@ -595,6 +593,24 @@ fn round_tracking(t: f64) -> f64 {
|
||||
if (t - t.round()).abs() < 0.05 { t.round() } else { t }
|
||||
}
|
||||
|
||||
/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another
|
||||
/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
let tol = (size * 0.01).max(0.01);
|
||||
for (k, m) in matches.iter().enumerate() {
|
||||
let Some(g) = drawn.next() else { return Some(k) };
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
|
||||
return Some(k);
|
||||
}
|
||||
}
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| matches.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
/// `lines` checked against their own layout: a line splits where its type stops drawing the
|
||||
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
|
||||
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
|
||||
@@ -687,6 +703,290 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
|
||||
out
|
||||
}
|
||||
|
||||
/// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes
|
||||
/// of the area type on the layers Retype changes
|
||||
/// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type.
|
||||
const MAX_WRAP_WORK: usize = 2_000_000;
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn max_wrap_work() -> usize {
|
||||
MAX_WRAP_WORK
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// [`MAX_WRAP_WORK`], lowered by tests on their own thread.
|
||||
static WRAP_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_WRAP_WORK) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn max_wrap_work() -> usize {
|
||||
WRAP_LIMIT.with(|c| c.get())
|
||||
}
|
||||
|
||||
/// Lines farther apart than this many times their size do not join into one object.
|
||||
const MAX_LEADING: f64 = 3.0;
|
||||
|
||||
/// What Retype makes: one type object and the shapes it replaces.
|
||||
struct Made {
|
||||
t: TextObject,
|
||||
/// For area type, the point type that also draws the glyphs in place: the type kept when
|
||||
/// Text Wrap objects above it change the area type's layout.
|
||||
point: Option<TextObject>,
|
||||
/// The glyphs the type must draw, in order.
|
||||
matches: Vec<GlyphMatch>,
|
||||
pieces: Vec<NodeId>,
|
||||
text: String,
|
||||
face: Arc<vectorcraft_text::FontFace>,
|
||||
size: f64,
|
||||
tracking: f64,
|
||||
/// The leading set on the type: None for Auto or a single line.
|
||||
leading: Option<f64>,
|
||||
opacity: f32,
|
||||
blend: vectorcraft_color::BlendMode,
|
||||
}
|
||||
|
||||
impl Made {
|
||||
fn line(l: &Line, system_layout: bool) -> Made {
|
||||
Made {
|
||||
t: l.text_object(system_layout),
|
||||
point: None,
|
||||
matches: l.matches.clone(),
|
||||
pieces: l.pieces.clone(),
|
||||
text: l.text.clone(),
|
||||
face: l.face.clone(),
|
||||
size: l.size(),
|
||||
tracking: l.tracking,
|
||||
leading: None,
|
||||
opacity: l.opacity,
|
||||
blend: l.blend,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The alignments lines can share, in the order one is chosen: their starts, their ends, their
|
||||
/// centers.
|
||||
const ALIGNS: [vectorcraft_doc::Justify; 3] = [vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Right, vectorcraft_doc::Justify::Center];
|
||||
|
||||
/// A run of lines that may become one object: lines after the first, each one leading further
|
||||
/// across, in the same group, paint, transparency, font, size, turn and tracking, lined up alike.
|
||||
struct Block {
|
||||
lines: Vec<Line>,
|
||||
/// The mean distance between baselines, from the first line's to the last line's.
|
||||
leading: f64,
|
||||
/// Which of [`ALIGNS`] every line so far shares.
|
||||
aligns: [bool; 3],
|
||||
/// The tracking of the first line that has one ([`Block::spaced`]).
|
||||
tracking: Option<f64>,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn new(l: Line) -> Block {
|
||||
let tracking = Block::spaced(&l).then_some(l.tracking);
|
||||
Block { lines: vec![l], leading: 0.0, aligns: [true; 3], tracking }
|
||||
}
|
||||
|
||||
/// Does line `l` have a tracking of its own? A line of fewer than three glyphs that kept no
|
||||
/// tracking has no gaps to measure it by ([`Line::tracked`]): it takes the block's.
|
||||
fn spaced(l: &Line) -> bool {
|
||||
l.pieces.len() >= 3 || l.tracking != 0.0
|
||||
}
|
||||
|
||||
/// Add `l` when it continues the block; `l` back when it does not. `follows` tells whether the
|
||||
/// shape `l` starts with comes right after the block's last shape, with nothing between them
|
||||
/// in paint order.
|
||||
fn take(&mut self, l: Line, follows: impl Fn(NodeId, NodeId) -> bool) -> Option<Line> {
|
||||
let (Some(first), Some(prev)) = (self.lines.first(), self.lines.last()) else { return Some(l) };
|
||||
let (Some(a), Some(b)) = (prev.pieces.last(), l.pieces.first()) else { return Some(l) };
|
||||
let size = first.size();
|
||||
let tol = (size * 0.01).max(0.01);
|
||||
let same = follows(*a, *b)
|
||||
&& l.parent == first.parent
|
||||
&& l.appearance == first.appearance
|
||||
&& l.opacity == first.opacity
|
||||
&& l.blend == first.blend
|
||||
&& l.face.id() == first.face.id()
|
||||
&& (l.scale - first.scale).abs() <= first.scale * 1e-4
|
||||
&& ((l.angle - first.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
// The lines' estimates may differ a little; the layout check decides.
|
||||
&& (!Block::spaced(&l) || self.tracking.is_none_or(|t| (l.tracking - t).abs() < 1.0))
|
||||
// Lines whose ink overlaps, or a gradient spanning them, would paint otherwise as one.
|
||||
&& paints_as_one(first);
|
||||
if !same {
|
||||
return Some(l);
|
||||
}
|
||||
// Across the lines, down from the first line's baseline.
|
||||
let across = Vec2::new(-first.angle.sin(), first.angle.cos());
|
||||
let down = (l.origin - first.origin).dot(across);
|
||||
let n = self.lines.len() as f64;
|
||||
// The mean distance between the baselines so far, which this line's must continue.
|
||||
let leading = if self.lines.len() == 1 { down } else { self.leading };
|
||||
// A quarter of the size is the least leading; the outlines' positions are rounded.
|
||||
if !(leading >= size * 0.25 * (1.0 - 1e-6) && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol {
|
||||
return Some(l);
|
||||
}
|
||||
let leading = down / n;
|
||||
let (s0, e0) = first.span_from(first.origin);
|
||||
let (s, e) = l.span_from(first.origin);
|
||||
let fits = [(s - s0).abs() <= tol, (e - e0).abs() <= tol, ((s + e) - (s0 + e0)).abs() * 0.5 <= tol];
|
||||
let aligns = [self.aligns[0] && fits[0], self.aligns[1] && fits[1], self.aligns[2] && fits[2]];
|
||||
if !aligns.contains(&true) {
|
||||
return Some(l);
|
||||
}
|
||||
self.leading = leading;
|
||||
self.aligns = aligns;
|
||||
if self.tracking.is_none() && Block::spaced(&l) {
|
||||
self.tracking = Some(l.tracking);
|
||||
}
|
||||
self.lines.push(l);
|
||||
None
|
||||
}
|
||||
|
||||
/// The block as one area type object when type draws every glyph in its place as area type,
|
||||
/// else as one point type object when that does. When neither does, the lines before the line
|
||||
/// of the first glyph the type moves are made again as a block, and the lines from that one on
|
||||
/// are joined again ([`blocks`]); the first line on its own stays one object. Area type whose
|
||||
/// frame would reach past [`crate::MAX_COORD`] stays point type, and point type whose bounds
|
||||
/// would stays one object per line. Each try takes six times the
|
||||
/// block's glyphs from `budget` (point and area type are each laid out, measured and checked);
|
||||
/// without enough left, each line is one object.
|
||||
fn made(self, system_layout: bool, budget: &mut usize) -> Vec<Made> {
|
||||
let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::<Vec<_>>();
|
||||
let (Some(first), true) = (self.lines.first(), self.lines.len() > 1) else { return single(&self.lines) };
|
||||
let Some(justify) = ALIGNS.iter().zip(self.aligns).find(|(_, ok)| *ok).map(|(j, _)| *j) else { return single(&self.lines) };
|
||||
let glyphs = self.lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add);
|
||||
let Some(left) = budget.checked_sub(glyphs.saturating_mul(6)) else { return single(&self.lines) };
|
||||
*budget = left;
|
||||
let mut all = first.clone();
|
||||
all.tracking = self.tracking.unwrap_or(first.tracking);
|
||||
all.text = self.lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>().join("\n");
|
||||
let mut t = all.probe(system_layout);
|
||||
t.para.justify = justify;
|
||||
let size = first.size();
|
||||
let mut set_leading = None;
|
||||
if let Some(r) = t.runs.first_mut() {
|
||||
// The leading that puts the last baseline where the last line's is: Auto when Auto
|
||||
// does, else the mean distance between baselines, to a thousandth of a point (as
|
||||
// typed leading is) when that still puts the last baseline in place.
|
||||
let gaps = self.lines.len().saturating_sub(1) as f64;
|
||||
let across = Vec2::new(-first.angle.sin(), first.angle.cos());
|
||||
let span = self.lines.last().map_or(0.0, |l| (l.origin - first.origin).dot(across));
|
||||
if (t.para.effective_leading(&r.style) * gaps - span).abs() > size * 1e-4 {
|
||||
let exact = span / gaps;
|
||||
let rounded = (exact * 1000.0).round() / 1000.0;
|
||||
let leading = if ((rounded - exact) * gaps).abs() <= size * 1e-4 { rounded } else { exact };
|
||||
r.style.leading = Some(leading);
|
||||
set_leading = Some(leading);
|
||||
}
|
||||
}
|
||||
let matches: Vec<GlyphMatch> = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect();
|
||||
// Aligned at its end or center, point type starts its first line elsewhere: the type moves
|
||||
// so its first glyph is where the first outline is.
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) {
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
t.xf = kurbo::Affine::translate(m.origin - at) * t.xf;
|
||||
}
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
if let Some(k) = first_mismatch(&t, &matches, size) {
|
||||
// The line that holds glyph `k`.
|
||||
let mut seen = 0usize;
|
||||
let at = self.lines.iter().position(|l| {
|
||||
seen = seen.saturating_add(l.pieces.len());
|
||||
k < seen
|
||||
});
|
||||
let Block { mut lines, leading, aligns, .. } = self;
|
||||
let rest = lines.split_off(at.unwrap_or(0).clamp(1, lines.len()));
|
||||
let mut out = if lines.len() > 1 {
|
||||
let tracking = lines.iter().find(|l| Block::spaced(l)).map(|l| l.tracking);
|
||||
Block { lines, leading, aligns, tracking }.made(system_layout, budget)
|
||||
} else {
|
||||
single(&lines)
|
||||
};
|
||||
// The lines of the rest followed each other in the block.
|
||||
out.extend(blocks(rest, |_, _| true, system_layout, budget));
|
||||
return out;
|
||||
}
|
||||
// The edit is refused when an object's bounds reach past the coordinate limit. A turned
|
||||
// block's box can reach a corner that none of its lines does: the lines then stay apart.
|
||||
let in_range =
|
||||
|t: &TextObject| Node::new(NodeId(0), NodeKind::Text(Box::new(t.clone()))).geometric_bounds().is_none_or(crate::sanity::rect_in_range);
|
||||
if !in_range(&t) {
|
||||
return single(&self.lines);
|
||||
}
|
||||
let mut area = t.clone();
|
||||
super::typemenu::point_to_area(&mut area);
|
||||
let mut point = None;
|
||||
if in_range(&area) && first_mismatch(&area, &matches, size).is_none() {
|
||||
point = Some(std::mem::replace(&mut t, area));
|
||||
}
|
||||
vec![Made {
|
||||
t,
|
||||
point,
|
||||
matches,
|
||||
pieces: self.lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(),
|
||||
text: all.text,
|
||||
face: first.face.clone(),
|
||||
size,
|
||||
tracking: all.tracking,
|
||||
leading: set_leading,
|
||||
opacity: first.opacity,
|
||||
blend: first.blend,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// A line of two untracked glyphs has one gap, too few to measure a tracking by
|
||||
/// ([`Line::tracked`]). It is set at the tracking of the nearest tracked line of the same font,
|
||||
/// size and turn, so the layout check ([`verified`]) tries it as that line is set: the check falls
|
||||
/// back to the line untracked, and then splits it, when the pair is not spaced so. A pair that
|
||||
/// untracked type already draws in place keeps its text, and negative tracking goes only to a pair
|
||||
/// that paints the same as one object ([`paints_as_one`]).
|
||||
fn share_tracking(lines: &mut [Line], system_layout: bool) {
|
||||
for i in 0..lines.len() {
|
||||
let Some(l) = lines.get(i).filter(|l| l.pieces.len() == 2 && l.tracking == 0.0) else { continue };
|
||||
if l.first_mismatch(&l.probe(system_layout)).is_none() {
|
||||
continue;
|
||||
}
|
||||
let like = |o: &Line| {
|
||||
o.tracking != 0.0
|
||||
&& o.parent == l.parent
|
||||
&& o.face.id() == l.face.id()
|
||||
&& (o.scale - l.scale).abs() <= l.scale * 1e-4
|
||||
&& ((o.angle - l.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
};
|
||||
let nearest = lines.iter().enumerate().filter(|(_, o)| like(o)).min_by_key(|(j, _)| j.abs_diff(i)).map(|(_, o)| o.tracking);
|
||||
if let Some(p) = nearest.filter(|t| *t > 0.0 || paints_as_one(l)).and_then(|t| l.respaced(0, 2, t)) {
|
||||
lines[i] = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of
|
||||
/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after
|
||||
/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
|
||||
fn blocks(lines: Vec<Line>, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec<Made> {
|
||||
let mut out = vec![];
|
||||
let mut block: Option<Block> = None;
|
||||
for l in lines {
|
||||
let l = match block.as_mut() {
|
||||
Some(b) => match b.take(l, &follows) {
|
||||
None => continue,
|
||||
Some(l) => l,
|
||||
},
|
||||
None => l,
|
||||
};
|
||||
if let Some(b) = block.take() {
|
||||
out.extend(b.made(system_layout, budget));
|
||||
}
|
||||
block = Some(Block::new(l));
|
||||
}
|
||||
if let Some(b) = block {
|
||||
out.extend(b.made(system_layout, budget));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Puts parts of a line at the front of the work list, in order.
|
||||
trait FrontParts {
|
||||
fn extend_front_parts<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]);
|
||||
@@ -874,7 +1174,8 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// glyphs), so every line has what its measure can take.
|
||||
let mut budget =
|
||||
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add);
|
||||
let lines = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
|
||||
let mut lines: Vec<Line> = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
|
||||
share_tracking(&mut lines, system_layout);
|
||||
let mut lines = verified(lines, system_layout, &mut unmatched);
|
||||
if pieces.len() > 1 {
|
||||
lines.retain(|l| {
|
||||
@@ -885,20 +1186,29 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
!lone
|
||||
});
|
||||
}
|
||||
(lines, unmatched, truncated)
|
||||
let at: std::collections::HashMap<NodeId, usize> = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect();
|
||||
let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) {
|
||||
(Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier),
|
||||
_ => false,
|
||||
};
|
||||
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
|
||||
// for small blocks.
|
||||
let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256);
|
||||
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated)
|
||||
};
|
||||
if lines.is_empty() {
|
||||
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
|
||||
}
|
||||
let made = s.edit("Retype", |d, sel| {
|
||||
// The layers as they were, for the Text Wrap check below.
|
||||
let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone());
|
||||
let mut ids = vec![];
|
||||
let mut emptied = vec![];
|
||||
for l in &lines {
|
||||
let Some(first) = l.pieces.first() else { continue };
|
||||
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
|
||||
let t = l.text_object(system_layout);
|
||||
let id = d.alloc_id();
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(t)));
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(l.t.clone())));
|
||||
// The glyphs' own transparency (the group's, kept, still applies over it).
|
||||
node.opacity = l.opacity;
|
||||
node.blend = l.blend;
|
||||
@@ -945,17 +1255,65 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Text Wrap objects above new area type flow it once the edit is done: area type they
|
||||
// would move a glyph of becomes the point type that draws it in place.
|
||||
if let Some(before) = &before {
|
||||
// Worked out on a copy, so the edit's own Text Wrap refresh still sees every other
|
||||
// area type whose wrap changes, and only on the layers this edit changed, as that
|
||||
// refresh is. The copy holds only the changed layers while the work is counted; past
|
||||
// the limit, the new area type is not flowed and all of it becomes its point type.
|
||||
let mut probe = d.clone();
|
||||
let all = std::mem::take(&mut probe.layers);
|
||||
probe.layers = all
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, layer)| {
|
||||
// As resolve_wrap tells an unchanged layer: the same layer at its index first.
|
||||
!(before.layers.get(*i).is_some_and(|b| Arc::ptr_eq(b, layer))
|
||||
|| before.layers.iter().any(|b| b.id == layer.id && Arc::ptr_eq(b, layer)))
|
||||
})
|
||||
.map(|(_, layer)| layer.clone())
|
||||
.collect();
|
||||
let units = vectorcraft_doc::text::wrap_copy_units(&probe);
|
||||
let flowed = units <= max_wrap_work();
|
||||
probe.layers = all;
|
||||
if flowed && units > 0 {
|
||||
vectorcraft_doc::text::resolve_wrap(Some(before), &mut probe);
|
||||
}
|
||||
// With nothing to copy, no area type on those layers has a wrap shape.
|
||||
for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) {
|
||||
let Some(point) = &l.point else { continue };
|
||||
let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue };
|
||||
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
**t = point.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keep: Vec<NodeId> = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect();
|
||||
keep.extend(&ids);
|
||||
sel.set(keep);
|
||||
Ok(ids)
|
||||
})?;
|
||||
let d = &s.doc()?.doc;
|
||||
let area =
|
||||
|id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }));
|
||||
Ok(json!({
|
||||
"ids": made.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
|
||||
"fonts": lines
|
||||
.iter()
|
||||
.map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.size(), "tracking": l.tracking}))
|
||||
.zip(&made)
|
||||
.map(|(l, id)| json!({
|
||||
"family": l.face.family,
|
||||
"style": l.face.style,
|
||||
"size": l.size,
|
||||
"tracking": l.tracking,
|
||||
"leading": l.leading,
|
||||
"area": area(id),
|
||||
}))
|
||||
.collect::<Vec<_>>(),
|
||||
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"truncated": truncated,
|
||||
|
||||
@@ -583,6 +583,224 @@ fn assert_same_places(a: &TextObject, b: &TextObject) {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_lines_become_one_area_type_object() {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one\nThird";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(true), "{r}");
|
||||
assert_eq!(r["fonts"][0]["leading"], json!(null), "Auto leading gives the lines' spacing: {r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }));
|
||||
assert_eq!(t.plain_text(), text);
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_a_quarter_of_the_size_apart_join_and_closer_ones_do_not() {
|
||||
// At 20 pt, 5 pt is the least leading that joins lines.
|
||||
// 4.9999999 pt is 5 pt to the rounding of the outlines' positions.
|
||||
for (leading, objects) in [(5.0, 1), (4.9999999, 1), (4.9, 2)] {
|
||||
let mut s = session();
|
||||
let text = "One\nTwo";
|
||||
let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 20}), &[json!({"leading": leading})]);
|
||||
assert_eq!(r["texts"].as_array().unwrap().len(), objects, "{leading}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_glyph_line_takes_the_tracking_of_the_lines_around_it() {
|
||||
let mut s = session();
|
||||
let text = "MMM\nMM\nMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 50})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_keep_their_leading_and_alignment() {
|
||||
for justify in ["left", "center", "right"] {
|
||||
let mut s = session();
|
||||
let text = "Wide first line\nmid\nlast one";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 300, "y": 100, "text": text, "size": 20, "justify": justify}), &[json!({"leading": 31})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{justify}: {r}");
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 31.0, 1e-3), "{justify}: {r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(true), "{justify}: {r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "{justify}");
|
||||
assert_eq!(t.para.justify, before.para.justify, "{justify}");
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_near_auto_leading_keeps_its_own_leading() {
|
||||
// 24.001 pt is Auto's 24 pt within a ten-thousandth of the size per line, but 250 lines
|
||||
// move the last one a quarter of a point.
|
||||
let mut s = session();
|
||||
let text = vec!["ab"; 250].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 24.001})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.001, 1e-4), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_at_auto_leading_of_a_fractional_size_keeps_auto() {
|
||||
// Auto leading of 20.002 pt is 24.0024 pt, finer than the thousandth of a point the leading
|
||||
// between two lines is read to.
|
||||
let mut s = session();
|
||||
// Six hundred lines: read to a thousandth, each gap would be 0.0004 pt short, and the last
|
||||
// line 0.24 pt off.
|
||||
let text = vec!["ab"; 600].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20.002}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert_eq!(r["fonts"][0]["leading"], json!(null), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_at_a_leading_finer_than_a_thousandth_keeps_it() {
|
||||
// 23.9996 pt read to a thousandth is 24 pt, Auto for 20 pt type: over 600 lines the last one
|
||||
// would be 0.24 pt off.
|
||||
let mut s = session();
|
||||
let text = vec!["ab"; 600].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 23.9996})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 23.9996, 1e-6), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_whose_first_gap_is_a_little_off_stays_one_object() {
|
||||
// The second line moved up 0.004 pt: its gap read alone, carried over 100 lines, would put
|
||||
// the last one 0.4 pt off.
|
||||
let mut s = session();
|
||||
let text = ["ab"; 100].join("\n");
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 40, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "leading": 24.004})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let kids = children_of(&s, g);
|
||||
s.execute("select.set", &json!({"ids": kids[2..4]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 0, "dy": -0.004})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.004, 1e-3), "{}", r["fonts"][0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_whose_frame_would_pass_the_coordinate_limit_stay_point_type() {
|
||||
let mut s = session();
|
||||
let text = "Wide line\nWide";
|
||||
let id = s.execute("text.create", &json!({"x": 3_999_000, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
let right = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x1;
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
// The ink ends 2 pt short of the limit; Convert To Area Type's slack would reach past it.
|
||||
s.execute("object.move", &json!({"dx": vectorcraft_doc::MAX_COORD - 2.0 - right, "dy": 0})).unwrap();
|
||||
let before = text_of(&s, id);
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(false), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_type_cannot_join_ends_the_block_there() {
|
||||
// The fourth line keeps a fraction of a unit of tracking that the others do not: joined, it
|
||||
// moves, so the lines before it stay one object and the lines after it join again.
|
||||
let mut s = session();
|
||||
let line = "M".repeat(40);
|
||||
let text = [line.as_str(); 6].join("\n");
|
||||
let start = 3 * 41;
|
||||
let (before, r) =
|
||||
retyped(&mut s, json!({"x": 20, "y": 40, "text": text, "size": 20}), &[json!({"start": start, "end": start + 40, "tracking": 0.6})]);
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.len(), 3, "{texts:?} {}", r["fonts"]);
|
||||
assert_eq!(texts.join("\n"), text);
|
||||
let places: Vec<kurbo::Point> = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect();
|
||||
let want = glyph_places(&before);
|
||||
assert_eq!(places.len(), want.len());
|
||||
for (x, y) in places.iter().zip(&want) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The glyphs of the outline groups `others` moved to the end of group `g`, in order, and the
|
||||
/// emptied groups removed.
|
||||
fn into_one_group(s: &mut Session, g: u64, others: &[u64]) {
|
||||
s.edit("test", |d, _| {
|
||||
for o in others {
|
||||
let kids: Vec<_> = d.node(NodeId(*o)).unwrap().children().unwrap().to_vec();
|
||||
d.remove(NodeId(*o))?;
|
||||
for k in kids {
|
||||
let at = d.node(NodeId(g)).unwrap().children().unwrap().len();
|
||||
d.insert(Some(NodeId(g)), at, (*k).clone())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_that_do_not_stack_as_a_paragraph_stay_apart() {
|
||||
let mut s = session();
|
||||
// Far apart, then lined up at nothing.
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Top", "size": 20}));
|
||||
let b = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Far", "size": 20}));
|
||||
let c = outlined(&mut s, json!({"x": 75, "y": 324, "text": "Askew", "size": 20}));
|
||||
into_one_group(&mut s, a, &[b, c]);
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_between_lines_keeps_them_apart() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB\nCD", "size": 30}));
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
s.edit("test", |d, _| {
|
||||
let n = d.node(NodeId(rect)).unwrap().clone();
|
||||
d.remove(NodeId(rect))?;
|
||||
d.insert(Some(NodeId(g)), 2, n)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["AB", "CD"]), "the rectangle is painted between the lines: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_lines_keep_their_tracking_and_spaces() {
|
||||
let mut s = session();
|
||||
let text = "SPACED OUT\nTITLE";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_line_takes_the_tracking_of_its_block() {
|
||||
// One glyph has no gap to measure tracking by: it joins the tracked lines.
|
||||
for text in ["TITLE\nB", "B\nTITLE", "TITLE\nB\nTITLE"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unevenly_tracked_type_still_becomes_type() {
|
||||
let mut s = session();
|
||||
@@ -909,3 +1127,112 @@ fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() {
|
||||
assert_eq!(r["texts"], json!(["M", "M", "M", "M"]), "{r}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["tracking"] == json!(0.0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translucent_gradient_or_stroked_lines_stay_apart() {
|
||||
for case in ["opacity", "blend", "gradient", "stroke"] {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "One\nTwo", "size": 30}));
|
||||
let kids = children_of(&s, g);
|
||||
match case {
|
||||
"gradient" => {
|
||||
let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("paint.setFill", &json!({"gradient": gradient, "ids": kids})).unwrap();
|
||||
}
|
||||
"stroke" => {
|
||||
s.execute("paint.setStroke", &json!({"color": "#ff0000", "ids": kids})).unwrap();
|
||||
}
|
||||
_ => {
|
||||
s.edit("test", |d, _| {
|
||||
for k in &kids {
|
||||
let n = d.node_mut(NodeId(*k)).unwrap();
|
||||
if case == "opacity" {
|
||||
n.opacity = 0.5;
|
||||
} else {
|
||||
n.blend = vectorcraft_color::BlendMode::Multiply;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["One", "Two"]), "{case}: one object would composite or fill the lines as one: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_stay_point_type_past_the_text_wrap_limit_of_their_layer() {
|
||||
// A Text Wrap object above the lines that moves no glyph, on their layer or on another one,
|
||||
// with the limit lowered to nothing: only on their layer does it count.
|
||||
for same_layer in [true, false] {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one";
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = text_of(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
if !same_layer {
|
||||
// Area type below the Text Wrap object on the other layer: work there, none on this one.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let other = s.execute("text.create", &json!({"x": 450, "y": 300, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("type.convertToAreaType", &json!({"ids": [other]})).unwrap();
|
||||
}
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 330, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
super::WRAP_LIMIT.with(|c| c.set(0));
|
||||
let r = s.execute("type.retype", &json!({}));
|
||||
super::WRAP_LIMIT.with(|c| c.set(super::MAX_WRAP_WORK));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(!same_layer), "{same_layer}: {r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_subpaths_of_a_text_wrap_object_count_as_wrap_work() {
|
||||
// Each one is copied into the wrap shapes of the area type below it.
|
||||
let mut s = session();
|
||||
let t = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Area", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("type.convertToAreaType", &json!({"ids": [t]})).unwrap();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
let base = vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc);
|
||||
let file_work = vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc);
|
||||
s.edit("test", |d, _| {
|
||||
if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(rect)).unwrap().kind {
|
||||
for _ in 0..100 {
|
||||
path.subpaths.push(vectorcraft_geom::SubPath::new(vec![], true));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc) >= base + 100);
|
||||
// The count file import and the `.ai` editing copy use stays anchors and shapes only.
|
||||
assert_eq!(vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc), file_work);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_under_a_text_wrap_object_stay_point_type() {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one";
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = text_of(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
// Above the outlines, over the end of both lines: area type would wrap round it.
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 90, "y": 70, "width": 60, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(false), "{r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Point));
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_geom::PathData;
|
||||
use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::appearance::{ItemTarget, edit_items, item_target};
|
||||
use super::paint::{live_paint_parts, live_paint_parts_skipped, painted};
|
||||
use super::paint::{live_paint_covered, live_paint_parts_skipped, painted};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
|
||||
use crate::DocState;
|
||||
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
|
||||
@@ -250,10 +250,15 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if item == ItemTarget::Top {
|
||||
own_stroke_or_leaves(s, p)?
|
||||
} else {
|
||||
item.targets(s, p)?
|
||||
item.targets_for(s, p, false)?
|
||||
};
|
||||
// A Live Paint group without edges was still selected or given: the options do not go to new art.
|
||||
let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty();
|
||||
let live_paint = !bucket
|
||||
&& if item == ItemTarget::Top {
|
||||
!live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty()
|
||||
} else {
|
||||
!super::appearance::contents_skipped(s, p, false)?.is_empty()
|
||||
};
|
||||
let new_art = bucket || (no_targets(&ids, p) && !live_paint);
|
||||
let given = !ids.is_empty() || live_paint;
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
@@ -453,12 +458,15 @@ impl Session {
|
||||
}
|
||||
let Some(first) = st.selection.objects.first() else { return Some(self.new_art_stroke()) };
|
||||
let first = st.doc.node(*first)?;
|
||||
// Only an active Appearance row is shown here: it is a row of the first selected object.
|
||||
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
|
||||
return first.appearance.stroke_at(Some(i)).cloned();
|
||||
}
|
||||
// A Live Paint group without edges shows the next selected object's stroke; any other object
|
||||
// without a painted object shows none.
|
||||
for id in &st.selection.objects {
|
||||
// without a painted object shows none. A face or edge selected with its Live Paint group counts
|
||||
// with the group, wherever it is in the selection.
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, true, &mut nodes);
|
||||
@@ -532,7 +540,7 @@ impl DocState {
|
||||
} else {
|
||||
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let covered: std::collections::HashSet<vectorcraft_doc::NodeId> = selected.iter().flat_map(|n| live_paint_parts(n)).collect();
|
||||
let covered = live_paint_covered(&self.doc, &self.selection.objects);
|
||||
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
|
||||
painted(n, true, true, &mut nodes);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
|
||||
use super::fileio::{create_dir, extension, read_file, write_file, write_new_file};
|
||||
use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file};
|
||||
use super::menucmds::squash;
|
||||
use super::package::free_name;
|
||||
use super::patternlib;
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document's graph designs are offered by Object › Graph › Column… and Marker… (graph.column, graph.marker and graph.design take the library's id) until the app quits. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own), unless it has graph designs, which then load with no swatches. A file larger than 256 MB is refused before it is read → {library: id, name, count, graphDesigns: the document's graph designs (0 for a library file)}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
@@ -92,6 +92,45 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The graph designs of the documents Other Library… loaded (`swatch.library.load`), which the
|
||||
/// Graph Column and Graph Marker dialogs offer besides the document's own; not saved.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DesignLibraries {
|
||||
libs: Vec<DesignLibrary>,
|
||||
}
|
||||
|
||||
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DesignLibrary {
|
||||
/// The id `swatch.library.load` gave the swatch library. A User Defined copy of it
|
||||
/// (`swatch.library.copyToUser`) holds the swatches alone, so the designs stay under this id.
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// The designs and the resources their art uses.
|
||||
pub doc: Arc<vectorcraft_doc::Document>,
|
||||
}
|
||||
|
||||
impl DesignLibraries {
|
||||
/// The libraries, in the order they were loaded.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &DesignLibrary> {
|
||||
self.libs.iter()
|
||||
}
|
||||
|
||||
/// The library loaded as swatch library `id`.
|
||||
pub fn get(&self, id: &str) -> Option<&DesignLibrary> {
|
||||
self.libs.iter().find(|l| l.id == id)
|
||||
}
|
||||
|
||||
/// Keep `doc`'s graph designs as library `id` named `name`, in place of the ones loaded as `id`
|
||||
/// before; with no designs, `id` no longer has any.
|
||||
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
|
||||
self.libs.retain(|l| l.id != id);
|
||||
if let Some(doc) = doc {
|
||||
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The libraries beyond the built-in ones: User Defined (the library files in the user library
|
||||
/// folder, as last scanned) and loaded ones (`swatch.library.load`). Graphic style libraries use
|
||||
/// the same with [`vectorcraft_doc::StyleLibrary`] ([`super::stylelib`]).
|
||||
@@ -354,12 +393,32 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
/// or a file with the same extension and bytes as one there, is that User Defined library;
|
||||
/// others are listed as loaded until the app quits.
|
||||
pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result<L>) -> Result<(LibraryInfo, Arc<L>)> {
|
||||
self.load_within(p, cmd, None, parse)
|
||||
}
|
||||
|
||||
/// [`Self::load`], with a file at `path` read up to `max` bytes and refused when it is longer.
|
||||
pub(crate) fn load_within(
|
||||
&mut self,
|
||||
p: &Value,
|
||||
cmd: &str,
|
||||
max: Option<usize>,
|
||||
parse: impl FnOnce(&[u8], &str) -> Result<L>,
|
||||
) -> Result<(LibraryInfo, Arc<L>)> {
|
||||
let path = text_param(p, "path", cmd)?;
|
||||
let data = text_param(p, "data", cmd)?;
|
||||
let data_base64 = text_param(p, "dataBase64", cmd)?;
|
||||
let name = text_param(p, "name", cmd)?;
|
||||
let bytes = match (path, data, data_base64) {
|
||||
(Some(path), ..) => read_file(path)?,
|
||||
(Some(path), ..) => match max {
|
||||
Some(max) => {
|
||||
let bytes = read_file_head(path, max.saturating_add(1))?;
|
||||
if bytes.len() > max {
|
||||
return Err(bad(cmd, too_big_message(max)));
|
||||
}
|
||||
bytes
|
||||
}
|
||||
None => read_file(path)?,
|
||||
},
|
||||
(None, Some(text), _) => text.as_bytes().to_vec(),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?,
|
||||
_ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")),
|
||||
@@ -777,12 +836,40 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The error for a library file larger than `max` bytes.
|
||||
fn too_big_message(max: usize) -> String {
|
||||
format!("the file is larger than {} MB", max >> 20)
|
||||
}
|
||||
|
||||
/// Whether the library `p` gives (`path`, `data` or `dataBase64`) is larger than `max` bytes,
|
||||
/// checked before the file is read, copied or decoded.
|
||||
pub(crate) fn library_too_big(p: &Value, cmd: &str, max: usize) -> Result<bool> {
|
||||
Ok(match text_param(p, "path", cmd)? {
|
||||
Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64),
|
||||
None => match text_param(p, "data", cmd)? {
|
||||
Some(text) => text.len() > max,
|
||||
// Base64 holds 3 bytes in every 4 characters (padding and white space hold none).
|
||||
None => {
|
||||
text_param(p, "dataBase64", cmd)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.load";
|
||||
let max = super::place::document::MAX_FILE;
|
||||
if library_too_big(p, C, max)? {
|
||||
return Err(bad(C, too_big_message(max)));
|
||||
}
|
||||
let mut designs = None;
|
||||
// The document a library with pattern swatches was read from, which holds their patterns.
|
||||
let mut patterns = None;
|
||||
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
// The file is read no further than the limit, so a file that grew since it was checked is
|
||||
// refused too.
|
||||
let (info, lib) = s.swatch_libraries.load_within(p, C, Some(max), |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library and whose graph
|
||||
// designs the Graph Column and Graph Marker dialogs offer.
|
||||
if palette_io::sniff_bytes(bytes) {
|
||||
return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e));
|
||||
}
|
||||
@@ -792,10 +879,17 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches.
|
||||
let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc);
|
||||
let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
let mut lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
let doc_designs = super::clipboard::resources::graph_design_library(&loaded.doc);
|
||||
if defaults || lib.is_empty() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
// A document with graph designs loads for them, with no swatches.
|
||||
if doc_designs.is_none() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
}
|
||||
lib.swatches.clear();
|
||||
lib.groups.clear();
|
||||
}
|
||||
designs = doc_designs;
|
||||
if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) {
|
||||
patterns = Some(Arc::new(loaded.doc));
|
||||
}
|
||||
@@ -804,7 +898,9 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if info.category == "loaded" {
|
||||
s.swatch_libraries.set_pattern_doc(&info.id, patterns);
|
||||
}
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
let count = designs.as_ref().map_or(0, |d| d.graph_designs.len());
|
||||
s.graph_design_libraries.set(&info.id, &info.name, designs);
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len(), "graphDesigns": count}))
|
||||
}
|
||||
|
||||
/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new
|
||||
|
||||
@@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec<Sy
|
||||
}
|
||||
}
|
||||
|
||||
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects after
|
||||
/// its art changed from `old` outside symbol editing (a graph in it drawn again): a change to an
|
||||
/// object that is no longer there is dropped ([`follow_objects`]).
|
||||
pub(crate) fn follow_art_change(d: &mut Document, name: &str, old: &Arc<Node>) {
|
||||
let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return };
|
||||
let parts = |art: &Arc<Node>| match (&art.kind, art.children()) {
|
||||
(NodeKind::Group { .. }, Some(ch)) => (ch.to_vec(), true),
|
||||
_ => (vec![art.clone()], false),
|
||||
};
|
||||
let (old, new) = (parts(old), parts(&new));
|
||||
follow_objects(d, name, (&old.0, old.1), (&new.0, new.1));
|
||||
}
|
||||
|
||||
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects
|
||||
/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art
|
||||
/// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the
|
||||
|
||||
@@ -634,34 +634,40 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !matches!(t.kind, TextKind::Point) {
|
||||
continue;
|
||||
}
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
// The frame is worked out in line space, where the lines are; vertical type turns it
|
||||
// into text space with the lines.
|
||||
let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() };
|
||||
let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds);
|
||||
// Across, the frame spans the lines as they are aligned: from their starts to their ends
|
||||
// without the tracking after their last characters (`LineInfo::trailing`), not to the
|
||||
// ink, which tracking can pull past an advance. Area type aligns them alike.
|
||||
let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing)));
|
||||
if x0.is_finite() && x1.is_finite() && x0 <= x1 {
|
||||
(b.x0, b.x1) = (x0, x1);
|
||||
}
|
||||
// Line breaking counts that tracking: the slack holds the most of it.
|
||||
let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max);
|
||||
let size = t.first_style().size;
|
||||
// A little slack on the right so the text doesn't rewrap.
|
||||
let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0);
|
||||
let slack = size * 0.5 + trailing;
|
||||
let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack);
|
||||
let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(frame) };
|
||||
refresh_bounds(t);
|
||||
point_to_area(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
/// Point type `t` turned into area type in a frame around its lines, with a little slack where its
|
||||
/// alignment leaves room, so the text stays where it is and does not rewrap.
|
||||
pub(super) fn point_to_area(t: &mut TextObject) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
// The frame is worked out in line space, where the lines are; vertical type turns it
|
||||
// into text space with the lines.
|
||||
let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() };
|
||||
let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds);
|
||||
// Across, the frame spans the lines as they are aligned: from their starts to their ends
|
||||
// without the tracking after their last characters (`LineInfo::trailing`), not to the
|
||||
// ink, which tracking can pull past an advance. Area type aligns them alike.
|
||||
let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing)));
|
||||
if x0.is_finite() && x1.is_finite() && x0 <= x1 {
|
||||
(b.x0, b.x1) = (x0, x1);
|
||||
}
|
||||
// Line breaking counts that tracking: the slack holds the most of it.
|
||||
let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max);
|
||||
let size = t.first_style().size;
|
||||
// A little slack on the right so the text doesn't rewrap.
|
||||
let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0);
|
||||
let slack = size * 0.5 + trailing;
|
||||
let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack);
|
||||
let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(frame) };
|
||||
refresh_bounds(t);
|
||||
}
|
||||
|
||||
/// How `slack` added to point type's lines in a frame is shared before and after them: where the
|
||||
/// alignment leaves room, so the text doesn't move or rewrap.
|
||||
fn slack_sides(justify: Justify, rtl: bool, slack: f64) -> (f64, f64) {
|
||||
|
||||
@@ -356,6 +356,7 @@ pub struct FillAttrs {
|
||||
|
||||
impl FillAttrs {
|
||||
pub const ALL: Self = Self { color: true, transparency: true, overprint: true };
|
||||
pub const NONE: Self = Self { color: false, transparency: false, overprint: false };
|
||||
}
|
||||
|
||||
impl Default for FillAttrs {
|
||||
@@ -383,6 +384,8 @@ pub struct StrokeAttrs {
|
||||
|
||||
impl StrokeAttrs {
|
||||
pub const ALL: Self = Self { color: true, transparency: true, overprint: true, weight: true, cap: true, join: true, miter: true, dash: true };
|
||||
pub const NONE: Self =
|
||||
Self { color: false, transparency: false, overprint: false, weight: false, cap: false, join: false, miter: false, dash: false };
|
||||
}
|
||||
|
||||
impl Default for StrokeAttrs {
|
||||
|
||||
@@ -153,6 +153,9 @@ pub struct Session {
|
||||
pub(crate) pending_paint: Option<Paint>,
|
||||
/// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved.
|
||||
pub swatch_libraries: cmd::swatchlib::Libraries,
|
||||
/// The graph designs of the documents loaded as swatch libraries (Window → Swatch Libraries →
|
||||
/// Other Library…), for the Graph Column and Graph Marker dialogs; not saved.
|
||||
pub graph_design_libraries: cmd::swatchlib::DesignLibraries,
|
||||
/// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it
|
||||
/// was selected on: read it with [`Session::selected_freeform_point`].
|
||||
pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>,
|
||||
|
||||
@@ -85,6 +85,7 @@ impl Session {
|
||||
recent_colors: vec![],
|
||||
pending_paint: None,
|
||||
swatch_libraries: Default::default(),
|
||||
graph_design_libraries: Default::default(),
|
||||
freeform_point: None,
|
||||
style_libraries: Default::default(),
|
||||
symbol_libraries: Default::default(),
|
||||
|
||||
@@ -124,7 +124,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"engraving",
|
||||
"arrows",
|
||||
"image-brush",
|
||||
"artistic"
|
||||
"artistic",
|
||||
"vector-packs"
|
||||
]
|
||||
);
|
||||
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
|
||||
@@ -204,6 +205,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
|
||||
("arrows", "art"),
|
||||
("image-brush", "scatter"),
|
||||
("artistic", "art"),
|
||||
("vector-packs", "scatter"),
|
||||
] {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.len() >= 4, "{id}");
|
||||
@@ -272,6 +274,48 @@ fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() {
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_packs_marks_are_editable_and_survive_a_saved_library() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "vector-packs").unwrap();
|
||||
let names = ["Compass Rose", "Botanical Sprig", "Facet Diamond", "Tide Crest"];
|
||||
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
|
||||
let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap();
|
||||
for b in &lib.brushes {
|
||||
let BrushKind::Scatter(sc) = &b.kind else { panic!("{} is not a scatter brush", b.name) };
|
||||
assert!(art_paths(&sc.art).len() >= 2, "{} has no editable vector mark", b.name);
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &black_stroke());
|
||||
assert!(pieces.len() >= 3, "{} does not repeat along a path", b.name);
|
||||
// The black marks take a non-black stroke color as their fill.
|
||||
let teal = vectorcraft_color::Color::rgb(0.1, 0.6, 0.5);
|
||||
let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(teal), 1.0);
|
||||
let mut fills = vec![];
|
||||
for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke) {
|
||||
piece.walk(&mut |c| {
|
||||
if c.path_data().is_some() {
|
||||
fills.push(c.appearance.fill().map(|f| f.paint.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
assert!(!fills.is_empty(), "{} draws no paths", b.name);
|
||||
for fill in fills {
|
||||
let Some(vectorcraft_color::Paint::Solid { color, .. }) = fill else { panic!("{} draws a path without a solid fill: {fill:?}", b.name) };
|
||||
let (got, want) = (color.to_rgb(), teal.to_rgb());
|
||||
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{} fills {got:?}, not the stroke color {want:?}", b.name);
|
||||
}
|
||||
let before = undo_len(&s);
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "vector-packs", "name": b.name, "apply": true, "ids": [line]}));
|
||||
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
|
||||
assert_eq!(added["applied"], json!([line]));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(doc(&s).node(NodeId(line)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
|
||||
}
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let reopened = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -4283,6 +4283,353 @@ fn live_paint_group_stroke_panel_edits_change_its_edges() {
|
||||
assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0));
|
||||
}
|
||||
|
||||
/// A face or edge selected before its Live Paint group counts with the group: the Fill proxy shows
|
||||
/// the faces' fill and the Stroke panel the edges' stroke, whatever the order of the selection.
|
||||
#[test]
|
||||
fn live_paint_group_proxies_do_not_depend_on_the_selection_order() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
|
||||
let magenta = serde_json::to_value(Paint::solid(Color::from_hex("#ff00ff").unwrap())).unwrap();
|
||||
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
|
||||
s.execute("select.set", &json!({"ids": [edge.0, g.0]})).unwrap();
|
||||
assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], magenta, "an edge first shows the faces' fill");
|
||||
// A face with a stroke of its own (from a file, say), selected first, shows the edges' stroke.
|
||||
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(face).unwrap();
|
||||
n.appearance.set_stroke(Paint::solid(Color::BLACK));
|
||||
n.appearance.stroke_at_mut(None).unwrap().width = 2.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [face.0, g.0]})).unwrap();
|
||||
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke");
|
||||
}
|
||||
|
||||
/// The Eyedropper onto a whole selected Live Paint group, or reversed onto a clicked one, gives the
|
||||
/// picked fill attributes to its faces and the picked stroke attributes to its edges; its hidden
|
||||
/// source paths keep their paint.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges() {
|
||||
for reverse in [false, true] {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [src.0], "weight": 3})).unwrap();
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
let sources0 = sources_looks(&s, g);
|
||||
if reverse {
|
||||
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": g.0, "reverse": true})).unwrap();
|
||||
} else {
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
|
||||
}
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
|
||||
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
|
||||
for (f, f0) in faces1.iter().zip(&faces0) {
|
||||
assert_eq!(f.fill_paint(), magenta, "reverse {reverse}: a face takes the fill");
|
||||
assert_eq!((f.stroke_paint(), f.stroke_width()), (f0.stroke_paint(), f0.stroke_width()), "reverse {reverse}: a face takes no stroke");
|
||||
}
|
||||
for (e, e0) in edges1.iter().zip(&edges0) {
|
||||
assert_eq!((e.stroke_paint(), e.stroke_width()), (blue.clone(), 3.0), "reverse {reverse}: an edge takes the stroke");
|
||||
assert_eq!(e.fill_paint(), e0.fill_paint(), "reverse {reverse}: an edge takes no fill");
|
||||
}
|
||||
assert_eq!(sources_looks(&s, g), sources0, "reverse {reverse}: the hidden source paths keep their paint");
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole-appearance Eyedropper pick of a source with several fills and strokes gives each face
|
||||
/// of a selected Live Paint group every fill row and each edge every stroke row.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_gives_every_fill_and_stroke_row() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [src.0]})).unwrap();
|
||||
s.execute("appearance.addStroke", &json!({"ids": [src.0]})).unwrap();
|
||||
let kinds = |a: &vectorcraft_doc::Appearance, fill: bool| a.items.iter().filter(|it| it.is_fill() == fill).count();
|
||||
let source = (*node(&s, src).appearance).clone();
|
||||
assert_eq!((kinds(&source, true), kinds(&source, false)), (2, 2));
|
||||
// A face with a stroke row below its fill keeps that row below the picked fills.
|
||||
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(face).unwrap();
|
||||
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 9.0)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
let order: Vec<bool> = faces1[0].items.iter().map(|it| it.is_fill()).collect();
|
||||
assert_eq!(order.first(), Some(&false), "the face's lower stroke row stays below its fills: {order:?}");
|
||||
for (f, f0) in faces1.iter().zip(&faces0) {
|
||||
assert_eq!(kinds(f, true), 2, "a face takes every fill row");
|
||||
assert_eq!(kinds(f, false), kinds(f0, false), "a face keeps its strokes");
|
||||
}
|
||||
for (e, e0) in edges1.iter().zip(&edges0) {
|
||||
assert_eq!(kinds(e, false), 2, "an edge takes every stroke row");
|
||||
assert_eq!(kinds(e, true), kinds(e0, true), "an edge keeps its fills");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Appearance panel's edits of a Live Paint group's contents (`target: "contents"`) follow the
|
||||
/// group's rule: a new fill goes on its faces, a new stroke on its edges, and its hidden source paths
|
||||
/// keep their appearance under every contents edit.
|
||||
#[test]
|
||||
fn live_paint_group_contents_edits_follow_the_group_rule() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
let sources0 = sources_looks(&s, g);
|
||||
s.execute("appearance.addFill", &json!({"target": "contents"})).unwrap();
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() == f0.items.len() + 1), "every face takes a new fill");
|
||||
assert_eq!(edges1, edges0, "edges take no new fill");
|
||||
s.execute("appearance.addStroke", &json!({"target": "contents"})).unwrap();
|
||||
let (faces2, edges2) = part_looks(&s, g);
|
||||
assert_eq!(faces2, faces1, "faces take no new stroke");
|
||||
assert!(edges2.iter().zip(&edges1).all(|(e, e0)| e.items.len() == e0.items.len() + 1), "every edge takes a new stroke");
|
||||
// A stroke row edit of the contents reaches the edges, not the faces.
|
||||
s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 7})).unwrap();
|
||||
let (faces3, edges3) = part_looks(&s, g);
|
||||
assert_eq!(faces3, faces2, "faces keep their rows");
|
||||
assert!(edges3.iter().all(|e| e.stroke_at(Some(0)).map(|st| st.width) == Some(7.0)), "every edge's stroke row takes the weight");
|
||||
s.execute("appearance.clear", &json!({"target": "contents"})).unwrap();
|
||||
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their appearance");
|
||||
}
|
||||
|
||||
/// Fill edits of a Live Paint group's contents with an `item` (a gradient vector, Invert, Overprint
|
||||
/// Fill) change its faces and leave an edge's fill row as it is, and Overprint on the whole group goes
|
||||
/// to the faces' fills and the edges' strokes, leaving the hidden source paths as they are.
|
||||
#[test]
|
||||
fn live_paint_group_item_edits_and_overprint_follow_the_group_rule() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
|
||||
// Each edge gets a copy of a face's gradient fill row, below its stroke.
|
||||
let n = node(&s, g);
|
||||
let face_row = vectorcraft_tools::builder::faces(&n)[0].appearance.items[0].clone();
|
||||
let edge_ids: Vec<NodeId> = vectorcraft_tools::builder::edges(&n).iter().map(|e| e.id).collect();
|
||||
let mut face_ids: Vec<u64> = vectorcraft_tools::builder::faces(&n).iter().map(|f| f.id.0).collect();
|
||||
face_ids.sort_unstable();
|
||||
s.edit("t", |d, _| {
|
||||
for e in &edge_ids {
|
||||
d.node_mut(*e).unwrap().appearance.items.insert(0, face_row.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
let sources0 = sources_looks(&s, g);
|
||||
let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "item": 0, "target": "contents", "start": [0, 0], "end": [100, 0]})).unwrap();
|
||||
let mut changed: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
changed.sort_unstable();
|
||||
assert_eq!(changed, face_ids, "only the faces take the vector");
|
||||
assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row keeps its vector");
|
||||
let stops = |a: &vectorcraft_doc::Appearance| match a.fill_paint() {
|
||||
Paint::Gradient(gr) => gr.gradient.stops.iter().map(|st| st.color).collect::<Vec<_>>(),
|
||||
_ => vec![],
|
||||
};
|
||||
let before: Vec<_> = part_looks(&s, g).0.iter().map(stops).collect();
|
||||
s.execute("paint.invert", &json!({"stroke": false, "item": 0, "target": "contents"})).unwrap();
|
||||
for (f, b) in part_looks(&s, g).0.iter().zip(&before) {
|
||||
assert_eq!(stops(f), b.iter().rev().copied().collect::<Vec<_>>(), "the black-to-white stops of a face's fill are inverted");
|
||||
}
|
||||
assert_ne!(part_looks(&s, g).0, faces0);
|
||||
assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row is not inverted");
|
||||
s.execute("object.setOverprint", &json!({"fill": true, "item": 0, "target": "contents"})).unwrap();
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
assert!(faces1.iter().all(|f| f.items[0].overprint()), "the faces' fill overprints");
|
||||
assert_eq!(edges1, edges0, "an edge's fill row does not overprint");
|
||||
s.execute("object.setOverprint", &json!({"fill": true, "stroke": true})).unwrap();
|
||||
let (_, edges2) = part_looks(&s, g);
|
||||
assert!(edges2.iter().all(|e| e.items.iter().all(|it| it.overprint() != it.is_fill())), "only the edges' strokes overprint");
|
||||
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their flags");
|
||||
}
|
||||
|
||||
/// A face selected before an ordinary group that holds its Live Paint group counts with that group:
|
||||
/// the Stroke panel shows the edges' stroke.
|
||||
#[test]
|
||||
fn live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(face).unwrap();
|
||||
n.appearance.set_stroke(Paint::solid(Color::BLACK));
|
||||
n.appearance.stroke_at_mut(None).unwrap().width = 2.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [face.0, outer.0]})).unwrap();
|
||||
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke");
|
||||
assert!(!s.active().unwrap().stroke_mixed().weight, "the face's own stroke does not make the weight mixed");
|
||||
// An unfilled edge selected with the outer group does not make the faces' fill mixed.
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
|
||||
s.execute("select.set", &json!({"ids": [edge.0, outer.0]})).unwrap();
|
||||
let r = s.execute("paint.proxies", &json!({})).unwrap();
|
||||
assert_eq!(r["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#ff0000").unwrap())).unwrap());
|
||||
assert_eq!(r["fillMixed"], false, "the edge counts with its group");
|
||||
}
|
||||
|
||||
/// The Eyedropper picks up a whole Live Paint group as its faces' fill under its edges' stroke, and
|
||||
/// `append` onto a whole group adds the picked fills and strokes without the picked effects.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(g).unwrap().opacity = 0.5;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap();
|
||||
let a = (*node(&s, target).appearance).clone();
|
||||
assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill");
|
||||
assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke");
|
||||
assert_eq!(node(&s, target).opacity, 0.5, "the group's own opacity");
|
||||
// A Live Paint group with no face and no edge is not picked up: the next selected object is.
|
||||
let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
|
||||
let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let en = node(&s, e);
|
||||
let parts: Vec<NodeId> =
|
||||
vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect();
|
||||
assert!(!parts.is_empty());
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, e)));
|
||||
let other = rect(&mut s, 700.0, 0.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#00ff00"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [e.0, other.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap();
|
||||
assert_eq!(node(&s, target).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()), "the next selected object's fill");
|
||||
// Append a source with a drop shadow onto the whole group.
|
||||
let src = rect(&mut s, 500.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
|
||||
assert!(!node(&s, src).appearance.effects.is_empty());
|
||||
let (faces0, edges0) = part_looks(&s, g);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": src.0, "append": true})).unwrap();
|
||||
let (faces1, edges1) = part_looks(&s, g);
|
||||
for (p, p0) in faces1.iter().chain(&edges1).zip(faces0.iter().chain(&edges0)) {
|
||||
assert_eq!(p.effects, p0.effects, "a face or edge takes no effect");
|
||||
}
|
||||
assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() > f0.items.len()), "every face takes the fill");
|
||||
}
|
||||
|
||||
/// Reversed onto a clicked object, an empty Live Paint group first in the selection passes to the next
|
||||
/// selected Live Paint group, whose faces' fill and edges' stroke are both picked up.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
|
||||
let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
|
||||
let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let en = node(&s, e);
|
||||
let parts: Vec<NodeId> =
|
||||
vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect();
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
|
||||
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true, "ids": [e.0, g.0]})).unwrap();
|
||||
let a = (*node(&s, target).appearance).clone();
|
||||
assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill");
|
||||
assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke");
|
||||
}
|
||||
|
||||
/// An Eyedropper pick whose source is the selected Live Paint group leaves the group's own faces and
|
||||
/// edges as they are.
|
||||
#[test]
|
||||
fn live_paint_group_eyedropper_does_not_target_its_own_source_group() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap();
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap();
|
||||
let before = part_looks(&s, g);
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": g.0})).unwrap();
|
||||
assert_eq!(part_looks(&s, g), before);
|
||||
}
|
||||
|
||||
/// A Live Paint group left with only its hidden source paths is still a selection: a stroke edit of its
|
||||
/// contents changes nothing and leaves the settings for new art as they are.
|
||||
#[test]
|
||||
fn live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let n = node(&s, g);
|
||||
let parts: Vec<NodeId> = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect();
|
||||
s.edit("t", |d, _| {
|
||||
d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke());
|
||||
s.execute("stroke.setAdvanced", &json!({"target": "contents", "item": 0, "arrowScale": [200, 150]})).unwrap();
|
||||
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
|
||||
}
|
||||
|
||||
/// Adding a fill or a stroke to the contents of a Live Paint group left with only its hidden source paths
|
||||
/// succeeds and changes nothing, while an empty selection is still refused.
|
||||
#[test]
|
||||
fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let n = node(&s, g);
|
||||
let parts: Vec<NodeId> = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect();
|
||||
s.edit("t", |d, _| {
|
||||
d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let before = node(&s, g);
|
||||
for cmd in ["appearance.addFill", "appearance.addStroke"] {
|
||||
s.execute(cmd, &json!({"target": "contents"})).unwrap();
|
||||
assert_eq!(node(&s, g), before, "{cmd} changes nothing");
|
||||
}
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused");
|
||||
}
|
||||
|
||||
/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
|
||||
/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
|
||||
/// leaves the settings for new art as they are.
|
||||
@@ -4304,6 +4651,8 @@ fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() {
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
s.execute("stroke.weightUp", &json!({})).unwrap();
|
||||
s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap();
|
||||
// A stroke row edit of the group's contents finds no edge either.
|
||||
s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 9})).unwrap();
|
||||
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
|
||||
assert_eq!(part_looks(&s, g), looks);
|
||||
|
||||
@@ -9280,6 +9629,111 @@ fn image_trace_built_in_presets_cannot_be_saved_over_or_deleted() {
|
||||
assert_eq!(six["params"], serde_json::to_value(vectorcraft_trace::preset("6 Colors").unwrap()).unwrap());
|
||||
}
|
||||
|
||||
/// Saved tracing presets go out to a .vctracepresets file and come back with their names and
|
||||
/// settings; a hand-written file in the documented layout imports too.
|
||||
#[test]
|
||||
fn image_trace_presets_export_and_import_round_trip() {
|
||||
let mut s = session();
|
||||
assert!(s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string().contains("no saved tracing presets"));
|
||||
s.execute("imageTrace.presets.save", &json!({"name": "Poster", "preset": "6 Colors", "params": {"noise": 40, "ignoreWhite": true}})).unwrap();
|
||||
s.execute("imageTrace.presets.save", &json!({"name": "Ink", "params": {"threshold": 90, "fills": false, "strokes": true}})).unwrap();
|
||||
let e = s.execute("imageTrace.presets.export", &json!({"names": ["Default"]})).unwrap_err().to_string();
|
||||
assert!(e.contains("only saved presets are exported"), "{e}");
|
||||
assert!(s.execute("imageTrace.presets.export", &json!({"names": ["Nope"]})).is_err());
|
||||
let all = s.execute("imageTrace.presets.export", &json!({})).unwrap();
|
||||
assert_eq!(all["count"], 2);
|
||||
let one = s.execute("imageTrace.presets.export", &json!({"names": ["poster", "Poster"]})).unwrap();
|
||||
assert_eq!(one["count"], 1);
|
||||
let file: Value = serde_json::from_str(all["data"].as_str().unwrap()).unwrap();
|
||||
assert_eq!((file["format"].as_str(), file["version"].as_u64()), (Some("vctracepresets"), Some(1)));
|
||||
let saved = s.prefs.trace_presets.clone();
|
||||
// Into a session without them: the same names and settings, and a new revision the panel follows.
|
||||
let mut t = session();
|
||||
let before = t.trace_presets_revision();
|
||||
let r = t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap();
|
||||
assert_eq!(r, json!({"imported": ["Poster", "Ink"], "replaced": [], "skipped": []}));
|
||||
assert_eq!(t.prefs.trace_presets, saved);
|
||||
assert_eq!(t.trace_presets_revision(), before + 2);
|
||||
// A file written by hand in the documented layout: missing settings are Default's.
|
||||
let hand = r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Hand", "params": {"mode": "grayscale", "colors": 12}}]}"#;
|
||||
t.execute("imageTrace.presets.import", &json!({ "dataBase64": vectorcraft_format::base64_encode(hand.as_bytes()) })).unwrap();
|
||||
let hand = t.trace_preset("hand").unwrap().params.clone();
|
||||
assert_eq!((hand.mode, hand.colors, hand.threshold), (vectorcraft_trace::Mode::Grayscale, 12, 128));
|
||||
}
|
||||
|
||||
/// Export writes no file that import would refuse (more than 1,000 presets, or more than 4 MiB),
|
||||
/// and no more than 1,000 tracing presets can be saved.
|
||||
#[test]
|
||||
fn image_trace_presets_export_keeps_to_what_import_reads() {
|
||||
let mut s = session();
|
||||
let params = vectorcraft_trace::preset("Default").unwrap();
|
||||
let preset = |name: String| crate::cmd::TracePreset { name, params: params.clone() };
|
||||
s.prefs.trace_presets = (1..=1001).map(|i| preset(format!("P{i}"))).collect();
|
||||
let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("more than one file holds (1000)"), "{e}");
|
||||
s.prefs.trace_presets.pop();
|
||||
let all = s.execute("imageTrace.presets.export", &json!({})).unwrap();
|
||||
assert_eq!(all["count"], 1000);
|
||||
let mut t = session();
|
||||
assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap()["imported"].as_array().map(Vec::len), Some(1000));
|
||||
// No more can be saved or imported then, so every saved preset still fits in one file; a
|
||||
// saved preset can still change, and a file of saved names still replaces them.
|
||||
let e = t.execute("imageTrace.presets.save", &json!({"name": "One More"})).unwrap_err().to_string();
|
||||
assert!(e.contains("delete one first"), "{e}");
|
||||
t.execute("imageTrace.presets.save", &json!({"name": "P1", "params": {"noise": 9}})).unwrap();
|
||||
let one = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "Fresh", "params": {}}]}).to_string();
|
||||
let e = t.execute("imageTrace.presets.import", &json!({ "data": one })).unwrap_err().to_string();
|
||||
assert!(e.contains("more than 1000 saved"), "{e}");
|
||||
let again = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "P2", "params": {}}]}).to_string();
|
||||
assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": again, "replace": true})).unwrap()["replaced"], json!(["P2"]));
|
||||
assert_eq!(t.prefs.trace_presets.len(), 1000);
|
||||
s.prefs.trace_presets = vec![preset("x".repeat(4 << 20))];
|
||||
let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("larger than 4 MiB"), "{e}");
|
||||
}
|
||||
|
||||
/// A saved preset of the same name is skipped unless `replace` is on; a file with a fault, or one
|
||||
/// too large, changes nothing.
|
||||
#[test]
|
||||
fn image_trace_presets_import_checks_the_whole_file_first() {
|
||||
let mut s = session();
|
||||
s.execute("imageTrace.presets.save", &json!({"name": "Poster", "params": {"noise": 40}})).unwrap();
|
||||
let file = |rows: Value| json!({"format": "vctracepresets", "version": 1, "presets": rows}).to_string();
|
||||
let data = file(json!([{"name": "poster", "params": {"noise": 7}}, {"name": "Fresh", "params": {}}]));
|
||||
let r = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap();
|
||||
assert_eq!(r, json!({"imported": ["Fresh"], "replaced": [], "skipped": ["poster"]}));
|
||||
assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 40);
|
||||
let r = s.execute("imageTrace.presets.import", &json!({"data": data, "replace": true})).unwrap();
|
||||
assert_eq!(r, json!({"imported": [], "replaced": ["Poster", "Fresh"], "skipped": []}));
|
||||
assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 7);
|
||||
assert!(s.execute("imageTrace.presets.import", &json!({"data": data, "replace": "yes"})).is_err());
|
||||
let saved = s.prefs.trace_presets.clone();
|
||||
let revision = s.trace_presets_revision();
|
||||
let bad_files = [
|
||||
(file(json!([{"name": "New One", "params": {}}, {"name": "[Default]", "params": {}}])), "built-in preset"),
|
||||
(file(json!([{"name": "custom", "params": {}}])), "built-in preset"),
|
||||
(file(json!([{"name": "Twice", "params": {}}, {"name": "twice", "params": {}}])), "two presets named"),
|
||||
(file(json!([{"name": " ", "params": {}}])), "has no name"),
|
||||
(file(json!([{"name": "No Params"}])), "has no `params`"),
|
||||
(file(json!([{"name": "Neither", "params": {"fills": false, "strokes": false}}])), "Create needs fills"),
|
||||
(file(json!([{"name": "Typo", "params": {"nosie": 3}}])), "nosie"),
|
||||
(json!({"format": "vctracepresets", "version": 2, "presets": []}).to_string(), "newer"),
|
||||
(json!({"format": "vcflattener", "version": 1, "presets": []}).to_string(), "not a tracing presets file"),
|
||||
("{".to_string(), "not a tracing presets file"),
|
||||
(file(Value::Array(vec![json!({"name": "x", "params": {}}); 1001])), "more than 1000"),
|
||||
(" ".repeat((4 << 20) + 1), "larger than 4 MiB"),
|
||||
];
|
||||
for (data, why) in bad_files {
|
||||
let e = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap_err().to_string();
|
||||
assert!(e.contains(why), "{why}: {e}");
|
||||
}
|
||||
let big = vectorcraft_format::base64_encode(&vec![b' '; (4 << 20) + 1]);
|
||||
assert!(s.execute("imageTrace.presets.import", &json!({ "dataBase64": big })).unwrap_err().to_string().contains("larger than 4 MiB"));
|
||||
assert!(s.execute("imageTrace.presets.import", &json!({})).is_err());
|
||||
assert_eq!(s.prefs.trace_presets, saved, "nothing changed");
|
||||
assert_eq!(s.trace_presets_revision(), revision);
|
||||
}
|
||||
|
||||
/// Saved tracing presets are kept with the preferences, are not a preference key, and survive
|
||||
/// resetting the preferences.
|
||||
#[test]
|
||||
|
||||
@@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() {
|
||||
assert!(!node(&s, id).extras().pixel_aligned);
|
||||
}
|
||||
|
||||
/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a
|
||||
/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other
|
||||
/// `anchors` value is an error and draws nothing.
|
||||
#[test]
|
||||
fn anchors_at_the_points_puts_an_anchor_at_each_point() {
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
|
||||
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap());
|
||||
let n = node(&s, id);
|
||||
let anchors: Vec<Point> = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}");
|
||||
assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind);
|
||||
assert!(!n.extras().pixel_aligned);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap());
|
||||
let anchors: Vec<Point> = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(anchors.len(), 4, "{anchors:?}");
|
||||
assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0)));
|
||||
let (count, undo) = (object_count(&s), undo_len(&s));
|
||||
for bad in [json!("corners"), json!(true), json!(4), Value::Null] {
|
||||
let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string();
|
||||
assert!(e.contains("`anchors` must be one of standard, points"), "{e}");
|
||||
}
|
||||
assert_eq!((object_count(&s), undo_len(&s)), (count, undo));
|
||||
}
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..ViewInfo::default() }
|
||||
}
|
||||
|
||||
@@ -127,6 +127,25 @@ fn c_flips_and_brackets_size_the_last_sharp_arc() {
|
||||
assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
|
||||
}
|
||||
|
||||
/// The drawing end (where the Quick Pen toolbar sits beside) is the path's last point with the
|
||||
/// direction it arrives in: none before the first click, no direction for one point, and none
|
||||
/// once Escape ends the path.
|
||||
#[test]
|
||||
fn the_drawing_end_is_the_last_point_and_its_direction() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
assert_eq!(s.tool_drawing_end(view()), None);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
assert_eq!(s.tool_drawing_end(view()), Some((pt(100.0, 100.0), None)));
|
||||
click(&mut s, 100.0, 200.0);
|
||||
let (p, dir) = s.tool_drawing_end(view()).unwrap();
|
||||
assert_eq!(p, pt(100.0, 200.0));
|
||||
let dir = dir.unwrap();
|
||||
assert!(dir.x.abs() < 1e-9 && dir.y > 0.99, "arrives heading down: {dir:?}");
|
||||
key(&mut s, ToolKey::Escape);
|
||||
assert_eq!(s.tool_drawing_end(view()), None);
|
||||
}
|
||||
|
||||
/// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a
|
||||
/// sharp-corner arc with a corner where it starts, and the path goes on drawing after it.
|
||||
#[test]
|
||||
@@ -183,6 +202,251 @@ fn escape_ends_the_path_and_a_drag_places_the_piece() {
|
||||
assert_eq!(paths(&s).len(), 2);
|
||||
}
|
||||
|
||||
/// The piece a press draws ends where the press is let go, past the last drag too, and a press let
|
||||
/// go a drag's distance away with no drag in between places it there as well.
|
||||
#[test]
|
||||
fn the_piece_ends_where_the_press_is_let_go() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 120.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 150.0), v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0));
|
||||
let undo = undo_steps(&s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 100.0), v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(340.0, 100.0));
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// C and `[` `]` during a drag change the sharp-corner arc being dragged, within the press's one
|
||||
/// undo step.
|
||||
#[test]
|
||||
fn c_and_brackets_during_a_drag_change_the_arc_being_dragged() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
let undo = undo_steps(&s);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap();
|
||||
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
|
||||
key(&mut s, ToolKey::Letter('c'));
|
||||
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "flipped while dragging");
|
||||
key(&mut s, ToolKey::BracketLeft);
|
||||
assert_eq!(s.tool_options()["turn"], 165.0);
|
||||
// A 165° arc is two segments, and its middle point lies the arc's sagitta below the chord
|
||||
// (a 180° arc's lies 100 below).
|
||||
let half = 82.5f64.to_radians();
|
||||
let mid_165 = pt(200.0, 300.0 + 100.0 / half.sin() * (1.0 - half.cos()));
|
||||
assert_eq!(only_path(&s).anchors.len(), 3);
|
||||
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the dragged arc is 165°");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
|
||||
let sp = only_path(&s);
|
||||
assert_eq!(sp.anchors.len(), 3);
|
||||
assert!(sp.anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the flip and the size stay after the release");
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// An edit made by another command during a drag ends the path: the next drag does not draw over
|
||||
/// the edit, the piece stays as last shown, and the next click starts a new path.
|
||||
#[test]
|
||||
fn an_edit_during_a_drag_ends_the_path() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let id = paths(&s)[0].0;
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the edit and the piece as last shown");
|
||||
click(&mut s, 400.0, 400.0);
|
||||
assert_eq!(paths(&s).len(), 2, "a new path");
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, a sharp-corner arc let go past the last drag is placed where it was
|
||||
/// let go, and C then flips that arc.
|
||||
#[test]
|
||||
fn a_deferred_arc_let_go_past_the_last_drag_flips() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 270.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
|
||||
let sp = only_path(&s);
|
||||
assert_eq!(sp.anchors.len(), 3);
|
||||
assert_eq!(sp.anchors.last().unwrap().p, pt(300.0, 300.0));
|
||||
let mid = sp.anchors.get(1).unwrap().p;
|
||||
key(&mut s, ToolKey::Letter('c'));
|
||||
let flipped = only_path(&s);
|
||||
assert_eq!(flipped.anchors.len(), 3);
|
||||
assert!(flipped.anchors.get(1).unwrap().p.distance(pt(200.0, 600.0 - mid.y)) < 1e-9, "flipped across the chord");
|
||||
}
|
||||
|
||||
/// An edit made by another command to the path's look during a drag ends the path too.
|
||||
#[test]
|
||||
fn a_look_edit_during_a_drag_ends_the_path() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let id = paths(&s)[0].0;
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown");
|
||||
click(&mut s, 400.0, 400.0);
|
||||
assert_eq!(paths(&s).len(), 2, "a new path");
|
||||
}
|
||||
|
||||
/// An edit made by another command to another object during a drag stays and ends the path: the
|
||||
/// press previews no more, its piece stays as last shown, and the next click starts a new path.
|
||||
#[test]
|
||||
fn an_edit_to_another_object_during_a_drag_stays() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap();
|
||||
let rect = s.doc().unwrap().selection.objects[0];
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
|
||||
let edited = s.doc().unwrap().doc.node(rect).unwrap().clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays");
|
||||
let pen = paths(&s).into_iter().find(|(id, _)| *id != rect).unwrap().1;
|
||||
let ends: Vec<Point> = pen.subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown");
|
||||
click(&mut s, 400.0, 400.0);
|
||||
assert_eq!(paths(&s).len(), 3, "a new path");
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, a drag during which another command edits the path adds no piece,
|
||||
/// and the edit stays.
|
||||
#[test]
|
||||
fn an_edit_during_a_deferred_drag_stays() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let id = paths(&s)[0].0;
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
|
||||
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0)], "the edit, and no piece");
|
||||
}
|
||||
|
||||
/// An edit made by another command to another object during a click stays, and the path goes on:
|
||||
/// a click previews its piece only when the press begins.
|
||||
#[test]
|
||||
fn an_edit_to_another_object_during_a_click_stays() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap();
|
||||
let rect = s.doc().unwrap().selection.objects[0];
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
|
||||
let edited = s.doc().unwrap().doc.node(rect).unwrap().clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays");
|
||||
click(&mut s, 300.0, 200.0);
|
||||
let all = paths(&s);
|
||||
assert_eq!(all.len(), 2, "no new path");
|
||||
let pen = all.into_iter().find(|(id, _)| *id != rect).unwrap().1;
|
||||
let ends: Vec<Point> = pen.subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0), pt(300.0, 200.0)]);
|
||||
}
|
||||
|
||||
/// An edit made by another command during a click (a press let go where it went down) ends the
|
||||
/// path too: the next click starts a new path instead of drawing over the edit.
|
||||
#[test]
|
||||
fn an_edit_during_a_click_ends_the_path() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let id = paths(&s)[0].0;
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 180.0), v).unwrap();
|
||||
click(&mut s, 400.0, 400.0);
|
||||
assert_eq!(paths(&s).len(), 2, "a new path");
|
||||
let ends: Vec<Point> = paths(&s)[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect();
|
||||
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 180.0)], "the edit stays");
|
||||
}
|
||||
|
||||
/// With Align New Objects to Pixel Grid on, the path the tool draws is pixel-aligned: its points
|
||||
/// move onto the grid, and the next click and drag still go on drawing the same path.
|
||||
#[test]
|
||||
fn a_pixel_aligned_path_goes_on_drawing() {
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let ends = |s: &Session| only_path(s).anchors.iter().map(|a| a.p).collect::<Vec<Point>>();
|
||||
let two = ends(&s);
|
||||
assert_eq!(two.len(), 2);
|
||||
assert_eq!(two[0].y, two[1].y, "a level line");
|
||||
press(&mut s, &[(300.0, 150.0), (310.0, 170.0), (320.0, 200.0)]);
|
||||
let three = ends(&s);
|
||||
assert_eq!(three.len(), 3, "one path of three points");
|
||||
assert_eq!(three[..2], two[..], "the points before the piece stay as they were");
|
||||
assert!(three[2].distance(pt(320.0, 200.0)) <= 1.0, "the drag's piece ends near where it was let go: {:?}", three[2]);
|
||||
click(&mut s, 400.0, 100.0);
|
||||
let four = ends(&s);
|
||||
assert_eq!(four.len(), 4);
|
||||
assert_eq!(four[..3], three[..]);
|
||||
}
|
||||
|
||||
/// A dropped press takes back only its own piece, and with Real-time Drawing off a drag places its
|
||||
/// piece on the release: in both cases the next click goes on drawing the same path.
|
||||
#[test]
|
||||
fn a_dropped_press_and_a_deferred_drag_keep_the_path() {
|
||||
let mut s = session();
|
||||
quick_pen(&mut s);
|
||||
click(&mut s, 100.0, 100.0);
|
||||
click(&mut s, 200.0, 100.0);
|
||||
let v = view();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 150.0), v).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert_eq!(only_path(&s).anchors.len(), 2, "the dropped piece is gone");
|
||||
click(&mut s, 300.0, 200.0);
|
||||
assert_eq!(only_path(&s).anchors.len(), 3, "the path goes on");
|
||||
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
press(&mut s, &[(400.0, 200.0), (420.0, 250.0), (450.0, 300.0)]);
|
||||
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(450.0, 300.0));
|
||||
click(&mut s, 500.0, 100.0);
|
||||
assert_eq!(only_path(&s).anchors.len(), 5, "the path goes on after the deferred piece");
|
||||
}
|
||||
|
||||
/// An anchor moved by another command ends the path being drawn: C does not flip the old arc back
|
||||
/// over the edit, and the next click starts a new path instead of rebuilding the old one.
|
||||
#[test]
|
||||
|
||||
@@ -133,6 +133,174 @@ fn colors_with_nothing_selected_leave_out_what_select_all_leaves_out() {
|
||||
assert_eq!(hexes(&run(&mut s, "recolor.colors", json!({"ids": [hidden.0]}))), ["#0000ff"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_list_the_most_used_first_with_their_colors() {
|
||||
let mut s = session();
|
||||
let reds: Vec<NodeId> = (0..3).map(|_| rect(&mut s, json!("#ff0000"))).collect();
|
||||
let blue = rect(&mut s, json!({"c": 100, "m": 100, "y": 0, "k": 0}));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
assert_eq!(r["selection"], false, "{r}");
|
||||
let colors = r["colors"].as_array().unwrap();
|
||||
assert_eq!(colors.len(), 2, "{r}");
|
||||
assert_eq!((colors[0]["key"].as_str(), colors[0]["hex"].as_str(), colors[0]["count"].as_u64()), (Some("rgb 255 0 0"), Some("#ff0000"), Some(3)));
|
||||
assert_eq!(colors[1]["count"], 1);
|
||||
let first = run(&mut s, "color.used", json!({"limit": 1}));
|
||||
assert_eq!(first["colors"], json!([colors[0]]), "`limit` keeps the most used");
|
||||
assert_eq!((r["uses"].clone(), first["uses"].clone()), (json!(4), json!(4)), "`uses` counts every color");
|
||||
// `color` is the color in its own model, which the paint commands take back.
|
||||
assert_eq!(colors[1]["color"]["model"], "cmyk", "{r}");
|
||||
assert!(close(color_value(&colors[1]["color"]).unwrap(), fill(&s, blue)));
|
||||
// The selection's colors while something is selected; `selection: false` reads all the art.
|
||||
run(&mut s, "select.set", json!({"ids": [blue.0]}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
assert_eq!((r["selection"].clone(), r["colors"].as_array().unwrap().len()), (json!(true), 1), "{r}");
|
||||
let all = run(&mut s, "color.used", json!({"selection": false}));
|
||||
assert_eq!((all["selection"].clone(), all["colors"][0]["count"].clone()), (json!(false), json!(3)), "{all}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [blue], "the selection is left as it was");
|
||||
// A hidden object's color is left out with nothing selected, as Select All leaves it out.
|
||||
run(&mut s, "object.hide", json!({"ids": [reds[0].0]}));
|
||||
assert_eq!(run(&mut s, "color.used", json!({"selection": false}))["colors"][0]["count"], 2);
|
||||
let e = s.execute("color.used", &json!({"selection": "no"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`selection` must be true or false"), "{e}");
|
||||
assert!(s.execute("color.used", &json!({"ids": [blue.0]})).is_err(), "an unknown key is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
let tinted = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [tinted.0], "swatch": "Ink", "tint": 40}));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
let c = &r["colors"][0];
|
||||
assert_eq!(c["swatch"].as_str(), Some("Ink"), "{r}");
|
||||
assert!((c["tint"].as_f64().unwrap() - 40.0).abs() < 1e-4, "{r}");
|
||||
// recolor.colors keeps its own fields.
|
||||
assert_eq!(run(&mut s, "recolor.colors", json!({}))["colors"][0].get("tint"), None);
|
||||
// A swatch of paper white looks the same at every tint; the tint comes from the paint.
|
||||
run(&mut s, "swatch.new", json!({"name": "Paper", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true}));
|
||||
let paper = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [paper.0], "swatch": "Paper", "tint": 33.333}));
|
||||
run(&mut s, "select.set", json!({"ids": [paper.0]}));
|
||||
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
|
||||
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
|
||||
// The tint is the paint's own, unrounded.
|
||||
let vectorcraft_color::Paint::Solid { tint, .. } = s.doc().unwrap().doc.node(paper).unwrap().appearance.fill_paint() else {
|
||||
panic!("a solid fill")
|
||||
};
|
||||
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
|
||||
assert!((tint - 0.33333).abs() < 1e-5);
|
||||
// A pattern's tile keeps its tint as well.
|
||||
run(&mut s, "select.set", json!({"ids": [paper.0]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Sheet", "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let filled = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [filled.0], "swatch": "Sheet"}));
|
||||
run(&mut s, "select.set", json!({"ids": [filled.0]}));
|
||||
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
|
||||
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
|
||||
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_read_the_tiles_of_patterns_used_inside_pattern_tiles() {
|
||||
let mut s = session();
|
||||
let red = rect(&mut s, json!("#ff0000"));
|
||||
run(&mut s, "select.set", json!({"ids": [red.0]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let middle = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [middle.0], "swatch": "Inner"}));
|
||||
run(&mut s, "select.set", json!({"ids": [middle.0]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let square = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [square.0], "swatch": "Outer"}));
|
||||
// The inner tile's square is stroked with the outer pattern, so the two patterns use each other.
|
||||
let outer = s.doc().unwrap().doc.node(square).unwrap().appearance.fill_paint().clone();
|
||||
let st = s.doc_mut().unwrap();
|
||||
let doc = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let tile = doc.pattern_mut("Inner").unwrap().art.first_mut().unwrap();
|
||||
std::sync::Arc::make_mut(tile).appearance.set_stroke(outer);
|
||||
run(&mut s, "select.set", json!({"ids": [square.0]}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
let colors = r["colors"].as_array().unwrap();
|
||||
assert_eq!(colors.iter().map(|c| (c["hex"].as_str(), c["count"].as_u64())).collect::<Vec<_>>(), [(Some("#ff0000"), Some(1))], "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
let shape = rect(&mut s, json!("#000000"));
|
||||
let mixed = Color::Cmyk { c: 0.3, m: 0.5, y: 0.3, k: 0.0 };
|
||||
let stop = |color, plates| GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates, ..GradientStop::new(0.0, color) };
|
||||
let mut end = stop(Color::Cmyk { c: 0.0, m: 0.5, y: 0.3, k: 0.0 }, None);
|
||||
end.offset = 1.0;
|
||||
let g = Gradient::new(GradientKind::Linear, vec![stop(mixed, Some([0.3, 0.0, 0.0, 0.0])), end]);
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
let entry = |key: &str| r["colors"].as_array().unwrap().iter().find(|c| c["key"] == key).cloned().unwrap();
|
||||
let mix = entry("cmyk 30 50 30 0");
|
||||
assert_eq!((mix.get("swatch"), mix.get("tint")), (None, None), "{r}");
|
||||
assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}");
|
||||
// recolor.colors keeps the swatch it lists.
|
||||
let listed = run(&mut s, "recolor.colors", json!({}));
|
||||
assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_same_color() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
let shape = rect(&mut s, json!("#000000"));
|
||||
let plain = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Ink", "tint": 50}));
|
||||
let ink = fill(&s, plain);
|
||||
// The stop below the plain fill has the same color, and process plates that add nothing.
|
||||
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
|
||||
let mut end = stop.clone();
|
||||
end.offset = 1.0;
|
||||
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let r = run(&mut s, "color.used", json!({}));
|
||||
let c = r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
|
||||
assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recolor_colors_keeps_the_swatch_of_the_first_linked_use_when_a_mixed_stop_comes_first() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
|
||||
let shape = rect(&mut s, json!("#000000"));
|
||||
let plain = rect(&mut s, json!("#000000"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Other", "tint": 50}));
|
||||
let ink = fill(&s, plain);
|
||||
// The stop below the plain fill has the same color, linked to another swatch, with process
|
||||
// plates that add nothing.
|
||||
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
|
||||
let mut end = stop.clone();
|
||||
end.offset = 1.0;
|
||||
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let three = |r: &Value| r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
|
||||
let used = run(&mut s, "color.used", json!({}));
|
||||
assert_eq!(three(&used)["swatch"], "Other", "{used}");
|
||||
let listed = run(&mut s, "recolor.colors", json!({}));
|
||||
assert_eq!(three(&listed)["swatch"], "Ink", "recolor.colors names the first linked use: {listed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -856,6 +856,12 @@ impl Session {
|
||||
self.ruler_origin = None;
|
||||
}
|
||||
|
||||
/// A guide is being dragged out of a ruler ([`Session::ruler_guide`]): its first event came
|
||||
/// and its release has not.
|
||||
pub fn ruler_guide_dragging(&self) -> bool {
|
||||
self.ruler_guide.is_some()
|
||||
}
|
||||
|
||||
/// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the
|
||||
/// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event.
|
||||
pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result<Vec<UiRequest>> {
|
||||
@@ -1256,6 +1262,12 @@ impl Session {
|
||||
self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx))
|
||||
}
|
||||
|
||||
/// The point a path the active tool is drawing goes on from, and the direction the path
|
||||
/// arrives there in (see `Tool::drawing_end`).
|
||||
pub fn tool_drawing_end(&mut self, view: ViewInfo) -> Option<(Point, Option<vectorcraft_geom::Vec2>)> {
|
||||
self.with_tool_cx(view, |t, cx| t.drawing_end(cx))
|
||||
}
|
||||
|
||||
pub fn overlays(&mut self, view: ViewInfo) -> Vec<Overlay> {
|
||||
// The Blend tool's first pick is not marked after an edit that dropped it.
|
||||
self.tell_tool_history_moved();
|
||||
@@ -1478,6 +1490,9 @@ impl Session {
|
||||
}
|
||||
// Every value is checked before any is set, so an invalid one changes nothing.
|
||||
vectorcraft_tools::builder::check_builder_options(id, &values)?;
|
||||
if id == vectorcraft_tools::circle::ID {
|
||||
vectorcraft_tools::circle::check_options(&values)?;
|
||||
}
|
||||
vectorcraft_tools::symbolism::check_options(id, &values)?;
|
||||
if id == vectorcraft_tools::cropimage::ID {
|
||||
use vectorcraft_tools::cropimage as crop;
|
||||
|
||||
@@ -367,6 +367,61 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> {
|
||||
circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0)
|
||||
}
|
||||
|
||||
/// The circle at `center` with `radius` as a closed path whose anchors are `points` (points on the
|
||||
/// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two
|
||||
/// of them into equal parts of at most a quarter turn. The path starts at the first point and runs
|
||||
/// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of
|
||||
/// the radius along the tangents at its ends (θ, its turn). Two points with `center` at their
|
||||
/// midpoint give four anchors. A point given twice is one anchor; with no points it starts at the
|
||||
/// left, as [`ellipse`] does.
|
||||
pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData {
|
||||
let quarter = PI / 2.0;
|
||||
let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x);
|
||||
let start = points.first().map_or(PI, |p| angle(*p));
|
||||
// (turn from the first point, the point itself).
|
||||
let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect();
|
||||
placed.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
placed.dedup_by(|a, b| a.1 == b.1);
|
||||
// Two points with the center at their midpoint are the ends of a diameter: the second is half a
|
||||
// turn from the first, also where rounding moves the angle from the center off it.
|
||||
if let [(_, a), (turn, b)] = placed.as_mut_slice()
|
||||
&& a.midpoint(*b) == center
|
||||
{
|
||||
*turn = PI;
|
||||
}
|
||||
if placed.is_empty() {
|
||||
placed.push((0.0, Point::new(center.x - radius, center.y)));
|
||||
}
|
||||
let on_circle = |t: f64| Point::new(center.x + radius * (start + t).cos(), center.y + radius * (start + t).sin());
|
||||
// Every anchor: (turn, position), the given points where they are and the others on the circle.
|
||||
let mut turns: Vec<(f64, Point)> = Vec::new();
|
||||
for (i, &(t, p)) in placed.iter().enumerate() {
|
||||
turns.push((t, p));
|
||||
let next = placed.get(i + 1).map_or(TAU, |n| n.0);
|
||||
let gap = next - t;
|
||||
// At most 4 parts for the whole turn: a gap is never more than a full turn.
|
||||
let parts = (gap / quarter - 1e-9).ceil().clamp(1.0, 4.0);
|
||||
for k in 1..parts as u32 {
|
||||
let tk = t + gap * f64::from(k) / parts;
|
||||
turns.push((tk, on_circle(tk)));
|
||||
}
|
||||
}
|
||||
let n = turns.len();
|
||||
let anchors = (0..n)
|
||||
.filter_map(|i| {
|
||||
let &(t, p) = turns.get(i)?;
|
||||
let prev = if i == 0 { turns.last()?.0 - TAU } else { turns.get(i - 1)?.0 };
|
||||
let next = turns.get(i + 1).map_or(TAU, |n| n.0);
|
||||
// The unit tangent along the run (y down: increasing angle).
|
||||
let a = start + t;
|
||||
let tangent = Vec2::new(-a.sin(), a.cos());
|
||||
let handle = |turn: f64| radius * 4.0 / 3.0 * (turn / 4.0).tan();
|
||||
Some(Anchor { p, h_in: p - tangent * handle(t - prev), h_out: p + tangent * handle(next - t), kind: AnchorKind::Smooth })
|
||||
})
|
||||
.collect();
|
||||
PathData::single(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre.
|
||||
pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData {
|
||||
let n = sides.max(3);
|
||||
@@ -1146,6 +1201,53 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors are the given points exactly, plus enough more that no curve turns more than a
|
||||
/// quarter; every anchor and every curve's middle lies on the circle, and the path starts at
|
||||
/// the first point.
|
||||
#[test]
|
||||
fn a_circle_with_its_anchors_at_given_points() {
|
||||
use kurbo::ParamCurve;
|
||||
let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN);
|
||||
let center = Point::new(4.0, 3.0);
|
||||
for (points, count) in [(&[a, b][..], 4), (&[a, b, c][..], 5), (&[b, a, c, b][..], 5), (&[][..], 4)] {
|
||||
let path = circle_with_anchors_at(center, 5.0, points);
|
||||
let sub = &path.subpaths[0];
|
||||
assert!(sub.closed, "{points:?}");
|
||||
assert_eq!(sub.anchors.len(), count, "{points:?}: {sub:?}");
|
||||
for p in points {
|
||||
assert!(sub.anchors.iter().any(|q| q.p == *p), "{p:?} is an anchor: {sub:?}");
|
||||
}
|
||||
if let Some(first) = points.first() {
|
||||
assert_eq!(sub.anchors[0].p, *first);
|
||||
}
|
||||
for q in &sub.anchors {
|
||||
assert!((q.p.distance(center) - 5.0).abs() < 1e-9, "{q:?}");
|
||||
}
|
||||
for seg in path.to_bezpath().segments() {
|
||||
let turn = {
|
||||
let (p0, p1) = (seg.start() - center, seg.end() - center);
|
||||
p0.cross(p1).atan2(p0.dot(p1))
|
||||
};
|
||||
assert!(turn > 0.0 && turn <= PI / 2.0 + 1e-9, "{turn} for {seg:?}");
|
||||
assert!((seg.eval(0.5).distance(center) - 5.0).abs() < 5.0 * 1e-3, "{seg:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The two ends of a diameter give four anchors, also where the midpoint rounds off it: at
|
||||
/// x = 10⁶, steps of 2⁻³³ put the second point more than half a turn from the first, seen from
|
||||
/// the rounded center.
|
||||
#[test]
|
||||
fn a_diameter_gives_four_anchors_where_its_midpoint_rounds() {
|
||||
let u = 2f64.powi(-33);
|
||||
let (a, b) = (Point::new(1_000_000.0, 0.0), Point::new(1_000_000.0 + 9.0 * u, 8.0 * u));
|
||||
let (center, radius) = circle_through_points(&[a, b]).expect("a circle");
|
||||
let path = circle_with_anchors_at(center, radius, &[a, b]);
|
||||
let sub = &path.subpaths[0];
|
||||
assert_eq!(sub.anchors.len(), 4, "{sub:?}");
|
||||
assert_eq!((sub.anchors[0].p, sub.anchors[2].p), (a, b));
|
||||
}
|
||||
|
||||
/// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta
|
||||
/// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular
|
||||
/// bisector; a point 10⁻¹² off it does not.
|
||||
|
||||
@@ -699,6 +699,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again",
|
||||
),
|
||||
(
|
||||
"window.quickPenToolbar",
|
||||
"Quick Pen Toolbar",
|
||||
"",
|
||||
"{} show or hide the toolbar the Quick Pen tool shows on the canvas (toggles; returns whether it shows), as Window › Quick Pen Toolbar and the toolbar's More Options › Hide Toolbar do; selecting the Quick Pen tool shows it again",
|
||||
),
|
||||
(
|
||||
"window.quickPenToolbar.pin",
|
||||
"Pin Toolbar Position",
|
||||
"",
|
||||
"{pinned?: bool} keep the Quick Pen toolbar where it is in the canvas window instead of following the drawing (true), let it follow the drawing again from where it is (false) or toggle (omitted), as the toolbar's More Options menu does; returns the new state",
|
||||
),
|
||||
("window.quickPenToolbar.reset", "Reset Toolbar Position", "", "{} unpin the Quick Pen toolbar and put it back beside the drawing"),
|
||||
(
|
||||
"tool.quickPen.flipArc",
|
||||
"Flip Arc",
|
||||
"",
|
||||
"{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc",
|
||||
),
|
||||
(
|
||||
"window.dock",
|
||||
"Panels",
|
||||
@@ -1156,7 +1175,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; 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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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.setOpti
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), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), 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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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 To
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
@@ -1330,6 +1349,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings",
|
||||
),
|
||||
(
|
||||
"ui.tracingPresetsDialog",
|
||||
"Tracing Presets…",
|
||||
"",
|
||||
"{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset",
|
||||
),
|
||||
(
|
||||
"ui.flattenerPreview",
|
||||
"Flattener Preview",
|
||||
@@ -1579,7 +1604,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.colorWheel",
|
||||
"Color Wheel Options",
|
||||
"",
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision}",
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}",
|
||||
),
|
||||
(
|
||||
"ui.savePdfDialog",
|
||||
@@ -1907,7 +1932,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.hpglOptionsDialog",
|
||||
"HP-GL Options Dialog",
|
||||
"",
|
||||
"{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too",
|
||||
"{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks); OK after another document has become active closes the dialog and writes nothing. Export As… → HP-GL opens it too",
|
||||
),
|
||||
(
|
||||
"file.saveForWeb",
|
||||
|
||||
+260
-21
@@ -16,8 +16,17 @@
|
||||
//! circle passes through the points (two are the same, three lie on one line) or the circle would
|
||||
//! reach past the canvas, the tool shows none and the release draws nothing; for three different
|
||||
//! points on one line, or a circle past the canvas, the pointer shows "Circle too large".
|
||||
//!
|
||||
//! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences):
|
||||
//! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the
|
||||
//! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]);
|
||||
//! `standardAnchors` off puts the circle's anchors at the points it was drawn through instead of
|
||||
//! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with
|
||||
//! a click and draws the circle through three points with a third click, and a click on the second
|
||||
//! point again (as a double-click there does) draws the circle on the two points. Every option is
|
||||
//! on by default, and `color` is blue.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::MAX_COORD;
|
||||
use vectorcraft_geom::{Point, Rect, Vec2, shapes};
|
||||
|
||||
@@ -35,6 +44,71 @@ const REACH_PX: f64 = 3.0;
|
||||
/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes.
|
||||
const DASHED_PX: f64 = 50_000.0;
|
||||
|
||||
/// The colors the center cross and the radius lines can be drawn in, by option value. Blue is the
|
||||
/// feedback color the other drawing tools use.
|
||||
pub const COLORS: &[(&str, [u8; 3])] = &[
|
||||
("red", [0xe5, 0x2d, 0x27]),
|
||||
("blue", crate::draw2::FEEDBACK),
|
||||
("magenta", [0xd6, 0x2c, 0xd6]),
|
||||
("green", [0x1f, 0xb4, 0x4b]),
|
||||
("black", [0x00, 0x00, 0x00]),
|
||||
("gray", [0x80, 0x80, 0x80]),
|
||||
];
|
||||
|
||||
/// The option keys that are true or false.
|
||||
const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"];
|
||||
|
||||
/// The tool's options (see the module comment).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Options {
|
||||
center: bool,
|
||||
radii: bool,
|
||||
diameter: bool,
|
||||
/// An entry of [`COLORS`].
|
||||
color: usize,
|
||||
standard_anchors: bool,
|
||||
drag_third: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Options {
|
||||
fn switch(&mut self, key: &str) -> Option<&mut bool> {
|
||||
Some(match key {
|
||||
"center" => &mut self.center,
|
||||
"radii" => &mut self.radii,
|
||||
"diameter" => &mut self.diameter,
|
||||
"standardAnchors" => &mut self.standard_anchors,
|
||||
"dragThird" => &mut self.drag_third,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Is every value in `values` one the tool takes? `tool.setOption` checks them all before setting
|
||||
/// any; [`Tool::set_option`] skips a value it cannot read.
|
||||
pub fn check_options(values: &Map<String, Value>) -> Result<(), String> {
|
||||
for (key, v) in values {
|
||||
if SWITCHES.contains(&key.as_str()) {
|
||||
if !v.is_boolean() {
|
||||
return Err(format!("`{key}` must be true or false"));
|
||||
}
|
||||
} else if key == "color" {
|
||||
if !v.as_str().is_some_and(|s| COLORS.iter().any(|(name, _)| *name == s)) {
|
||||
let names: Vec<&str> = COLORS.iter().map(|(name, _)| *name).collect();
|
||||
return Err(format!("`{key}` must be one of {}", names.join(", ")));
|
||||
}
|
||||
} else {
|
||||
return Err(format!("unknown Circle tool option `{key}`"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The press in progress.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Press {
|
||||
@@ -47,23 +121,36 @@ enum Press {
|
||||
/// places the third point and the circle passes through `snapped`. A press within
|
||||
/// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let
|
||||
/// go there it places nothing, and dragged out it draws the circle on the diameter it drags out.
|
||||
/// With `dragThird` off, a drag moves the second point and the release places it.
|
||||
Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool },
|
||||
/// With `dragThird` off, the press after the second point was placed, at `at` (snapped). Let go
|
||||
/// on the second point (`on_second`), it draws the circle on the two points; let go on the
|
||||
/// first point it places nothing; otherwise it draws the circle through the three points.
|
||||
Third { at: Point, from: Point, on_first: bool, on_second: bool, dragged: bool },
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct CircleTool {
|
||||
snap: DrawSnap,
|
||||
options: Options,
|
||||
/// The first point, placed by a click (or by the press of a drag in progress).
|
||||
first: Option<Point>,
|
||||
/// With `dragThird` off, the second point, placed by a click where it is shown (snapped, with
|
||||
/// Alt's rounding of the diameter when Alt was held), and where the click let go: a press near
|
||||
/// either is a press on the second point, so the second click of a double-click finds it even
|
||||
/// where Alt's rounding moved it away from the pointer.
|
||||
second: Option<(Point, Point)>,
|
||||
press: Option<Press>,
|
||||
/// Where the pointer is, snapped: the point the next press or release places.
|
||||
pointer: Option<Point>,
|
||||
}
|
||||
|
||||
/// The command the tool runs for `points`.
|
||||
fn command(points: &[Point]) -> (String, Value) {
|
||||
/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are
|
||||
/// at the points.
|
||||
fn command(points: &[Point], standard_anchors: bool) -> (String, Value) {
|
||||
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
("shape.circleThroughPoints".into(), json!({ "points": pairs }))
|
||||
let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) };
|
||||
("shape.circleThroughPoints".into(), params)
|
||||
}
|
||||
|
||||
/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints`
|
||||
@@ -73,6 +160,17 @@ pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> {
|
||||
shapes::circle_through_points(points).filter(on_canvas)
|
||||
}
|
||||
|
||||
/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with
|
||||
/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its
|
||||
/// curves can reach slightly outside the circle.
|
||||
fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> {
|
||||
let fits = |(c, r): &(Point, f64)| {
|
||||
let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath());
|
||||
[b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)
|
||||
};
|
||||
circle_of(points).filter(|c| standard_anchors || fits(c))
|
||||
}
|
||||
|
||||
/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on
|
||||
/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and
|
||||
/// when that rounding leaves no distance.
|
||||
@@ -84,43 +182,65 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point
|
||||
|
||||
/// Are the points two or more different points through which no circle is drawn: three on one
|
||||
/// line, or a circle that would reach past the canvas?
|
||||
fn too_large(points: &[Point]) -> bool {
|
||||
fn too_large(points: &[Point], standard_anchors: bool) -> bool {
|
||||
let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p));
|
||||
points.len() >= 2 && distinct && circle_of(points).is_none()
|
||||
points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none()
|
||||
}
|
||||
|
||||
impl CircleTool {
|
||||
fn clear(&mut self) {
|
||||
self.first = None;
|
||||
self.second = None;
|
||||
self.press = None;
|
||||
self.pointer = None;
|
||||
self.snap.clear();
|
||||
}
|
||||
|
||||
/// How the second point keeps to the first: Shift's 45° steps and the construction guides.
|
||||
/// How the second point keeps to the first: Shift's 45° steps and the construction guides. A
|
||||
/// third point keeps to neither.
|
||||
fn leave(&self, cx: &ToolContext, mods: Mods) -> Option<Leave> {
|
||||
self.first.map(|a| Leave::segment(cx, a, mods.shift))
|
||||
self.first.filter(|_| self.second.is_none()).map(|a| Leave::segment(cx, a, mods.shift))
|
||||
}
|
||||
|
||||
/// The points the circle passes through as the tool shows it now.
|
||||
fn points(&self) -> Vec<Point> {
|
||||
let mut out: Vec<Point> = self.first.into_iter().collect();
|
||||
if let Some((b, _)) = self.second {
|
||||
match self.press {
|
||||
// Let go where it was pressed, a press on the first point draws nothing and one on
|
||||
// the second point draws the circle on the two.
|
||||
Some(Press::Third { on_first: true, dragged: false, .. }) => {}
|
||||
Some(Press::Third { on_second: true, dragged: false, .. }) => out.push(b),
|
||||
_ => {
|
||||
out.push(b);
|
||||
out.extend(self.pointer);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
match self.press {
|
||||
Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())),
|
||||
// A press on the first point adds no point: a drag from it drags out a diameter.
|
||||
Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)),
|
||||
Some(Press::Second { at, dragged: false, .. }) => out.push(at),
|
||||
// With `dragThird` off, a drag moves the second point.
|
||||
Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at),
|
||||
Some(Press::Second { snapped, dragged: true, .. }) => {
|
||||
out.push(snapped);
|
||||
out.extend(self.pointer);
|
||||
}
|
||||
Some(Press::Third { .. }) => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The second point as the tool shows it: none for a press on the first point.
|
||||
fn second(&self) -> Option<Point> {
|
||||
if let Some((b, _)) = self.second {
|
||||
return Some(b);
|
||||
}
|
||||
match self.press {
|
||||
Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at),
|
||||
Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at),
|
||||
Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped),
|
||||
_ => None,
|
||||
@@ -131,18 +251,34 @@ impl CircleTool {
|
||||
/// (the tool showed none), it only starts afresh.
|
||||
fn draw(&mut self, points: &[Point]) -> Vec<Action> {
|
||||
self.clear();
|
||||
if circle_of(points).is_none() {
|
||||
if drawn_circle(points, self.options.standard_anchors).is_none() {
|
||||
return vec![];
|
||||
}
|
||||
let (c, v) = command(points);
|
||||
let (c, v) = command(points, self.options.standard_anchors);
|
||||
vec![Action::Exec(c, v)]
|
||||
}
|
||||
|
||||
/// With `dragThird` off, the release of a press after the second point was placed: on the
|
||||
/// second point it draws the circle on the two points, on the first it places nothing, and
|
||||
/// elsewhere it draws the circle through the three, or keeps the points where none passes
|
||||
/// through them.
|
||||
fn third_up(&mut self, at: Point, on_first: bool, on_second: bool, dragged: bool) -> Vec<Action> {
|
||||
let (Some(a), Some((b, _))) = (self.first, self.second) else { return vec![] };
|
||||
if on_second && !dragged {
|
||||
return self.draw(&[a, b]);
|
||||
}
|
||||
if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() {
|
||||
self.snap.clear();
|
||||
return vec![];
|
||||
}
|
||||
self.draw(&[a, b, at])
|
||||
}
|
||||
|
||||
/// Is the press let go at `ev` a drag: is `ev` [`DRAG_PX`] or more from the press? A release
|
||||
/// nearer the press is a click, also after a drag that came back to it.
|
||||
fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool {
|
||||
match self.press {
|
||||
Some(Press::First { from, .. } | Press::Second { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX),
|
||||
Some(Press::First { from, .. } | Press::Second { from, .. } | Press::Third { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
@@ -173,6 +309,13 @@ impl Tool for CircleTool {
|
||||
*dragged = false;
|
||||
(*at, *on_first)
|
||||
}
|
||||
// With `dragThird` off, a click on the third point's press: the point goes back
|
||||
// to where it was pressed.
|
||||
Press::Third { at, from, dragged, .. } => {
|
||||
*dragged = false;
|
||||
*at = self.snap.press(cx, *from, &[], None);
|
||||
(*at, false)
|
||||
}
|
||||
};
|
||||
// A click on the first point places nothing: the pointer goes back to that point, so
|
||||
// the tool shows no circle.
|
||||
@@ -184,10 +327,27 @@ impl Tool for CircleTool {
|
||||
PointerKind::Move => {
|
||||
let leave = self.leave(cx, ev.mods);
|
||||
let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref());
|
||||
self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
|
||||
// Alt's rounding of the diameter is for the second point only.
|
||||
let rounds = self.first.filter(|_| self.second.is_none());
|
||||
self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
if let (Some(a), Some((b, clicked))) = (self.first, self.second) {
|
||||
let at = self.snap.press(cx, ev.pos, &[], None);
|
||||
let reach = cx.tol(REACH_PX);
|
||||
let to_second = ev.pos.distance(b).min(ev.pos.distance(clicked));
|
||||
let (mut on_first, mut on_second) = (at == a || ev.pos.distance(a) <= reach, at == b || to_second <= reach);
|
||||
// A press in reach of both points is on the one it snapped to, otherwise on the
|
||||
// nearer one.
|
||||
if on_first && on_second {
|
||||
let first = if (at == a) != (at == b) { at == a } else { ev.pos.distance(a) < to_second };
|
||||
(on_first, on_second) = (first, !first);
|
||||
}
|
||||
self.press = Some(Press::Third { at, from: ev.pos, on_first, on_second, dragged: false });
|
||||
self.pointer = Some(at);
|
||||
return vec![];
|
||||
}
|
||||
match self.first {
|
||||
None => {
|
||||
let at = self.snap.press(cx, ev.pos, &[], None);
|
||||
@@ -207,7 +367,28 @@ impl Tool for CircleTool {
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Drag => {
|
||||
let drag_third = self.options.drag_third;
|
||||
let first = self.first;
|
||||
match &mut self.press {
|
||||
// With `dragThird` off, the second point follows the pointer as it does before
|
||||
// the press.
|
||||
// The point stays where it was pressed until the press is a drag.
|
||||
Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => {
|
||||
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
|
||||
if *dragged {
|
||||
let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift));
|
||||
*snapped = self.snap.drag(cx, ev.pos, leave.as_ref());
|
||||
*at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods));
|
||||
self.pointer = Some(*at);
|
||||
}
|
||||
}
|
||||
Some(Press::Third { at, from, dragged, .. }) => {
|
||||
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
|
||||
if *dragged {
|
||||
*at = self.snap.drag(cx, ev.pos, None);
|
||||
self.pointer = Some(*at);
|
||||
}
|
||||
}
|
||||
Some(Press::First { at, from, dragged }) => {
|
||||
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
|
||||
let leave = Leave::segment(cx, *at, ev.mods.shift);
|
||||
@@ -230,6 +411,16 @@ impl Tool for CircleTool {
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Up => match (self.press.take(), self.first, self.pointer) {
|
||||
(Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged),
|
||||
// With `dragThird` off, the release places the second point; let go on the first
|
||||
// point, as a press there is, it places nothing.
|
||||
(Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => {
|
||||
if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) {
|
||||
self.second = Some((at, ev.pos));
|
||||
}
|
||||
self.snap.clear();
|
||||
vec![]
|
||||
}
|
||||
(Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]),
|
||||
// A click places the first point; the guides of the press go.
|
||||
(Some(Press::First { .. }), ..) => {
|
||||
@@ -296,22 +487,33 @@ impl Tool for CircleTool {
|
||||
let mut o = self.snap.guides().to_vec();
|
||||
let points = self.points();
|
||||
let color = crate::draw2::FEEDBACK;
|
||||
if let Some((c, r)) = circle_of(&points) {
|
||||
let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath();
|
||||
if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) {
|
||||
// The path the release draws: with `standardAnchors` off, the one with an anchor at each point.
|
||||
let path = if self.options.standard_anchors {
|
||||
shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath()
|
||||
} else {
|
||||
shapes::circle_with_anchors_at(c, r, &points).to_bezpath()
|
||||
};
|
||||
// The canvas draws a dashed outline dash by dash along its whole length: a circle longer
|
||||
// than DASHED_PX on screen is drawn solid instead.
|
||||
let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX);
|
||||
o.push(Overlay::Path { path, color, width: 1.0, dashed });
|
||||
for p in &points {
|
||||
o.push(Overlay::Line { a: c, b: *p, color, dashed: false });
|
||||
let opts = self.options;
|
||||
let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb);
|
||||
if opts.radii {
|
||||
for p in &points {
|
||||
o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false });
|
||||
}
|
||||
}
|
||||
let arm = cx.tol(CROSS_PX);
|
||||
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false });
|
||||
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false });
|
||||
if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) {
|
||||
if opts.center {
|
||||
let arm = cx.tol(CROSS_PX);
|
||||
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: lines, dashed: false });
|
||||
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: lines, dashed: false });
|
||||
}
|
||||
if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) {
|
||||
o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) });
|
||||
}
|
||||
} else if let Some(p) = self.pointer.filter(|_| too_large(&points)) {
|
||||
} else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) {
|
||||
o.push(Overlay::Label { p, text: "Circle too large".into(), color });
|
||||
}
|
||||
for p in self.first.into_iter().chain(self.second()) {
|
||||
@@ -323,6 +525,43 @@ impl Tool for CircleTool {
|
||||
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
|
||||
Cursor::Crosshair
|
||||
}
|
||||
|
||||
fn options(&self) -> Value {
|
||||
let o = self.options;
|
||||
let color = COLORS.get(o.color).map_or("blue", |(name, _)| *name);
|
||||
json!({
|
||||
"center": o.center,
|
||||
"radii": o.radii,
|
||||
"diameter": o.diameter,
|
||||
"color": color,
|
||||
"standardAnchors": o.standard_anchors,
|
||||
"dragThird": o.drag_third,
|
||||
})
|
||||
}
|
||||
|
||||
/// Takes the values [`check_options`] takes.
|
||||
fn check_option(&self, key: &str, value: &Value) -> Result<(), String> {
|
||||
check_options(&Map::from_iter([(key.to_string(), value.clone())]))
|
||||
}
|
||||
|
||||
/// Sets one option; a value the option does not take leaves it as it was. Switching
|
||||
/// `dragThird` drops the points placed so far.
|
||||
fn set_option(&mut self, key: &str, value: &Value) {
|
||||
if key == "color" {
|
||||
if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) {
|
||||
self.options.color = i;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(on) = value.as_bool() else { return };
|
||||
let was = self.options.drag_third;
|
||||
if let Some(switch) = self.options.switch(key) {
|
||||
*switch = on;
|
||||
}
|
||||
if self.options.drag_third != was {
|
||||
self.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -94,6 +94,302 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() {
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)]));
|
||||
}
|
||||
|
||||
/// The lines the tool shows from the center `c`: (radius lines, arms of the center cross), each
|
||||
/// with its color.
|
||||
fn annotations(o: &[Overlay], c: Point) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) {
|
||||
let (mut radii, mut cross) = (vec![], vec![]);
|
||||
for o in o {
|
||||
if let Overlay::Line { a, b, color, .. } = o {
|
||||
if *a == c {
|
||||
radii.push(*color);
|
||||
} else if a.midpoint(*b).distance(c) < 1e-9 {
|
||||
cross.push(*color);
|
||||
}
|
||||
}
|
||||
}
|
||||
(radii, cross)
|
||||
}
|
||||
|
||||
/// `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the
|
||||
/// diameter label, each on its own, and `color` is the color of the cross and the lines; the
|
||||
/// outline stays in the feedback color. Each option lasts in [`Tool::options`].
|
||||
#[test]
|
||||
fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let mut t = CircleTool::default();
|
||||
click(&mut t, &cx, (300.0, 300.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default()));
|
||||
let c = Point::new(340.0, 330.0);
|
||||
let blue = crate::draw2::FEEDBACK;
|
||||
assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![blue; 2]));
|
||||
let diameter = |t: &CircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { .. }));
|
||||
assert!(diameter(&t));
|
||||
t.set_option("center", &json!(false));
|
||||
assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![]));
|
||||
t.set_option("radii", &json!(false));
|
||||
assert_eq!(annotations(&t.overlays(&cx), c), (vec![], vec![]));
|
||||
assert!(diameter(&t));
|
||||
t.set_option("diameter", &json!(false));
|
||||
assert!(!diameter(&t));
|
||||
t.set_option("center", &json!(true));
|
||||
t.set_option("radii", &json!(true));
|
||||
t.set_option("color", &json!("red"));
|
||||
let red = [0xe5, 0x2d, 0x27];
|
||||
let o = t.overlays(&cx);
|
||||
assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2]));
|
||||
assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}");
|
||||
assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true}));
|
||||
// A value an option does not take leaves it as it was.
|
||||
for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] {
|
||||
t.set_option(key, &value);
|
||||
}
|
||||
assert_eq!(t.options()["color"], json!("red"));
|
||||
assert_eq!((&t.options()["center"], &t.options()["radii"]), (&json!(true), &json!(true)));
|
||||
}
|
||||
|
||||
/// With `standardAnchors` off, the circle's anchors go at the points it was drawn through.
|
||||
#[test]
|
||||
fn anchors_at_the_points_asks_for_them() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("standardAnchors", &json!(false));
|
||||
let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default());
|
||||
let points = json!([[300.0, 300.0], [380.0, 360.0]]);
|
||||
assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]);
|
||||
}
|
||||
|
||||
/// With `standardAnchors` off, the tool shows the path with an anchor at each point, the one its
|
||||
/// release draws.
|
||||
#[test]
|
||||
fn anchors_at_the_points_show_the_path_they_draw() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("standardAnchors", &json!(false));
|
||||
click(&mut t, &cx, (300.0, 300.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default()));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, (310.0, 340.0), Mods::default()));
|
||||
let points = [Point::new(300.0, 300.0), Point::new(380.0, 300.0), Point::new(310.0, 340.0)];
|
||||
let (c, r) = circle_of(&points).expect("a circle");
|
||||
let want = shapes::circle_with_anchors_at(c, r, &points).to_bezpath();
|
||||
let o = t.overlays(&cx);
|
||||
assert!(o.iter().any(|o| matches!(o, Overlay::Path { path, .. } if *path == want)), "{o:?}");
|
||||
}
|
||||
|
||||
/// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at
|
||||
/// the points curves past that edge is not shown and not drawn; with standard anchors it is.
|
||||
#[test]
|
||||
fn anchors_at_the_points_keep_the_path_on_the_canvas() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let r = MAX_COORD - 1.0;
|
||||
let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin());
|
||||
let points = [at(0.0), at(70.0), at(180.0)];
|
||||
let geom: Vec<Point> = points.iter().map(|(x, y)| Point::new(*x, *y)).collect();
|
||||
assert!(drawn_circle(&geom, true).is_some());
|
||||
assert_eq!(drawn_circle(&geom, false), None);
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("standardAnchors", &json!(false));
|
||||
click(&mut t, &cx, points[0]);
|
||||
t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default()));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default()));
|
||||
// No outline at all: at this size the tool would draw it solid, not dashed.
|
||||
let o = t.overlays(&cx);
|
||||
assert!(!o.iter().any(|o| matches!(o, Overlay::Path { .. })), "{o:?}");
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]);
|
||||
}
|
||||
|
||||
/// With `dragThird` off, a click in reach of both placed points is on the nearer one: nearer the
|
||||
/// first point it places nothing, nearer the second it draws the circle on the two.
|
||||
#[test]
|
||||
fn with_third_point_by_dragging_off_a_click_near_both_points_takes_the_nearer() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("dragThird", &json!(false));
|
||||
click(&mut t, &cx, (100.0, 100.0));
|
||||
assert_eq!(click(&mut t, &cx, (104.0, 100.0)), vec![]);
|
||||
assert_eq!(click(&mut t, &cx, (101.0, 100.0)), vec![]);
|
||||
assert_eq!(click(&mut t, &cx, (103.0, 100.0)), circle(&[(100.0, 100.0), (104.0, 100.0)]));
|
||||
}
|
||||
|
||||
/// With `dragThird` off, a press on the second point shows the circle on the two points, which its
|
||||
/// release draws, and a press on the first point shows none.
|
||||
#[test]
|
||||
fn with_third_point_by_dragging_off_a_press_shows_the_circle_its_release_draws() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("dragThird", &json!(false));
|
||||
click(&mut t, &cx, (100.0, 100.0));
|
||||
click(&mut t, &cx, (200.0, 100.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.0), Mods::default()));
|
||||
assert_eq!(preview(&t.overlays(&cx)), None);
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.0), Mods::default())), vec![]);
|
||||
t.pointer(&cx, &ev(PointerKind::Down, (202.0, 101.0), Mods::default()));
|
||||
let o = t.overlays(&cx);
|
||||
assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 50.0, 200.0, 150.0)), "{o:?}");
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (202.0, 101.0), Mods::default())), circle(&[(100.0, 100.0), (200.0, 100.0)]));
|
||||
}
|
||||
|
||||
/// With `dragThird` off, a press that moves less than 2 screen points keeps the point where it was
|
||||
/// pressed, for the second point and for the third.
|
||||
#[test]
|
||||
fn with_third_point_by_dragging_off_a_short_move_keeps_the_pressed_point() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up);
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("dragThird", &json!(false));
|
||||
click(&mut t, &cx, (100.0, 100.0));
|
||||
t.pointer(&cx, &ev(down, (200.0, 100.0), Mods::default()));
|
||||
t.pointer(&cx, &ev(drag, (201.0, 100.0), Mods::default()));
|
||||
assert_eq!(t.pointer(&cx, &ev(up, (200.0, 100.0), Mods::default())), vec![]);
|
||||
t.pointer(&cx, &ev(down, (150.0, 200.0), Mods::default()));
|
||||
t.pointer(&cx, &ev(drag, (151.0, 200.0), Mods::default()));
|
||||
let three = circle(&[(100.0, 100.0), (200.0, 100.0), (150.0, 200.0)]);
|
||||
assert_eq!(t.pointer(&cx, &ev(up, (150.0, 200.0), Mods::default())), three);
|
||||
}
|
||||
|
||||
/// With `dragThird` off, a second click places the second point and a third click draws the circle
|
||||
/// through the three; a click on the second point again (as a double-click there does) draws the
|
||||
/// circle on the two; a second point let go on the first places nothing; a drag from the first
|
||||
/// point still draws the circle on its diameter.
|
||||
#[test]
|
||||
fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("dragThird", &json!(false));
|
||||
click(&mut t, &cx, (300.0, 300.0));
|
||||
assert_eq!(click(&mut t, &cx, (380.0, 300.0)), vec![]);
|
||||
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 360.0), Mods::default()));
|
||||
let o = t.overlays(&cx);
|
||||
assert!(near(preview(&o).expect("the circle through the three is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}");
|
||||
assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}");
|
||||
// A click on the first point places nothing and keeps both points.
|
||||
assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]);
|
||||
assert!(t.busy());
|
||||
assert_eq!(click(&mut t, &cx, (300.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)]));
|
||||
assert!(!t.busy());
|
||||
// The events of a double-click on the second point: its first click places it, the second
|
||||
// draws the circle on the two points, and the double-click event that follows adds nothing.
|
||||
click(&mut t, &cx, (100.0, 100.0));
|
||||
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]);
|
||||
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), circle(&[(100.0, 100.0), (200.0, 100.0)]));
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, (200.0, 100.0), Mods::default())), vec![]);
|
||||
assert!(!t.busy());
|
||||
// A drag that moves the second point places it where it is let go.
|
||||
click(&mut t, &cx, (100.0, 100.0));
|
||||
assert_eq!(drag(&mut t, &cx, (150.0, 100.0), &[(180.0, 100.0), (200.0, 100.0)], Mods::default()), vec![]);
|
||||
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
|
||||
// Three points on one line keep the two placed: the next click elsewhere draws.
|
||||
click(&mut t, &cx, (100.0, 100.0));
|
||||
click(&mut t, &cx, (200.0, 100.0));
|
||||
assert_eq!(click(&mut t, &cx, (300.0, 100.0)), vec![]);
|
||||
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
|
||||
// A second press elsewhere, dragged back and let go on the first point, places nothing: the
|
||||
// next click places the second point.
|
||||
click(&mut t, &cx, (100.0, 100.0));
|
||||
assert_eq!(drag(&mut t, &cx, (200.0, 100.0), &[(150.0, 100.0), (100.0, 100.0)], Mods::default()), vec![]);
|
||||
assert!(t.busy());
|
||||
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]);
|
||||
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
|
||||
// A drag from the first point.
|
||||
assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)]));
|
||||
// Switching the option drops the points placed so far.
|
||||
click(&mut t, &cx, (100.0, 100.0));
|
||||
t.set_option("dragThird", &json!(true));
|
||||
assert!(!t.busy());
|
||||
}
|
||||
|
||||
/// With `dragThird` off, a drag of the second or third point ends where it is let go, also when the
|
||||
/// release is away from the last drag.
|
||||
#[test]
|
||||
fn with_third_point_by_dragging_off_a_drag_ends_where_it_is_let_go() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up);
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("dragThird", &json!(false));
|
||||
click(&mut t, &cx, (300.0, 300.0));
|
||||
t.pointer(&cx, &ev(down, (350.0, 300.0), Mods::default()));
|
||||
t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default()));
|
||||
assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), vec![]);
|
||||
t.pointer(&cx, &ev(down, (350.0, 350.0), Mods::default()));
|
||||
t.pointer(&cx, &ev(drag, (320.0, 380.0), Mods::default()));
|
||||
assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0), (300.0, 400.0)]));
|
||||
}
|
||||
|
||||
/// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter
|
||||
/// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview,
|
||||
/// the circle on the two points and the circle through three all use it.
|
||||
#[test]
|
||||
fn an_alt_click_places_the_second_point_where_it_is_shown() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let mut t = CircleTool::default();
|
||||
t.set_option("dragThird", &json!(false));
|
||||
click(&mut t, &cx, (300.0, 300.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt));
|
||||
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 390.0), Mods::default()));
|
||||
let o = t.overlays(&cx);
|
||||
let second = Point::new(390.0, 300.0);
|
||||
assert!(o.iter().any(|o| matches!(o, Overlay::Anchor { p, .. } if p.distance(second) < 1e-9)), "{o:?}");
|
||||
// (300, 300), (390, 300) and (300, 390): center (345, 345), radius 45·√2.
|
||||
let r = 45.0 * 2f64.sqrt();
|
||||
assert!(near(preview(&o).unwrap(), Rect::new(345.0 - r, 345.0 - r, 345.0 + r, 345.0 + r)), "{o:?}");
|
||||
assert_eq!(click(&mut t, &cx, (300.0, 390.0)), circle(&[(300.0, 300.0), (390.0, 300.0), (300.0, 390.0)]));
|
||||
click(&mut t, &cx, (300.0, 300.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt));
|
||||
assert_eq!(click(&mut t, &cx, (390.0, 300.0)), circle(&[(300.0, 300.0), (390.0, 300.0)]));
|
||||
// In inches the ticks are farther apart, and the rounding can move the point more than the
|
||||
// 3 screen points a click reaches: the second click of a double-click, where the first let go,
|
||||
// still draws the circle on the two points, at the rounded point.
|
||||
let inches = ToolContext { unit: vectorcraft_doc::Unit::Inches, ..cx };
|
||||
let d = 94.4;
|
||||
let rounded = vectorcraft_doc::Unit::Inches.snap_to_ruler_tick(d, 1.0);
|
||||
assert!((rounded - d).abs() > 3.0, "{rounded}");
|
||||
click(&mut t, &inches, (300.0, 300.0));
|
||||
t.pointer(&inches, &ev(PointerKind::Down, (300.0 + d, 300.0), alt));
|
||||
t.pointer(&inches, &ev(PointerKind::Up, (300.0 + d, 300.0), alt));
|
||||
assert_eq!(click(&mut t, &inches, (300.0 + d, 300.0)), circle(&[(300.0, 300.0), (300.0 + rounded, 300.0)]));
|
||||
}
|
||||
|
||||
/// `tool.setOption`'s check takes the values the options take and nothing else.
|
||||
#[test]
|
||||
fn check_options_takes_only_the_values_the_options_take() {
|
||||
let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false});
|
||||
assert_eq!(check_options(ok.as_object().unwrap()), Ok(()));
|
||||
// The tool's own check, which `tool.setOption` also runs, takes the same values.
|
||||
let tool = CircleTool::default();
|
||||
assert_eq!(tool.check_options(ok.as_object().unwrap()), Ok(()));
|
||||
for (bad, error) in [
|
||||
(json!({"center": 1}), "`center` must be true or false"),
|
||||
(json!({"dragThird": null}), "`dragThird` must be true or false"),
|
||||
(json!({"color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"),
|
||||
(json!({"colour": "red"}), "unknown Circle tool option `colour`"),
|
||||
] {
|
||||
assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}");
|
||||
assert_eq!(tool.check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A drag ends where it is let go, also when the release is away from the last drag: from a first
|
||||
/// press, from a second press, and from a press on the first point. A release within 2 screen
|
||||
/// points of a second press is still a click and keeps the point of the press.
|
||||
@@ -288,8 +584,8 @@ fn points_on_one_line_say_the_circle_is_too_large() {
|
||||
assert_eq!(label(&t), None, "a circle is shown");
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default()));
|
||||
assert_eq!(label(&t), None, "the third point is on the second");
|
||||
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)]));
|
||||
assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)]));
|
||||
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true));
|
||||
assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true));
|
||||
}
|
||||
|
||||
/// Escape drops the first point; so do a dropped press and an edit made outside the tool. A
|
||||
|
||||
@@ -1657,7 +1657,7 @@ impl DirectSelectionTool {
|
||||
// The grabbed anchor snaps and the others follow it. Shift keeps the move at its
|
||||
// angle, and the anchor slides along it onto what Smart Guides find there (#886).
|
||||
self.guides.clear();
|
||||
if segment && let Some(grid) = &self.partial_grid {
|
||||
if segment && let Some(grid) = &mut self.partial_grid {
|
||||
(d, self.guides) = if ev.mods.shift { grid.snap_along(cx, grab, d, false) } else { grid.snap(cx, grab, d, false) };
|
||||
} else if let Some(snap) = &self.anchor_snap {
|
||||
let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true));
|
||||
@@ -1710,7 +1710,7 @@ impl DirectSelectionTool {
|
||||
&& let Some(snap) = &self.partial_snap
|
||||
{
|
||||
let held = grab.unwrap_or(hold);
|
||||
if let Some(grid) = &self.partial_grid {
|
||||
if let Some(grid) = &mut self.partial_grid {
|
||||
(d, self.guides) = if ev.mods.shift { grid.snap_along(cx, held, d, false) } else { grid.snap(cx, held, d, false) };
|
||||
} else {
|
||||
let shift = ev.mods.shift.then(|| Leave::segment(cx, held, true));
|
||||
@@ -1730,7 +1730,7 @@ impl DirectSelectionTool {
|
||||
let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true));
|
||||
let (q, guides) = snap.snap_from(cx, grab + (p - start), shift.as_ref());
|
||||
(d, self.guides) = (q - grab, guides);
|
||||
} else if let Some(snap) = &self.move_snap {
|
||||
} else if let Some(snap) = &mut self.move_snap {
|
||||
(d, self.guides) = if ev.mods.shift { snap.snap_along(cx, hold, d, ev.mods.alt) } else { snap.snap(cx, hold, d, ev.mods.alt) };
|
||||
}
|
||||
self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides);
|
||||
|
||||
@@ -707,6 +707,12 @@ impl Targets {
|
||||
self
|
||||
}
|
||||
|
||||
/// These targets without the ruler guides, once they stop showing during the drag they were
|
||||
/// gathered for (#8363).
|
||||
pub(crate) fn forget_rulers(&mut self) {
|
||||
self.rulers.clear();
|
||||
}
|
||||
|
||||
/// The ruler guides alone ([`Self::with_rulers`]): what a dragged selection's grabbed point
|
||||
/// still snaps to with View → Snap to Point when Smart Guides line the selection up.
|
||||
pub(crate) fn rulers(cx: &ToolContext) -> Self {
|
||||
|
||||
@@ -226,6 +226,12 @@ pub trait Tool: Send {
|
||||
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
|
||||
false
|
||||
}
|
||||
/// The point a path the tool is drawing goes on from, and the direction the path arrives there
|
||||
/// in (none for a path of one point), while the tool draws one: the Quick Pen toolbar sits
|
||||
/// beside it.
|
||||
fn drawing_end(&self, _cx: &ToolContext) -> Option<(Point, Option<Vec2>)> {
|
||||
None
|
||||
}
|
||||
/// Does the tool want typed text (Type tool editing)? Single-key shortcuts are suppressed.
|
||||
fn wants_text(&self) -> bool {
|
||||
false
|
||||
|
||||
+180
-57
@@ -7,15 +7,17 @@
|
||||
//! sharp-corner arc (it turns through the arc size, 180° by default, and meets the path before it
|
||||
//! at a corner). Alt (Option) pressed and let go on its own switches to the next action. C flips
|
||||
//! the last sharp-corner arc to the other side of its chord, and [ and ] make the arc size 15°
|
||||
//! smaller or larger, for the last sharp-corner arc and the ones after it. A click on the first
|
||||
//! smaller or larger, for the last sharp-corner arc and the ones after it; during a drag they
|
||||
//! change the arc being dragged. A dragged piece ends where the press is let go. A click on the first
|
||||
//! point closes the path, a click on an end of an open path goes on drawing from it, and Escape
|
||||
//! or Enter ends the path. The path's points show as circles, without handles, and a preview
|
||||
//! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step.
|
||||
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2};
|
||||
|
||||
use crate::draw2::FEEDBACK;
|
||||
@@ -39,6 +41,11 @@ const DRAG_PX: f64 = 3.0;
|
||||
/// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight
|
||||
/// behind, is drawn as a line: no circle runs there in the path's direction.
|
||||
const STRAIGHT: f64 = 1e-6;
|
||||
/// The notice the tool asks for after each of its own edits, to see the path as the document then
|
||||
/// has it.
|
||||
const DRAWN: &str = "drawn";
|
||||
/// The notice after a press's piece is committed.
|
||||
const PLACED: &str = "placed";
|
||||
|
||||
/// What the next click adds.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -214,21 +221,50 @@ pub fn build(base: &SubPath, pieces: &[Piece], closed: bool) -> SubPath {
|
||||
sp
|
||||
}
|
||||
|
||||
/// The path being drawn: subpath `si` of `id`, whose points were `base` before the tool drew on
|
||||
/// (both none until the engine made a new path), then `pieces`. A new path starts at `start`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
/// The path being drawn: subpath `si` of `id` (none until the engine made a new path, which starts
|
||||
/// at `start`), and the `pieces` the tool added to it, each after the number of points in `kept`
|
||||
/// the subpath had before it. `seen` is the path object as the document had it after the tool's
|
||||
/// last edit, pixel alignment and other changes the engine makes after each edit included, and
|
||||
/// `before_press` as it was when the press under way began. A piece is drawn again on the points
|
||||
/// the document holds before it, so the points before it stay as they are.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct Drawing {
|
||||
id: Option<NodeId>,
|
||||
si: usize,
|
||||
base: Option<SubPath>,
|
||||
start: Option<Point>,
|
||||
pieces: Vec<Piece>,
|
||||
kept: Vec<usize>,
|
||||
seen: Option<Arc<Node>>,
|
||||
before_press: Option<Arc<Node>>,
|
||||
/// The document's revision ([`ToolContext::revision`]) after the tool's last edit.
|
||||
revision: (u64, u64),
|
||||
}
|
||||
|
||||
/// The node `id` as the document shares it, found through the document's index.
|
||||
fn shared_node(doc: &Document, id: NodeId) -> Option<&Arc<Node>> {
|
||||
let path = doc.index_path(id)?;
|
||||
let (first, rest) = path.split_first()?;
|
||||
let mut cur = doc.layers.get(*first)?;
|
||||
for &i in rest {
|
||||
cur = cur.children()?.get(i)?;
|
||||
}
|
||||
Some(cur)
|
||||
}
|
||||
|
||||
/// Is `now` the node `then` was: the same shared node, or one equal to it?
|
||||
fn same_node(now: &Node, then: &Arc<Node>) -> bool {
|
||||
std::ptr::eq(now, Arc::as_ptr(then)) || *now == **then
|
||||
}
|
||||
|
||||
impl Drawing {
|
||||
/// The subpath as the tool drew it.
|
||||
fn drawn(&self) -> Option<SubPath> {
|
||||
Some(build(self.base.as_ref()?, &self.pieces, false))
|
||||
fn push(&mut self, piece: Piece, kept: usize) {
|
||||
self.pieces.push(piece);
|
||||
self.kept.push(kept);
|
||||
}
|
||||
|
||||
fn pop(&mut self) {
|
||||
self.pieces.pop();
|
||||
self.kept.pop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,30 +302,41 @@ fn point_tol(cx: &ToolContext) -> f64 {
|
||||
cx.tol(5.0).max(cx.point_tol())
|
||||
}
|
||||
|
||||
/// Asks to see the path once the actions before it are applied.
|
||||
fn drawn() -> Action {
|
||||
Action::Notify(DRAWN.into())
|
||||
}
|
||||
|
||||
impl QuickPenTool {
|
||||
/// The subpath being drawn, while it is selected, editable, open and still exactly what the tool
|
||||
/// drew: an edit made outside the tool (a point moved, the path it went on from changed) ends
|
||||
/// the drawing, so the next piece does not undo it.
|
||||
/// The subpath being drawn, while it is selected, editable, open and its path still exactly as
|
||||
/// the tool's last edit left it: an edit made to the path outside the tool (a point moved, its
|
||||
/// look changed, the path it went on from changed), also during a press, ends the drawing, so
|
||||
/// the next piece does not undo it.
|
||||
fn active<'a>(&self, cx: &'a ToolContext) -> Option<(NodeId, &'a SubPath)> {
|
||||
let dr = self.drawing.as_ref()?;
|
||||
let id = dr.id?;
|
||||
if !selected_alone(cx, id) || !cx.doc.is_editable(id) {
|
||||
return None;
|
||||
}
|
||||
let sp = cx.doc.node(id)?.path_data()?.subpaths.get(dr.si)?;
|
||||
(!sp.closed && dr.drawn()?.anchors == sp.anchors).then_some((id, sp))
|
||||
let node = cx.doc.node(id)?;
|
||||
if !same_node(node, dr.seen.as_ref()?) {
|
||||
return None;
|
||||
}
|
||||
let sp = node.path_data()?.subpaths.get(dr.si)?;
|
||||
(!sp.closed).then_some((id, sp))
|
||||
}
|
||||
|
||||
/// `path.quickPen`'s params for the path being drawn, closed when `closed`.
|
||||
/// `path.quickPen`'s params for the path being drawn: its last piece on the points before it,
|
||||
/// closed when `closed`.
|
||||
fn params(&self, closed: bool) -> Value {
|
||||
let Some(dr) = &self.drawing else { return json!({}) };
|
||||
let pieces: Vec<Value> = dr.pieces.iter().map(Piece::to_json).collect();
|
||||
let pieces: Vec<Value> = dr.pieces.last().map(Piece::to_json).into_iter().collect();
|
||||
let mut v = json!({"pieces": pieces});
|
||||
match (dr.id, dr.start) {
|
||||
(Some(id), _) => {
|
||||
v["id"] = json!(id.0);
|
||||
v["subpath"] = json!(dr.si);
|
||||
v["keep"] = json!(dr.base.as_ref().map_or(1, |b| b.anchors.len().max(1)));
|
||||
v["keep"] = json!(dr.kept.last().copied().unwrap_or(1).max(1));
|
||||
}
|
||||
(None, Some(s)) => v["start"] = json!([s.x, s.y]),
|
||||
(None, None) => {}
|
||||
@@ -300,15 +347,57 @@ impl QuickPenTool {
|
||||
v
|
||||
}
|
||||
|
||||
/// The last piece, while it is a sharp-corner arc and no press is under way.
|
||||
/// The last piece, while it is a sharp-corner arc: the one drawn last while no press is under
|
||||
/// way, or the one a press is drawing.
|
||||
fn last_sharp_arc(&self, cx: &ToolContext) -> Option<Piece> {
|
||||
if self.press.is_some() {
|
||||
return None;
|
||||
match self.press {
|
||||
Some(pr) if !pr.begun => return None,
|
||||
Some(_) => self.held(cx).then_some(())?,
|
||||
None => self.active(cx).map(|_| ())?,
|
||||
}
|
||||
self.active(cx)?;
|
||||
self.drawing.as_ref()?.pieces.last().copied().filter(|p| p.stroke == Stroke::SharpArc)
|
||||
}
|
||||
|
||||
/// During a press: is the path being drawn still active, and the document as the tool's last
|
||||
/// preview left it? A preview starts again from the document as the press found it, so after
|
||||
/// an edit made outside the tool the press previews no more.
|
||||
fn held(&self, cx: &ToolContext) -> bool {
|
||||
self.active(cx).is_some() && self.drawing.as_ref().is_some_and(|dr| dr.revision == cx.revision)
|
||||
}
|
||||
|
||||
/// Moves the end of the piece a press draws to `p` (snapped) and previews it. An edit made
|
||||
/// outside the tool since the last preview ends the drawing instead: the press then commits
|
||||
/// the document as it is.
|
||||
fn drag_to(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
|
||||
if !self.held(cx) {
|
||||
self.drawing = None;
|
||||
self.snap.clear();
|
||||
return vec![];
|
||||
}
|
||||
// The snapping leaves from the point before the piece being dragged, as the press found it.
|
||||
let from = self.drawing.as_ref().and_then(|dr| {
|
||||
let sp = dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?;
|
||||
sp.anchors.get(dr.kept.last()?.checked_sub(1)?).map(|a| Leave::segment(cx, a.p, false).without_contact())
|
||||
});
|
||||
let q = self.snap.drag(cx, p, from.as_ref());
|
||||
let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] };
|
||||
if last.to == q {
|
||||
return vec![];
|
||||
}
|
||||
last.to = q;
|
||||
vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]
|
||||
}
|
||||
|
||||
/// Draws the path again after its last piece changed: a preview while a press draws that
|
||||
/// piece, else a step of its own.
|
||||
fn redraw(&self) -> Vec<Action> {
|
||||
if self.press.is_some_and(|pr| pr.begun) {
|
||||
vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]
|
||||
} else {
|
||||
vec![Action::Exec(COMMAND.into(), self.params(false)), drawn()]
|
||||
}
|
||||
}
|
||||
|
||||
fn piece_to(&self, to: Point) -> Piece {
|
||||
Piece { to, stroke: self.action, turn: self.turn, flip: false }
|
||||
}
|
||||
@@ -332,9 +421,9 @@ impl QuickPenTool {
|
||||
_ => return vec![],
|
||||
};
|
||||
if sp.anchors.len() >= 2 && p.distance(first) <= tol && p.distance(first) <= p.distance(last) {
|
||||
let piece = self.piece_to(first);
|
||||
let (piece, kept) = (self.piece_to(first), sp.anchors.len());
|
||||
if let Some(dr) = self.drawing.as_mut() {
|
||||
dr.pieces.push(piece);
|
||||
dr.push(piece, kept);
|
||||
}
|
||||
let out = vec![Action::Exec(COMMAND.into(), self.params(true))];
|
||||
self.drawing = None;
|
||||
@@ -345,27 +434,25 @@ impl QuickPenTool {
|
||||
}
|
||||
let from = self.leave(cx).map(|l| l.1);
|
||||
let q = self.snap.press(cx, p, &[id], from.as_ref());
|
||||
let piece = self.piece_to(q);
|
||||
let (piece, kept) = (self.piece_to(q), sp.anchors.len());
|
||||
if let Some(dr) = self.drawing.as_mut() {
|
||||
dr.pieces.push(piece);
|
||||
dr.push(piece, kept);
|
||||
dr.before_press = shared_node(cx.doc, id).cloned();
|
||||
}
|
||||
self.press = Some(Press { at: p, dragged: false, begun: true });
|
||||
return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false))];
|
||||
return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()];
|
||||
}
|
||||
if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None)
|
||||
&& cx.doc.is_editable(id)
|
||||
&& let Some(sp) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si))
|
||||
{
|
||||
// From its start, `continue_from` reverses the path first.
|
||||
let mut base = sp.clone();
|
||||
if at_first {
|
||||
base.reverse();
|
||||
}
|
||||
self.drawing = Some(Drawing { id: Some(id), si, base: Some(base), start: None, pieces: vec![] });
|
||||
return continue_from(cx, id, si, at_first);
|
||||
// From its start, `continue_from` reverses the path first; the tool then sees it.
|
||||
self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() });
|
||||
let mut out = continue_from(cx, id, si, at_first);
|
||||
out.push(drawn());
|
||||
return out;
|
||||
}
|
||||
let q = self.snap.press(cx, p, &[], None);
|
||||
self.drawing = Some(Drawing { id: None, si: 0, base: None, start: Some(q), pieces: vec![] });
|
||||
self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() });
|
||||
vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())]
|
||||
}
|
||||
|
||||
@@ -427,36 +514,61 @@ impl Tool for QuickPenTool {
|
||||
}
|
||||
pr.dragged = true;
|
||||
self.press = Some(pr);
|
||||
// The snapping leaves from the point before the piece being dragged.
|
||||
let from = self.drawing.as_ref().and_then(|dr| {
|
||||
let sp = build(dr.base.as_ref()?, dr.pieces.split_last().map_or(&[][..], |(_, rest)| rest), false);
|
||||
sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact())
|
||||
});
|
||||
let q = self.snap.drag(cx, p, from.as_ref());
|
||||
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
|
||||
last.to = q;
|
||||
if !pr.begun {
|
||||
return vec![];
|
||||
}
|
||||
vec![Action::Preview(COMMAND.into(), self.params(false))]
|
||||
self.drag_to(cx, p)
|
||||
}
|
||||
PointerKind::Up => {
|
||||
self.snap.clear();
|
||||
match self.press.take() {
|
||||
Some(pr) if pr.begun => vec![Action::Commit],
|
||||
let out = match self.press {
|
||||
// The piece ends where the press is let go, also past the last drag.
|
||||
Some(pr) if pr.begun => {
|
||||
let mut out = vec![];
|
||||
if pr.dragged || p.distance(pr.at) >= cx.tol(DRAG_PX) {
|
||||
out = self.drag_to(cx, p);
|
||||
} else if self.active(cx).is_none() {
|
||||
// An edit made outside the tool during the press ends the path.
|
||||
self.drawing = None;
|
||||
}
|
||||
// With Real-time Drawing off, the commit applies the piece.
|
||||
out.extend([Action::Commit, Action::Notify(PLACED.into())]);
|
||||
out
|
||||
}
|
||||
_ => vec![],
|
||||
};
|
||||
if let Some(dr) = self.drawing.as_mut() {
|
||||
dr.before_press = None;
|
||||
}
|
||||
self.press = None;
|
||||
self.snap.clear();
|
||||
out
|
||||
}
|
||||
PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn notify(&mut self, cx: &ToolContext, what: &str) {
|
||||
let Some(dr) = self.drawing.as_mut() else { return };
|
||||
if what == "created"
|
||||
&& let [id] = cx.selection.objects.as_slice()
|
||||
&& let Some(base) = cx.doc.node(*id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.first())
|
||||
&& let Some(dr) = self.drawing.as_mut()
|
||||
&& let Some(node) = shared_node(cx.doc, *id).filter(|n| n.path_data().is_some_and(|pd| !pd.subpaths.is_empty()))
|
||||
&& dr.id.is_none()
|
||||
{
|
||||
(dr.id, dr.si, dr.base, dr.start) = (Some(*id), 0, Some(base.clone()), None);
|
||||
(dr.id, dr.si, dr.start, dr.seen) = (Some(*id), 0, None, Some(node.clone()));
|
||||
} else if (what == DRAWN || what == PLACED)
|
||||
&& let Some(id) = dr.id
|
||||
{
|
||||
dr.seen = shared_node(cx.doc, id).cloned();
|
||||
dr.revision = cx.revision;
|
||||
// Once committed, a piece that added no point to the path (the command refused it) is
|
||||
// not kept for C and [ ] to change.
|
||||
let points = dr.seen.as_ref().and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(dr.si)).map(|sp| sp.anchors.len());
|
||||
if what == PLACED
|
||||
&& let (Some(points), Some(&kept)) = (points, dr.kept.last())
|
||||
&& points <= kept
|
||||
{
|
||||
dr.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,6 +577,11 @@ impl Tool for QuickPenTool {
|
||||
self.active(cx).is_some()
|
||||
}
|
||||
|
||||
fn drawing_end(&self, cx: &ToolContext) -> Option<(Point, Option<Vec2>)> {
|
||||
let (_, sp) = self.active(cx)?;
|
||||
Some((sp.anchors.last()?.p, arrival(sp)))
|
||||
}
|
||||
|
||||
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
|
||||
match key {
|
||||
ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(),
|
||||
@@ -475,13 +592,19 @@ impl Tool for QuickPenTool {
|
||||
}
|
||||
|
||||
/// A dropped press does not end the path being drawn: the piece it added goes.
|
||||
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
/// The drawing goes on only when the path is back as it was before the press.
|
||||
fn drop_press(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
self.snap.clear();
|
||||
if self.press.take().is_some_and(|pr| pr.begun)
|
||||
&& let Some(dr) = self.drawing.as_mut()
|
||||
{
|
||||
dr.pieces.pop();
|
||||
dr.pop();
|
||||
let now = dr.id.and_then(|id| cx.doc.node(id));
|
||||
match (now, dr.before_press.take()) {
|
||||
(Some(now), Some(before)) if same_node(now, &before) => dr.seen = Some(before),
|
||||
_ => self.drawing = None,
|
||||
}
|
||||
}
|
||||
self.snap.clear();
|
||||
vec![]
|
||||
}
|
||||
|
||||
@@ -495,7 +618,7 @@ impl Tool for QuickPenTool {
|
||||
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
|
||||
last.flip = !last.flip;
|
||||
}
|
||||
vec![Action::Exec(COMMAND.into(), self.params(false))]
|
||||
self.redraw()
|
||||
}
|
||||
ToolKey::BracketLeft | ToolKey::BracketRight => {
|
||||
let by = if key == ToolKey::BracketLeft { -TURN_STEP } else { TURN_STEP };
|
||||
@@ -511,17 +634,17 @@ impl Tool for QuickPenTool {
|
||||
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
|
||||
last.turn = turn;
|
||||
}
|
||||
vec![Action::Exec(COMMAND.into(), self.params(false))]
|
||||
self.redraw()
|
||||
}
|
||||
ToolKey::AltTap => {
|
||||
self.action = self.action.next();
|
||||
// A drag under way draws its piece with the new action.
|
||||
if self.press.is_some_and(|pr| pr.begun) {
|
||||
if self.press.is_some_and(|pr| pr.begun) && self.held(cx) {
|
||||
let (action, turn) = (self.action, self.turn);
|
||||
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
|
||||
(last.stroke, last.turn, last.flip) = (action, turn, false);
|
||||
}
|
||||
return vec![Action::Preview(COMMAND.into(), self.params(false))];
|
||||
return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()];
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
@@ -309,10 +309,24 @@ impl MoveSnap {
|
||||
Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false }
|
||||
}
|
||||
|
||||
/// The ruler guides stopped showing since the move began (View › Hide Guides, or Trim View,
|
||||
/// #8363): the move no longer snaps to them, for the rest of it, while its other targets stay.
|
||||
/// They were gathered when it began, and nothing pulls toward a guide the canvas does not draw.
|
||||
fn forget_hidden_rulers(&mut self, cx: &ToolContext) {
|
||||
if cx.guides {
|
||||
return;
|
||||
}
|
||||
self.rulers = None;
|
||||
for t in [&mut self.points, &mut self.copy_points].into_iter().flatten() {
|
||||
t.forget_rulers();
|
||||
}
|
||||
}
|
||||
|
||||
/// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its
|
||||
/// guides. With Smart Guides › Snap to Last Location, a move within Snapping Tolerance of where
|
||||
/// it began goes back there before anything else snaps ([`Targets::snap_back`]).
|
||||
pub(crate) fn snap(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
|
||||
pub(crate) fn snap(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
|
||||
self.forget_hidden_rulers(cx);
|
||||
let (targets, points) = if copy { (&self.copy_targets, &self.copy_points) } else { (&self.targets, &self.points) };
|
||||
if let Some(ov) = targets.as_ref().and_then(|t| t.snap_back(self.bounds, d, cx.snap_tol())) {
|
||||
return (Vec2::ZERO, ov);
|
||||
@@ -391,7 +405,8 @@ impl MoveSnap {
|
||||
/// passes an anchor or crosses a ruler guide ([`Targets::snap_point_along`]). A move of zero
|
||||
/// length does not snap, and Snap to Last Location goes back to where the move began first, as
|
||||
/// in [`Self::snap`].
|
||||
pub(crate) fn snap_along(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
|
||||
pub(crate) fn snap_along(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
|
||||
self.forget_hidden_rulers(cx);
|
||||
let len = d.hypot();
|
||||
if !len.is_finite() || len <= 1e-9 {
|
||||
return (d, vec![]);
|
||||
@@ -1957,7 +1972,7 @@ impl SelectionTool {
|
||||
}
|
||||
let mut d = move_delta(start, p, m.shift, cx.constrain_angle);
|
||||
let unsnapped = d;
|
||||
if let Some(snap) = &self.moving {
|
||||
if let Some(snap) = &mut self.moving {
|
||||
(d, self.guides) = if m.shift { snap.snap_along(cx, hold, d, m.alt) } else { snap.snap(cx, hold, d, m.alt) };
|
||||
}
|
||||
// Shift has already constrained `d`: any change is a snap.
|
||||
|
||||
@@ -2198,7 +2198,7 @@ fn move_follows_the_while_moving_option() {
|
||||
let p = paint();
|
||||
let pixel_snap = PixelSnap { moving: false, ..PixelSnap::default() };
|
||||
let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
|
||||
let snap = MoveSnap::new(&c);
|
||||
let mut snap = MoveSnap::new(&c);
|
||||
let (dv, _) = snap.snap(&c, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false);
|
||||
assert!((dv - Vec2::new(3.3, 4.6)).hypot() < 1e-9, "{dv:?}");
|
||||
let on = ToolContext { pixel_snap: PixelSnap::default(), ..c };
|
||||
|
||||
@@ -78,6 +78,8 @@ const ROWS: &[Row] = &[
|
||||
(&["star"], None, &["points"]),
|
||||
// The Ellipse dialog's Anchors.
|
||||
(&["ellipse"], None, &["anchors"]),
|
||||
// Circle Tool Options (`circle::CircleTool`).
|
||||
(&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]),
|
||||
(&["freeTransform"], None, &["constrain"]),
|
||||
// Shape Builder Tool Options (`builder::ShapeBuilderOptions`).
|
||||
(
|
||||
|
||||
@@ -479,6 +479,10 @@ impl VectorcraftApp {
|
||||
if crate::touch::is_drawing_tool(now) {
|
||||
self.ui.touch_drawing_tool = Some(now.to_string());
|
||||
}
|
||||
// Selecting the Quick Pen tool shows its toolbar, even after Hide Toolbar.
|
||||
if now == vectorcraft_tools::quickpen::ID {
|
||||
self.ui.quick_pen_bar = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ impl VectorcraftApp {
|
||||
zoom: self.view().map_or(1.0, |v| v.screen_zoom(self.canvas_ui_zoom)),
|
||||
outline: self.outline_view(),
|
||||
smart_guides: self.ui.view.smart_guides,
|
||||
guides: self.ui.view.guides,
|
||||
guides: self.ui.view.guides_shown(),
|
||||
snap_to_grid: self.ui.view.snap_to_grid,
|
||||
pixel_preview: self.ui.view.pixel_preview,
|
||||
snap_to_pixel: self.ui.view.snap_to_pixel,
|
||||
|
||||
@@ -28,6 +28,7 @@ mod input;
|
||||
mod outline;
|
||||
mod overlays;
|
||||
mod panes;
|
||||
mod quick_pen_bar;
|
||||
mod raster;
|
||||
mod selection_marks;
|
||||
mod task_bar;
|
||||
@@ -68,6 +69,7 @@ use overlays::{
|
||||
};
|
||||
pub use panes::{Layout as TileLayout, Panes};
|
||||
pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area};
|
||||
pub(crate) use quick_pen_bar::quick_pen_bar_rect;
|
||||
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
|
||||
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
|
||||
pub use selection_marks::SelectionMarks;
|
||||
@@ -326,7 +328,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
|
||||
paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view()));
|
||||
// The grid behind the art (Guides & Grid › Grids In Back), else over it below.
|
||||
let grid_look = (app.ui.view.grid && !presenting).then(|| LineLook::grid(&app.session.prefs));
|
||||
let grid_look = (app.ui.view.grid_shown() && !presenting).then(|| LineLook::grid(&app.session.prefs));
|
||||
let grids_in_back = app.session.prefs.grids_in_back;
|
||||
if let Some(look) = grid_look.filter(|_| grids_in_back) {
|
||||
grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look);
|
||||
@@ -416,7 +418,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false });
|
||||
}
|
||||
artboard_outlines(app, ui, &painter, &xf, &t);
|
||||
if app.ui.view.guides {
|
||||
if app.ui.view.guides_shown() {
|
||||
guide_lines(app, &painter, &xf, rect, &t);
|
||||
}
|
||||
nine_slice_overlay(app, &painter, &xf);
|
||||
@@ -463,6 +465,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
task_bar(app, ui, &xf);
|
||||
}
|
||||
if app.ui.screen_mode < 3 {
|
||||
// The Quick Pen toolbar gives way to a drag as the task bar does.
|
||||
quick_pen_bar::quick_pen_bar(app, ui, &xf);
|
||||
contour_bar::contour_bar(app, ui, &xf);
|
||||
// After the task bar, which the row of character alternates keeps clear of.
|
||||
alternates_bar::alternates_bar(app, ui, &xf);
|
||||
@@ -899,7 +903,7 @@ fn cache_key(
|
||||
outline: app.outline_view(),
|
||||
trim: app.ui.view.trim_view,
|
||||
templates: app.ui.view.templates,
|
||||
guides: app.ui.view.guides,
|
||||
guides: app.ui.view.guides_shown(),
|
||||
ppp,
|
||||
hidden: vec![],
|
||||
rot: v.rotation,
|
||||
@@ -1098,7 +1102,7 @@ fn frame_options(
|
||||
overprint_preview: vectorcraft_render::proof::overprint_preview_on(),
|
||||
trim: app.ui.view.trim_view,
|
||||
hide_templates: !app.ui.view.templates,
|
||||
hide_guides: !app.ui.view.guides,
|
||||
hide_guides: !app.ui.view.guides_shown(),
|
||||
tile_edge: vectorcraft_color::Color::from_hex(&app.session.prefs.pattern_tile_edge_color).map_or(opts.tile_edge, |c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
|
||||
@@ -222,7 +222,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
|
||||
if resp.clicked_by(egui::PointerButton::Primary) {
|
||||
ui.data_mut(|d| d.insert_temp(last_click, now));
|
||||
}
|
||||
if resp.double_clicked_by(egui::PointerButton::Primary)
|
||||
// Trim View hides the guides (#8363): a guide made now could not be seen, so none is.
|
||||
let trim_view = app.ui.view.trim_view;
|
||||
let refuse = |app: &mut VectorcraftApp| app.status(crate::menus::TRIM_VIEW_HIDES.to_string());
|
||||
if trim_view && first_here && resp.double_clicked_by(egui::PointerButton::Primary) {
|
||||
refuse(app);
|
||||
}
|
||||
if !trim_view
|
||||
&& resp.double_clicked_by(egui::PointerButton::Primary)
|
||||
&& first_here
|
||||
&& let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()))
|
||||
{
|
||||
@@ -253,12 +260,22 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()));
|
||||
let on_canvas = p.is_some_and(|p| canvas.contains(p));
|
||||
if on_canvas {
|
||||
// The new guide shows even if guides were hidden.
|
||||
app.ui.view.guides = true;
|
||||
// A drag Trim View is on for at any point makes no guide, so none previews, even when
|
||||
// Trim View is turned off again before the release: the whole gesture is cancelled and
|
||||
// stays so until the button is released.
|
||||
let cancel = egui::Id::unique(if vertical { "ruler-left-trim-cancel" } else { "ruler-top-trim-cancel" });
|
||||
if resp.drag_started() {
|
||||
ui.data_mut(|d| d.remove::<bool>(cancel));
|
||||
}
|
||||
if trim_view && ui.data(|d| d.get_temp::<bool>(cancel).is_none()) {
|
||||
refuse(app);
|
||||
ui.data_mut(|d| d.insert_temp(cancel, true));
|
||||
}
|
||||
let cancelled = ui.data(|d| d.get_temp::<bool>(cancel).is_some());
|
||||
if cancelled && kind == PointerKind::Up {
|
||||
ui.data_mut(|d| d.remove::<bool>(cancel));
|
||||
}
|
||||
let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()));
|
||||
let ev = PointerEvent {
|
||||
kind,
|
||||
pos: p.map_or(Point::ZERO, |p| xf.to_doc(p)),
|
||||
@@ -267,6 +284,21 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
|
||||
pressure: 1.0,
|
||||
pen: None,
|
||||
};
|
||||
if cancelled {
|
||||
// A guide already dragged when Trim View turned on ends as a release off the canvas
|
||||
// does: no guide, no undo step.
|
||||
if app.session.ruler_guide_dragging()
|
||||
&& let Err(e) = app.session.ruler_guide(vertical, &PointerEvent { kind: PointerKind::Up, ..ev }, false, app.view_info())
|
||||
{
|
||||
app.status(e.to_string());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let on_canvas = p.is_some_and(|p| canvas.contains(p));
|
||||
if on_canvas {
|
||||
// The new guide shows even if guides were hidden.
|
||||
app.ui.view.guides = true;
|
||||
}
|
||||
if let Err(e) = app.session.ruler_guide(vertical, &ev, on_canvas, app.view_info()) {
|
||||
app.status(e.to_string());
|
||||
}
|
||||
@@ -288,11 +320,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
|
||||
let drag_id = ruler_origin_drag_id();
|
||||
let uid = app.session.active().map(|d| d.uid);
|
||||
if corner.drag_started_by(egui::PointerButton::Primary) {
|
||||
ui.data_mut(|d| d.insert_temp(drag_id, (uid, false)));
|
||||
ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: uid, cancelled: false, trim_view: app.ui.view.trim_view }));
|
||||
}
|
||||
let mut preview = None;
|
||||
if let Some((started_in, mut cancelled)) = ui.data(|d| d.get_temp::<(Option<u64>, bool)>(drag_id)) {
|
||||
cancelled |= started_in != uid || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape));
|
||||
if let Some(OriginDrag { doc: started_in, mut cancelled, trim_view }) = ui.data(|d| d.get_temp::<OriginDrag>(drag_id)) {
|
||||
// Trim View turned on or off during the drag: the snap targets gathered at its start
|
||||
// hold the ruler guides, or leave them out, as they no longer show (#8363), so the origin
|
||||
// could snap to a guide nobody sees. The drag is cancelled as for hidden rulers.
|
||||
cancelled |= started_in != uid || trim_view != app.ui.view.trim_view || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape));
|
||||
let pointer =
|
||||
corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p));
|
||||
// The origin snaps as a drawn point does (Smart Guides, Snap to Point, pixels, the grid).
|
||||
@@ -313,7 +348,7 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
|
||||
} else if !ui.input(|i| i.pointer.primary_down()) {
|
||||
end_ruler_origin_drag(app, ui);
|
||||
} else {
|
||||
ui.data_mut(|d| d.insert_temp(drag_id, (started_in, cancelled)));
|
||||
ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: started_in, cancelled, trim_view }));
|
||||
if !cancelled {
|
||||
preview = at;
|
||||
}
|
||||
@@ -333,10 +368,21 @@ pub(super) fn rulers_hidden(app: &mut VectorcraftApp, ui: &Ui) -> Option<Point>
|
||||
|
||||
/// Ends a drag from the rulers' corner, released or cancelled: its state and its snapping guides go.
|
||||
fn end_ruler_origin_drag(app: &mut VectorcraftApp, ui: &Ui) {
|
||||
ui.data_mut(|d| d.remove::<(Option<u64>, bool)>(ruler_origin_drag_id()));
|
||||
ui.data_mut(|d| d.remove::<OriginDrag>(ruler_origin_drag_id()));
|
||||
app.session.end_ruler_origin_drag();
|
||||
}
|
||||
|
||||
/// A drag of the rulers' origin out of their corner, kept between frames.
|
||||
#[derive(Clone, Copy)]
|
||||
struct OriginDrag {
|
||||
/// The document it started in (`Document::uid`): another one active cancels it.
|
||||
doc: Option<u64>,
|
||||
/// Cancelled (Escape, focus lost, another document, Trim View toggled): it sets nothing.
|
||||
cancelled: bool,
|
||||
/// View › Trim View was on when it started.
|
||||
trim_view: bool,
|
||||
}
|
||||
|
||||
/// The key of the ruler origin drag's state in egui's temporary data.
|
||||
fn ruler_origin_drag_id() -> egui::Id {
|
||||
egui::Id::unique("ruler-origin-drag")
|
||||
@@ -345,7 +391,7 @@ fn ruler_origin_drag_id() -> egui::Id {
|
||||
/// Is a drag from the rulers' corner in progress? It stays true after Escape cancels the move, until
|
||||
/// the button is released.
|
||||
pub(crate) fn ruler_origin_dragging(ctx: &egui::Context) -> bool {
|
||||
ctx.data(|d| d.get_temp::<(Option<u64>, bool)>(ruler_origin_drag_id()).is_some())
|
||||
ctx.data(|d| d.get_temp::<OriginDrag>(ruler_origin_drag_id()).is_some())
|
||||
}
|
||||
|
||||
/// What the rulers count, and from where: `unit`, from `origin` (document points), with each
|
||||
|
||||
@@ -188,7 +188,7 @@ pub(super) fn hit_with<T>(
|
||||
path_only: prefs.object_selection_by_path_only,
|
||||
type_path_only: prefs.type_selection_by_path_only,
|
||||
scope: app.session.active().and_then(|st| st.isolation),
|
||||
skip_guides: !app.ui.view.guides,
|
||||
skip_guides: !app.ui.view.guides_shown(),
|
||||
..Default::default()
|
||||
};
|
||||
test(&app.session.active()?.doc, p, opt)
|
||||
|
||||
@@ -554,7 +554,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
|
||||
let xf = Xf::at(rect, &v, ui_zoom);
|
||||
let painter = ui.painter_at(rect);
|
||||
paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline));
|
||||
let grid_look = app.ui.view.grid.then(|| LineLook::grid(&app.session.prefs));
|
||||
let grid_look = app.ui.view.grid_shown().then(|| LineLook::grid(&app.session.prefs));
|
||||
let grids_in_back = app.session.prefs.grids_in_back;
|
||||
if let Some(look) = grid_look.filter(|_| grids_in_back) {
|
||||
grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look);
|
||||
@@ -587,7 +587,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
|
||||
if shows_artboards(app) {
|
||||
artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false);
|
||||
}
|
||||
if app.ui.view.guides {
|
||||
if app.ui.view.guides_shown() {
|
||||
guides_of(app, st, (&painter, &xf, &t), rect);
|
||||
}
|
||||
if app.ui.view.edges {
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! The Quick Pen toolbar: a floating bar on the canvas while the Quick Pen tool is active. It holds
|
||||
//! the tool's actions (Straight Line, Continuous Arc, Sharp Corner Arc), Flip Arc for the last
|
||||
//! sharp-corner arc, and a More Options menu with Hide Toolbar, Pin Toolbar Position and Reset
|
||||
//! Toolbar Position. Its handle, at its left end, drags it.
|
||||
//!
|
||||
//! Public behavior: selecting the tool shows the toolbar, its actions decide what a click or drag
|
||||
//! draws, Flip Arc flips the sharp-corner arc just drawn, the More menu hides the toolbar and resets
|
||||
//! its position, and the toolbar moves by dragging its left side
|
||||
//! ([Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html)).
|
||||
//! The toolbar follows the drawing, beside the point the path goes on from and away from what was
|
||||
//! drawn ([Behind the design: the Quick Pen tool](https://adobe.design/ideas/behind-the-design-adobe-illustrator-s-quick-pen-tool)).
|
||||
//! VectorCraft's own rules: the exact place beside the point, moving to the drawn side where the
|
||||
//! other side runs off the canvas, the place with no path being drawn, how a drag's offset is kept,
|
||||
//! Pin Toolbar Position (which holds the toolbar at its place in the canvas window, not on the
|
||||
//! artboard), and Window › Quick Pen Toolbar to show it again.
|
||||
|
||||
use vectorcraft_tools::quickpen::{self, Stroke as Action};
|
||||
|
||||
use super::{Color32, CornerRadius, Pos2, Sense, Stroke, Tokens, Ui, Vec2, VectorcraftApp, Xf, json, pos2, vec2, widgets};
|
||||
|
||||
/// The space between the point the path goes on from and the toolbar's nearest corner.
|
||||
const GAP: f32 = 24.0;
|
||||
/// The width of the toolbar's handle.
|
||||
const HANDLE: f32 = 4.0;
|
||||
/// The side of the toolbar's buttons.
|
||||
const BUTTON: f32 = 28.0;
|
||||
/// The space between the toolbar's controls.
|
||||
const SPACING: f32 = 4.0;
|
||||
|
||||
fn bar_id() -> egui::Id {
|
||||
egui::Id::unique("quick-pen-bar")
|
||||
}
|
||||
|
||||
/// Where the Quick Pen toolbar was last drawn (none while it isn't shown).
|
||||
pub(crate) fn quick_pen_bar_rect(ctx: &egui::Context) -> Option<egui::Rect> {
|
||||
let id = bar_id();
|
||||
ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten())
|
||||
}
|
||||
|
||||
/// The toolbar's top-left corner, of `size`, beside `end` (the point the path goes on from, on
|
||||
/// screen), on the side the path arrives there from `dir` (on screen): to its right and below it
|
||||
/// for a path drawn to the right and down, so the toolbar stays off what was drawn. A path of one
|
||||
/// point puts it to the right and below. Where that side runs out of `room` (the canvas) and the
|
||||
/// other side fits, it goes on the other side; where neither fits, on the side with more room.
|
||||
/// Kept in `room` ([`keep_in`]), it covers `end` only when neither side fits across or down.
|
||||
fn beside(end: Pos2, dir: Option<Vec2>, size: Vec2, room: egui::Rect) -> Pos2 {
|
||||
// `first` unless it runs out of room and `other` fits or runs out by less.
|
||||
let pick = |first: f32, other: f32, lo: f32, hi: f32, len: f32| {
|
||||
let over = |p: f32| (lo - p).max(0.0) + (p + len - hi).max(0.0);
|
||||
if over(other) < over(first) { other } else { first }
|
||||
};
|
||||
let (right, left) = (end.x + GAP, end.x - GAP - size.x);
|
||||
let (below, above) = (end.y + GAP, end.y - GAP - size.y);
|
||||
let x = if dir.is_none_or(|d| d.x >= 0.0) { (right, left) } else { (left, right) };
|
||||
let y = if dir.is_none_or(|d| d.y >= 0.0) { (below, above) } else { (above, below) };
|
||||
pos2(pick(x.0, x.1, room.left(), room.right(), size.x), pick(y.0, y.1, room.top(), room.bottom(), size.y))
|
||||
}
|
||||
|
||||
/// The toolbar's place with no path being drawn: centered at the bottom of the canvas area `room`.
|
||||
fn resting(room: egui::Rect, size: Vec2) -> Pos2 {
|
||||
pos2(room.center().x - size.x / 2.0, room.bottom() - size.y)
|
||||
}
|
||||
|
||||
/// `p` moved, as little as it takes, for a toolbar of `size` to lie inside `room`.
|
||||
fn keep_in(p: Pos2, size: Vec2, room: egui::Rect) -> Pos2 {
|
||||
p.clamp(room.min, (room.max - size).max(room.min))
|
||||
}
|
||||
|
||||
/// Where an unpinned toolbar of `size` sits: `home` moved by the drag `offset`, kept in `room`,
|
||||
/// unless that would cover `end` (the point the path goes on from, on screen), where it sits at
|
||||
/// `home` as if never dragged.
|
||||
fn unpinned(home: Pos2, offset: Vec2, end: Option<Pos2>, size: Vec2, room: egui::Rect) -> Pos2 {
|
||||
let moved = keep_in(home + offset, size, room);
|
||||
if end.is_some_and(|e| egui::Rect::from_min_size(moved, size).contains(e)) { keep_in(home, size, room) } else { moved }
|
||||
}
|
||||
|
||||
/// What a click on the toolbar does.
|
||||
enum Click {
|
||||
Action(Action),
|
||||
Run(&'static str, serde_json::Value),
|
||||
}
|
||||
|
||||
/// Is a drag under way (past the drag threshold) that began on the canvas `canvas` outside the
|
||||
/// toolbar's last place `bar`? A stroke, a Space or middle-button pan and a drag from a path's first
|
||||
/// point all are; a drag of the toolbar's handle is not.
|
||||
fn canvas_drag(dragging: bool, press: Option<Pos2>, canvas: egui::Rect, bar: Option<egui::Rect>) -> bool {
|
||||
dragging && press.is_some_and(|p| canvas.contains(p) && !bar.is_some_and(|b| b.contains(p)))
|
||||
}
|
||||
|
||||
/// The Quick Pen toolbar, while the Quick Pen tool is active, Window › Quick Pen Toolbar is on and
|
||||
/// no press is dragging on the canvas. Selecting the tool turns Window › Quick Pen Toolbar on
|
||||
/// ([`VectorcraftApp::try_select_tool`]).
|
||||
pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
|
||||
if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID {
|
||||
return;
|
||||
}
|
||||
let (dragging, press, down) = ui.input(|i| (i.pointer.is_decidedly_dragging(), i.pointer.press_origin(), i.pointer.any_down()));
|
||||
// The handle's drag moves the toolbar away from where the press began.
|
||||
let handle_id = bar_id().with("handle");
|
||||
if !down {
|
||||
ui.ctx().data_mut(|d| d.insert_temp(handle_id, false));
|
||||
}
|
||||
let on_handle = ui.ctx().data(|d| d.get_temp::<bool>(handle_id)).unwrap_or(false);
|
||||
let shown = app.ui.quick_pen_bar_place.shown_at.zip(egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size));
|
||||
if canvas_drag(dragging && !on_handle, press, xf.rect, shown.map(|(at, size)| egui::Rect::from_min_size(xf.rect.min + at, size))) {
|
||||
return;
|
||||
}
|
||||
let Some(doc) = app.session.active().map(|st| st.uid) else { return };
|
||||
let view = app.view_info();
|
||||
let end = app.session.tool_drawing_end(view);
|
||||
let flip = app.session.tool_claims_key(vectorcraft_tools::ToolKey::Letter('c'), view);
|
||||
let current = app.session.tool_options().get("action").and_then(serde_json::Value::as_str).and_then(Action::parse).unwrap_or_default();
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let id = bar_id();
|
||||
let bounds = xf.rect.shrink(8.0);
|
||||
let est = vec2(HANDLE + 5.0 * BUTTON + 6.0 * SPACING + 16.0, BUTTON + 12.0);
|
||||
let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).unwrap_or(est);
|
||||
let end = end.map(|(p, dir)| {
|
||||
let at = xf.to_screen(p);
|
||||
(at, dir.map(|d| xf.to_screen(p + d) - at))
|
||||
});
|
||||
let drawing = end.is_some();
|
||||
let home = match end {
|
||||
Some((at, dir)) => beside(at, dir, size, bounds),
|
||||
None => resting(bounds, size),
|
||||
};
|
||||
let place = &mut app.ui.quick_pen_bar_place;
|
||||
// Just unpinned: follow the drawing from the pinned spot.
|
||||
if !place.pinned
|
||||
&& let Some(at) = place.pin_at.take()
|
||||
{
|
||||
place.offset = Some((doc, drawing, xf.rect.min + at - home));
|
||||
}
|
||||
// A drag's offset holds in the document and the kind of place (beside the drawing, or resting)
|
||||
// it was made in.
|
||||
let offset = place.offset.filter(|(d, beside, _)| *d == doc && *beside == drawing).map_or(Vec2::ZERO, |(_, _, o)| o);
|
||||
let pos = match place.pin_at {
|
||||
Some(at) => keep_in(xf.rect.min + at, size, bounds),
|
||||
None => unpinned(home, offset, end.map(|(at, _)| at), size, bounds),
|
||||
};
|
||||
place.shown_at = Some(pos - xf.rect.min);
|
||||
// Pinned before it ever showed: hold it here.
|
||||
if place.pinned && place.pin_at.is_none() {
|
||||
place.pin_at = place.shown_at;
|
||||
}
|
||||
let pinned = place.pinned;
|
||||
let mut moved = Vec2::ZERO;
|
||||
let mut click: Option<Click> = None;
|
||||
egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(t.panel)
|
||||
.stroke(Stroke::new(1.0, t.tool_active))
|
||||
.corner_radius(CornerRadius::same(5))
|
||||
.inner_margin(egui::Margin::symmetric(8, 6))
|
||||
.shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: Color32::from_black_alpha(70) })
|
||||
.show(ui, |ui| {
|
||||
// In a canvas pane narrower than the toolbar, its controls wrap onto more rows.
|
||||
ui.set_max_width((bounds.width() - 18.0).max(HANDLE + SPACING + BUTTON));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(SPACING, SPACING);
|
||||
let (g, grip) = ui.allocate_exact_size(vec2(HANDLE, BUTTON), Sense::drag());
|
||||
let active = grip.hovered() || grip.dragged();
|
||||
ui.painter().rect_filled(g.shrink2(vec2(0.5, 4.0)), CornerRadius::same(2), if active { t.text_dim } else { t.button_border });
|
||||
if grip.dragged() {
|
||||
ui.ctx().data_mut(|d| d.insert_temp(handle_id, true));
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
moved = grip.drag_delta();
|
||||
} else if grip.hovered() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
|
||||
}
|
||||
let actions = [
|
||||
(Action::Line, "dc-line", tl!("Straight Line")),
|
||||
(Action::ContinuousArc, "spline", tl!("Continuous Arc")),
|
||||
(Action::SharpArc, "dc-arc", tl!("Sharp Corner Arc")),
|
||||
];
|
||||
for (action, icon, tip) in actions {
|
||||
if widgets::icon_button(ui, icon, tip, current == action, BUTTON).clicked() {
|
||||
click = Some(Click::Action(action));
|
||||
}
|
||||
}
|
||||
if widgets::icon_button_enabled(ui, "flip-horizontal-2", tl!("Flip Arc"), false, flip, BUTTON).clicked() {
|
||||
click = Some(Click::Run("tool.quickPen.flipArc", json!({})));
|
||||
}
|
||||
let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, BUTTON);
|
||||
egui::Popup::menu(&more).show(|ui| {
|
||||
ui.set_min_width(170.0);
|
||||
let items = [
|
||||
(tl!("Hide Toolbar"), "window.quickPenToolbar", false),
|
||||
(tl!("Pin Toolbar Position"), "window.quickPenToolbar.pin", pinned),
|
||||
(tl!("Reset Toolbar Position"), "window.quickPenToolbar.reset", false),
|
||||
];
|
||||
for (label, cmd, checked) in items {
|
||||
if widgets::menu_item(ui, label, true, checked) {
|
||||
click = Some(Click::Run(cmd, json!({})));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
if moved != Vec2::ZERO {
|
||||
let to = keep_in(pos + moved, size, bounds);
|
||||
let place = &mut app.ui.quick_pen_bar_place;
|
||||
if place.pinned {
|
||||
place.pin_at = Some(to - xf.rect.min);
|
||||
} else {
|
||||
place.offset = Some((doc, drawing, to - home));
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
let r = match click {
|
||||
Some(Click::Action(a)) => app.run("tool.setOption", json!({"key": "action", "value": a.name()})).map(|_| ()),
|
||||
Some(Click::Run(cmd, p)) => app.run(cmd, p).map(|_| ()),
|
||||
None => Ok(()),
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.ui.status = e;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The toolbar sits off what was drawn: ahead of a path drawn right and down, behind-left and
|
||||
/// above for one drawn left and up, and to the right and below a single point.
|
||||
#[test]
|
||||
fn the_toolbar_sits_beside_the_end_away_from_the_drawing() {
|
||||
let (end, size) = (pos2(500.0, 300.0), vec2(180.0, 40.0));
|
||||
let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0));
|
||||
assert_eq!(beside(end, Some(vec2(1.0, 0.0)), size, room), pos2(524.0, 324.0));
|
||||
assert_eq!(beside(end, Some(vec2(-1.0, -1.0)), size, room), pos2(500.0 - 24.0 - 180.0, 300.0 - 24.0 - 40.0));
|
||||
assert_eq!(beside(end, Some(vec2(0.0, 1.0)), size, room), pos2(524.0, 324.0));
|
||||
assert_eq!(beside(end, Some(vec2(-1.0, 0.5)), size, room), pos2(296.0, 324.0));
|
||||
assert_eq!(beside(end, None, size, room), pos2(524.0, 324.0));
|
||||
assert_eq!(resting(room, size), pos2(318.0, 568.0));
|
||||
// Near the canvas's bottom right corner, the side that runs off it gives way to the other.
|
||||
let corner = pos2(700.0, 580.0);
|
||||
assert_eq!(beside(corner, Some(vec2(1.0, 1.0)), size, room), pos2(700.0 - 24.0 - 180.0, 580.0 - 24.0 - 40.0));
|
||||
// Near the top left corner, a path heading up and left still gets a toolbar off its end.
|
||||
let corner = pos2(30.0, 30.0);
|
||||
assert_eq!(beside(corner, Some(vec2(-1.0, -1.0)), size, room), pos2(54.0, 54.0));
|
||||
// On a canvas too narrow for either side across, the toolbar goes on the side with more
|
||||
// room and stays off the end by going below it.
|
||||
let narrow = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(208.0, 608.0));
|
||||
let end = pos2(60.0, 300.0);
|
||||
let at = keep_in(beside(end, Some(vec2(-1.0, 1.0)), size, narrow), size, narrow);
|
||||
assert_eq!(at, pos2(28.0, 324.0));
|
||||
assert!(!egui::Rect::from_min_size(at, size).contains(end));
|
||||
}
|
||||
|
||||
/// Any drag that began on the canvas hides the toolbar, whether or not the tool has a press
|
||||
/// (a pan does not); a drag that began on the toolbar, and no drag, do not.
|
||||
#[test]
|
||||
fn a_drag_that_began_on_the_canvas_hides_the_toolbar() {
|
||||
let canvas = egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 600.0));
|
||||
let bar = Some(egui::Rect::from_min_size(pos2(300.0, 500.0), vec2(180.0, 40.0)));
|
||||
assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, bar), "a pan or stroke on the canvas");
|
||||
assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, None), "no toolbar shown yet");
|
||||
assert!(!canvas_drag(false, Some(pos2(100.0, 100.0)), canvas, bar), "a click, not a drag");
|
||||
assert!(!canvas_drag(true, Some(pos2(310.0, 510.0)), canvas, bar), "the toolbar's own drag");
|
||||
assert!(!canvas_drag(true, Some(pos2(900.0, 100.0)), canvas, bar), "a drag in another panel");
|
||||
assert!(!canvas_drag(true, None, canvas, bar));
|
||||
}
|
||||
|
||||
/// A drag's offset moves the toolbar from its place, unless that would put it over the point
|
||||
/// the path goes on from.
|
||||
#[test]
|
||||
fn a_dragged_toolbar_never_covers_the_end() {
|
||||
let size = vec2(180.0, 40.0);
|
||||
let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0));
|
||||
let (end, home) = (pos2(500.0, 300.0), pos2(524.0, 324.0));
|
||||
assert_eq!(unpinned(home, vec2(30.0, 40.0), Some(end), size, room), pos2(554.0, 364.0));
|
||||
assert_eq!(unpinned(home, vec2(-60.0, -40.0), Some(end), size, room), home, "over the end");
|
||||
assert_eq!(unpinned(home, vec2(-60.0, -40.0), None, size, room), pos2(464.0, 284.0));
|
||||
assert_eq!(unpinned(home, vec2(900.0, 0.0), Some(end), size, room), pos2(628.0, 324.0), "kept on the canvas");
|
||||
}
|
||||
}
|
||||
@@ -15357,3 +15357,250 @@ fn auto_spell_check_is_a_toggle_of_the_canvas_lines() {
|
||||
assert_eq!(count(&mut app), 0, "off");
|
||||
assert!(app.canvas.spelling.lines.is_empty(), "no node is kept");
|
||||
}
|
||||
|
||||
/// #8363: Trim View hides the ruler guides, the guide paths and the grid while it is on, and they
|
||||
/// are neither snapped to nor picked, as hidden guides are; turned off, they come back as they
|
||||
/// were. The rulers stay.
|
||||
#[test]
|
||||
fn trim_view_hides_the_guides_and_the_grid() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.canvas.worker_started = true; // render on this thread
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.session.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap();
|
||||
app.run("view.guides.make", json!({})).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
(app.ui.view.grid, app.ui.view.guides, app.ui.view.rulers) = (true, true, true);
|
||||
let (red, green) = (Color32::from_rgb(255, 0, 0), Color32::from_rgb(0, 255, 0));
|
||||
app.session.execute("prefs.set", &json!({"values": {"gridColor": "#ff0000", "guideColor": "#00ff00"}})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
// → (a gridline, a ruler guide, guide paths in the art, guides snapped to and picked).
|
||||
let drawn = |app: &mut VectorcraftApp| {
|
||||
let s = shapes(app, &ctx);
|
||||
let line = |c: Color32| s.iter().any(|s| matches!(s, Shape::LineSegment { stroke, .. } if stroke.color == c));
|
||||
let guide_paths = !app.canvas.shown.as_ref().unwrap().1.hide_guides;
|
||||
(line(red), line(green), guide_paths, app.view_info().guides)
|
||||
};
|
||||
assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: all of them");
|
||||
|
||||
app.run("view.trimView", json!({})).unwrap();
|
||||
assert_eq!(drawn(&mut app), (false, false, false, false), "Trim View on: none of them");
|
||||
assert!(app.ui.view.grid && app.ui.view.guides && app.ui.view.rulers, "the choices stay, and so do the rulers");
|
||||
|
||||
app.run("view.trimView", json!({})).unwrap();
|
||||
assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: back as they were");
|
||||
|
||||
// Hidden before, they stay hidden after.
|
||||
app.run("view.guides", json!({})).unwrap();
|
||||
app.run("view.trimView", json!({})).unwrap();
|
||||
app.run("view.trimView", json!({})).unwrap();
|
||||
assert_eq!(drawn(&mut app), (true, false, false, false), "guides hidden before Trim View stay hidden");
|
||||
}
|
||||
|
||||
/// #8363: a selected guide path is deselected when Trim View hides it, as Hide Guides does (#3219).
|
||||
#[test]
|
||||
fn trim_view_deselects_selected_guide_paths() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("view.guides.make", json!({})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id)]);
|
||||
|
||||
app.run("view.trimView", json!({})).unwrap();
|
||||
|
||||
assert!(app.session.active().unwrap().selection.objects.is_empty());
|
||||
}
|
||||
|
||||
/// #8363: Trim View hides the guides, so a guide dragged or double-clicked out of a ruler while it
|
||||
/// is on would be made but never seen. None is: no preview line, no guide, no undo step, the
|
||||
/// stored Show/Hide Guides choice is left alone, and the status line says why. A drag already
|
||||
/// going when Trim View turns on ends as a release off the canvas does.
|
||||
#[test]
|
||||
fn trim_view_makes_no_guide_from_the_rulers() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.ui.view.rulers = true;
|
||||
app.ui.view.guides = false;
|
||||
app.ui.view.smart_guides = false;
|
||||
app.ui.view.snap_to_point = false;
|
||||
app.ui.view.trim_view = true;
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let rect = app.canvas_rect.unwrap();
|
||||
let from = pos2(rect.center().x, rect.top() - RULER / 2.0);
|
||||
let at = pos2(rect.center().x, rect.top() + 120.0);
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let across = |s: &Shape| {
|
||||
matches!(s, Shape::LineSegment { points, .. }
|
||||
if (points[0].y - at.y).abs() <= 2.0 && points[0].y == points[1].y && (points[1].x - points[0].x).abs() >= rect.width() - 0.5)
|
||||
};
|
||||
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len();
|
||||
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
|
||||
let before = steps(&app);
|
||||
|
||||
// A drag: nothing previews and nothing is made.
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
|
||||
frame(&mut app, &ctx, vec![button(from, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews");
|
||||
assert!(!app.session.ruler_guide_dragging());
|
||||
frame(&mut app, &ctx, vec![button(at, false)]);
|
||||
assert_eq!(count(&app), 0, "no guide from a drag");
|
||||
assert!(!app.ui.view.guides, "the stored choice is left alone");
|
||||
assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES);
|
||||
|
||||
// A double-click: nothing either.
|
||||
app.ui.status.clear();
|
||||
let click = |app: &mut VectorcraftApp| {
|
||||
frame(app, &ctx, vec![egui::Event::PointerMoved(from)]);
|
||||
frame(app, &ctx, vec![button(from, true)]);
|
||||
frame(app, &ctx, vec![button(from, false)]);
|
||||
};
|
||||
click(&mut app);
|
||||
click(&mut app);
|
||||
assert_eq!(count(&app), 0, "no guide from a double-click");
|
||||
assert!(!app.ui.view.guides);
|
||||
assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES);
|
||||
assert_eq!(steps(&app), before, "no undo step");
|
||||
|
||||
// Trim View turned on during a drag: the drag ends without a guide.
|
||||
app.ui.view.trim_view = false;
|
||||
let from2 = pos2(rect.center().x + 30.0, rect.top() - RULER / 2.0);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from2)]);
|
||||
frame(&mut app, &ctx, vec![button(from2, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
assert!(app.session.ruler_guide_dragging(), "the drag started with Trim View off");
|
||||
app.ui.view.trim_view = true;
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x + 5.0, at.y))]);
|
||||
assert!(!app.session.ruler_guide_dragging(), "ended");
|
||||
assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews");
|
||||
frame(&mut app, &ctx, vec![button(at, false)]);
|
||||
assert_eq!(count(&app), 0, "no guide from the drag Trim View interrupted");
|
||||
assert_eq!(steps(&app), before, "no undo step");
|
||||
|
||||
// With Trim View off again, a drag makes a guide as before.
|
||||
app.ui.view.trim_view = false;
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
|
||||
frame(&mut app, &ctx, vec![button(from, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
frame(&mut app, &ctx, vec![button(at, false)]);
|
||||
assert_eq!(count(&app), 1);
|
||||
assert!(app.ui.view.guides, "the new guide shows");
|
||||
}
|
||||
|
||||
/// #8363: a guide drag Trim View cancelled stays cancelled until the button is released. Trim
|
||||
/// View turned off again before the release does not start a new guide: the release makes none
|
||||
/// and adds no undo step. The next drag works as before.
|
||||
#[test]
|
||||
fn a_ruler_drag_trim_view_cancelled_stays_cancelled_until_released() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.ui.view.rulers = true;
|
||||
app.ui.view.smart_guides = false;
|
||||
app.ui.view.snap_to_point = false;
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let rect = app.canvas_rect.unwrap();
|
||||
let from = pos2(rect.center().x, rect.top() - RULER / 2.0);
|
||||
let at = pos2(rect.center().x, rect.top() + 120.0);
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len();
|
||||
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
|
||||
let before = steps(&app);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
|
||||
frame(&mut app, &ctx, vec![button(from, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
assert!(app.session.ruler_guide_dragging());
|
||||
app.ui.view.trim_view = true;
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 5.0))]);
|
||||
assert!(!app.session.ruler_guide_dragging(), "Trim View ends the drag");
|
||||
app.ui.view.trim_view = false;
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 10.0))]);
|
||||
assert!(!app.session.ruler_guide_dragging(), "turned off again, no new guide starts");
|
||||
frame(&mut app, &ctx, vec![button(pos2(at.x, at.y + 10.0), false)]);
|
||||
assert_eq!(count(&app), 0, "the release makes no guide");
|
||||
assert_eq!(steps(&app), before, "no undo step");
|
||||
// The next drag makes a guide.
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
|
||||
frame(&mut app, &ctx, vec![button(from, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
frame(&mut app, &ctx, vec![button(at, false)]);
|
||||
assert_eq!(count(&app), 1);
|
||||
}
|
||||
|
||||
/// #8363: Trim View turned on or off during a drag of the rulers' origin out of their corner
|
||||
/// cancels it, as hiding the rulers does: the snap targets gathered at its start would hold
|
||||
/// guides Trim View hides. The origin is left where it was. A drag wholly with Trim View on, or
|
||||
/// wholly off, sets it.
|
||||
#[test]
|
||||
fn trim_view_toggled_during_a_ruler_origin_drag_cancels_it() {
|
||||
for (start, end, sets) in [(false, true, false), (true, false, false), (true, true, true), (false, false, true)] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.session.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap();
|
||||
app.ui.view.rulers = true;
|
||||
app.ui.view.trim_view = start;
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let rect = app.canvas_rect.unwrap();
|
||||
let xf = Xf::new(rect, app.view().unwrap());
|
||||
let origin = |app: &VectorcraftApp| {
|
||||
let d = &app.session.active().unwrap().doc;
|
||||
format!("{:?} {:?}", d.ruler_origin, d.artboard_ruler_origins)
|
||||
};
|
||||
let was = origin(&app);
|
||||
let from = pos2(rect.left() - RULER / 2.0, rect.top() - RULER / 2.0);
|
||||
let at = xf.to_screen(Point::new(151.0, 100.0));
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
|
||||
frame(&mut app, &ctx, vec![button(from, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
assert!(crate::canvas::ruler_origin_dragging(&ctx), "{start} {end}: dragging");
|
||||
app.ui.view.trim_view = end;
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + vec2(1.0, 0.0))]);
|
||||
frame(&mut app, &ctx, vec![button(at + vec2(1.0, 0.0), false)]);
|
||||
assert_eq!(origin(&app) != was, sets, "Trim View {start} then {end}: origin set {sets}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8363: a Selection move begun with the guides shown gathers the ruler guides to snap to. When
|
||||
/// they stop showing during the move (Trim View or Hide Guides turned on), it no longer snaps to
|
||||
/// them; with them shown throughout, it does.
|
||||
#[test]
|
||||
fn a_move_stops_snapping_to_guides_hidden_during_it() {
|
||||
// What hides the guides mid-move (none: they stay shown), and whether the move then snaps.
|
||||
for (hide, snaps) in [(None, true), (Some("trim"), false), (Some("guides"), false)] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 50, "height": 50})).unwrap();
|
||||
app.session.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap();
|
||||
app.select_tool("selection");
|
||||
app.ui.view.smart_guides = false;
|
||||
app.ui.view.snap_to_point = true;
|
||||
app.ui.view.guides = true;
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let rect = app.canvas_rect.unwrap();
|
||||
let xf = Xf::new(rect, app.view().unwrap());
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
// Grabbed at its centre, moved first well away from the guide, then 1.5 px short of it.
|
||||
let grab = xf.to_screen(Point::new(75.0, 75.0));
|
||||
let away = xf.to_screen(Point::new(120.0, 75.0));
|
||||
let near = xf.to_screen(Point::new(200.0, 75.0)) - vec2(1.5, 0.0);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)]);
|
||||
frame(&mut app, &ctx, vec![button(grab, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(away)]);
|
||||
match hide {
|
||||
Some("trim") => app.ui.view.trim_view = true,
|
||||
Some(_) => app.ui.view.guides = false,
|
||||
None => {}
|
||||
}
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(near)]);
|
||||
frame(&mut app, &ctx, vec![button(near, false)]);
|
||||
let b = app.session.active().unwrap().doc.art_bounds().unwrap();
|
||||
let centre = (b.x0 + b.x1) / 2.0;
|
||||
assert_eq!((centre - 200.0).abs() < 1e-6, snaps, "{hide:?}: the grabbed centre at {centre}");
|
||||
assert!((centre - xf.to_doc(near).x).abs() < 1e-6 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}");
|
||||
}
|
||||
}
|
||||
@@ -209,7 +209,8 @@ pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option<u64>) {
|
||||
(text, Some(next))
|
||||
}
|
||||
StatusBarShow::Undos => {
|
||||
let text = st.map(|d| format!("{}: {} {}: {}", tl!("Undos"), d.history.undo.len(), tl!("Redos"), d.history.redo.len()));
|
||||
let (undos, redos) = (crate::i18n::colon(tl!("Undos")), crate::i18n::colon(tl!("Redos")));
|
||||
let text = st.map(|d| format!("{undos} {} {redos} {}", d.history.undo.len(), d.history.redo.len()));
|
||||
(text.unwrap_or_default(), None)
|
||||
}
|
||||
StatusBarShow::ColorProfile => (st.map(|d| color_profile_name(&d.doc)).unwrap_or_default(), None),
|
||||
|
||||
@@ -1127,6 +1127,12 @@ fn the_status_bar_info_field_shows_the_chosen_readout() {
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(counts(&app), format!("Undos: {before} Redos: 1"));
|
||||
assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == counts(&app)), "the redo step counts");
|
||||
// The labels take the UI language's colon (#7991).
|
||||
let fr = crate::i18n::Lang::from_code("fr").unwrap();
|
||||
crate::i18n::set_current(fr);
|
||||
let (french, _) = super::status_bar::info_text(&app);
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
assert_eq!(french, format!("{}\u{a0}: {before} {}\u{a0}: 1", crate::i18n::tr(fr, "Undos"), crate::i18n::tr(fr, "Redos")));
|
||||
|
||||
app.run("view.statusBarShow", json!({"show": "colorProfile"})).unwrap();
|
||||
let working = vectorcraft_color::cms::working_settings();
|
||||
|
||||
@@ -268,6 +268,11 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
|
||||
"pinned": app.ui.task_bar_place.pinned,
|
||||
"rect": crate::canvas::task_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
|
||||
},
|
||||
// The Quick Pen toolbar: pinned (not saved either) and where it shows.
|
||||
"quickPenToolbar": {
|
||||
"pinned": app.ui.quick_pen_bar_place.pinned,
|
||||
"rect": crate::canvas::quick_pen_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
|
||||
},
|
||||
// The Free Transform tool's widget, where it shows.
|
||||
"freeTransformWidget": crate::free_transform::rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
|
||||
"view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()),
|
||||
|
||||
@@ -25,6 +25,7 @@ pub mod brush_replace_art;
|
||||
pub mod bullets_numbering;
|
||||
pub mod char_style_options;
|
||||
pub mod check_spelling;
|
||||
pub mod circle_options;
|
||||
pub mod color_balance;
|
||||
pub mod color_group_options;
|
||||
pub mod color_guide_options;
|
||||
@@ -155,6 +156,7 @@ mod tiff_bmp_tga;
|
||||
pub mod tile_edge_color;
|
||||
mod tools;
|
||||
pub mod trace_presets;
|
||||
pub mod tracing_presets;
|
||||
pub(crate) mod transform;
|
||||
pub mod transform_each;
|
||||
pub mod variables;
|
||||
@@ -381,6 +383,9 @@ registry! {
|
||||
FlattenTransparency: [flatten::KIND] => flatten::SPEC,
|
||||
FlattenerPresets: [flattener_presets::KIND] => flattener_presets::SPEC,
|
||||
ImageTracePreset: [trace_presets::KIND] => trace_presets::SPEC,
|
||||
TracingPresets: [tracing_presets::KIND] => tracing_presets::SPEC,
|
||||
TracingPreset: [tracing_presets::PRESET_KIND] => tracing_presets::PRESET_SPEC,
|
||||
TracingPresetsReplace: [tracing_presets::REPLACE_KIND] => tracing_presets::REPLACE_SPEC,
|
||||
SaveStyleLibrary: [save_style_library::KIND] => save_style_library::SPEC,
|
||||
SaveSymbolLibrary: [save_symbol_library::KIND] => save_symbol_library::SPEC,
|
||||
SaveBrushLibrary: [save_brush_library::KIND] => save_brush_library::SPEC,
|
||||
@@ -472,6 +477,7 @@ registry! {
|
||||
FreehandOptions: [freehand::KIND] => freehand::SPEC,
|
||||
ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC,
|
||||
ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC,
|
||||
CircleOptions: [circle_options::KIND] => circle_options::SPEC,
|
||||
ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC,
|
||||
FlareOptions: [flare_options::KIND] => flare_options::SPEC,
|
||||
SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC,
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! Circle Tool Options (double-click the Circle tool, or `tool.options`): Show Center, Show Radii
|
||||
//! and Show Diameter switch the center cross, the radius lines and the diameter label the tool
|
||||
//! shows while a circle is drawn; Color is the color of the cross and the lines; Anchors at
|
||||
//! Standard Positions off puts the circle's anchors at the points it was drawn through; Third
|
||||
//! Point by Dragging off places the second point with a click and the third with another. OK sets
|
||||
//! them with `tool.setOption {tool: "circle", values}`; they last across tool switches and are
|
||||
//! saved with the preferences.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_tools::circle::{COLORS, ID as TOOL};
|
||||
|
||||
use super::{DialogSpec, run_and_close};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// The dialog kind of Circle Tool Options.
|
||||
pub const KIND: &str = "circleOptions";
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM };
|
||||
|
||||
/// The options the dialog edits, in the order it shows its check boxes, with their labels.
|
||||
const SWITCHES: [(&str, &str); 5] = [
|
||||
("center", "Show Center"),
|
||||
("radii", "Show Radii"),
|
||||
("diameter", "Show Diameter"),
|
||||
("standardAnchors", "Anchors at Standard Positions"),
|
||||
("dragThird", "Third Point by Dragging"),
|
||||
];
|
||||
|
||||
/// The labels of [`COLORS`], in its order.
|
||||
const COLOR_LABELS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"];
|
||||
|
||||
/// Width of the label column.
|
||||
const LABEL_W: f32 = 60.0;
|
||||
|
||||
fn heading(_: &Dialog) -> String {
|
||||
let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label);
|
||||
crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))])
|
||||
}
|
||||
|
||||
/// Open the tool's options with their current values.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Value {
|
||||
let o = app.session.tool_options_of(TOOL);
|
||||
let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]);
|
||||
let fields: Map<String, Value> = keys.filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect();
|
||||
app.ui.dialog = Some(Dialog { kind: KIND.into(), fields });
|
||||
json!({ "dialog": KIND })
|
||||
}
|
||||
|
||||
fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) {
|
||||
let on = d.bool(key);
|
||||
if widgets::check(ui, tl!(label), on, true) {
|
||||
d.fields.insert(key.into(), json!(!on));
|
||||
}
|
||||
}
|
||||
|
||||
fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
for (key, label) in &SWITCHES[..3] {
|
||||
check(ui, d, key, label);
|
||||
}
|
||||
let color = d.str("color");
|
||||
let at = COLORS.iter().position(|(name, _)| *name == color).unwrap_or(1);
|
||||
widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| {
|
||||
let shown = COLOR_LABELS.get(at).copied().unwrap_or("Blue");
|
||||
if let Some((name, _)) =
|
||||
widgets::dropdown_named(ui, "circle-options-color", Some(tl!("Color:")), shown, &COLOR_LABELS, 110.0).and_then(|i| COLORS.get(i))
|
||||
{
|
||||
d.fields.insert("color".into(), json!(name));
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
for (key, label) in &SWITCHES[3..] {
|
||||
check(ui, d, key, label);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// OK: set the tool's options.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]);
|
||||
let values: Map<String, Value> = keys.filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect();
|
||||
run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// 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()))
|
||||
}
|
||||
|
||||
/// Every label the dialog shows has a row for each of [`COLORS`].
|
||||
#[test]
|
||||
fn every_color_has_a_label() {
|
||||
assert_eq!(COLOR_LABELS.len(), COLORS.len());
|
||||
for (label, (name, _)) in COLOR_LABELS.iter().zip(COLORS) {
|
||||
assert_eq!(label.to_lowercase(), *name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() {
|
||||
let mut app = app();
|
||||
let o = app.session.tool_options_of(TOOL);
|
||||
for key in ["center", "radii", "diameter", "standardAnchors", "dragThird"] {
|
||||
assert_eq!(o[key], json!(true), "{key}");
|
||||
}
|
||||
assert_eq!(o["color"], json!("blue"));
|
||||
let r = app.run("tool.options", json!({"tool": TOOL})).unwrap();
|
||||
assert_eq!(r["dialog"], json!(KIND));
|
||||
let text = painted(&mut app);
|
||||
for label in [
|
||||
"Circle Tool Options",
|
||||
"Show Center",
|
||||
"Show Radii",
|
||||
"Show Diameter",
|
||||
"Color:",
|
||||
"Blue",
|
||||
"Anchors at Standard Positions",
|
||||
"Third Point by Dragging",
|
||||
"OK",
|
||||
"Cancel",
|
||||
] {
|
||||
assert!(text.contains(label), "{label} in {text}");
|
||||
}
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
for key in ["radii", "standardAnchors", "dragThird"] {
|
||||
assert!(d.bool(key), "{key}");
|
||||
d.fields.insert(key.into(), json!(false));
|
||||
}
|
||||
d.fields.insert("color".into(), json!("magenta"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
let o = app.session.tool_options_of(TOOL);
|
||||
let got: Vec<&Value> = ["center", "radii", "diameter", "standardAnchors", "dragThird", "color"].iter().map(|k| &o[*k]).collect();
|
||||
assert_eq!(got, [&json!(true), &json!(false), &json!(true), &json!(false), &json!(false), &json!("magenta")]);
|
||||
// They last while another tool is chosen, and the dialog opens on them again.
|
||||
app.select_tool(TOOL);
|
||||
app.select_tool("selection");
|
||||
app.run("tool.options", json!({"tool": TOOL})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert!(!d.bool("standardAnchors") && d.bool("center"));
|
||||
assert_eq!(d.str("color"), "magenta");
|
||||
}
|
||||
|
||||
/// `tool.setOption` takes only the values the options take, and an invalid one changes none.
|
||||
#[test]
|
||||
fn invalid_values_are_errors_and_change_nothing() {
|
||||
let mut app = app();
|
||||
for (values, error) in [
|
||||
(json!({"center": false, "radii": "no"}), "`radii` must be true or false"),
|
||||
(json!({"center": false, "color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"),
|
||||
(json!({"center": false, "size": 3}), "unknown Circle tool option `size`"),
|
||||
] {
|
||||
let e = app.run("tool.setOption", json!({"tool": TOOL, "values": values})).unwrap_err();
|
||||
assert!(e.contains(error), "{e}");
|
||||
assert_eq!(app.session.tool_options_of(TOOL)["center"], json!(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,12 @@
|
||||
//! For Fractions; OK runs `graph.column`.
|
||||
//! Marker: the design the selected graph series draw their data points with, or None (the default
|
||||
//! square marker); OK runs `graph.marker`.
|
||||
//! Column and Marker also list, under each library's name, the graph designs of the documents
|
||||
//! Window › Swatch Libraries › Other Library… loaded that the document lacks; OK on one copies it
|
||||
//! into the document with the resources its art uses.
|
||||
//!
|
||||
//! Fields: `selected` (the selected designs' names; Column and Marker: one name, null for None),
|
||||
//! in Column and Marker `library` (the library of the selected design, null for the document's),
|
||||
//! in Graph Design `name` (the name Rename gives), and in Column `columnType`, `each` and
|
||||
//! `fractions`.
|
||||
|
||||
@@ -46,6 +50,7 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec {
|
||||
confirm: |app, d| {
|
||||
let p = json!({
|
||||
"design": d.fields.get("selected").and_then(Value::as_str),
|
||||
"library": library_of(d),
|
||||
"columnType": d.str("columnType"),
|
||||
"each": d.f64("each", vectorcraft_doc::ColumnDesign::EACH),
|
||||
"fractions": d.str("fractions"),
|
||||
@@ -59,7 +64,9 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec {
|
||||
pub(super) const MARKER_SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Graph Marker").into(),
|
||||
body: marker_body,
|
||||
confirm: |app, d| run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str) })),
|
||||
confirm: |app, d| {
|
||||
run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str), "library": library_of(d) }))
|
||||
},
|
||||
min_width: 300.0,
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
@@ -95,6 +102,24 @@ fn names(app: &VectorcraftApp) -> Result<Vec<String>, String> {
|
||||
Ok(st.doc.graph_designs.iter().map(|d| d.name.clone()).collect())
|
||||
}
|
||||
|
||||
/// The designs of the loaded libraries that the document lacks (the document's own design of a name
|
||||
/// is the one used), by library: its id, its name and the design names, libraries with none left
|
||||
/// out.
|
||||
fn library_designs(app: &VectorcraftApp) -> Vec<(String, String, Vec<String>)> {
|
||||
let own = names(app).unwrap_or_default();
|
||||
app.session
|
||||
.graph_design_libraries
|
||||
.iter()
|
||||
.map(|l| (l.id.clone(), l.name.clone(), l.doc.graph_designs.iter().map(|g| g.name.clone()).filter(|n| !own.contains(n)).collect::<Vec<_>>()))
|
||||
.filter(|(.., names)| !names.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Column and Marker's `library`: the library of the selected design, `None` for the document's.
|
||||
fn library_of(d: &Dialog) -> Option<&str> {
|
||||
d.fields.get("library").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// Graph Design's selected designs.
|
||||
fn selected(d: &Dialog) -> Vec<String> {
|
||||
d.fields.get("selected").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
@@ -105,8 +130,9 @@ fn select(d: &mut Dialog, names: Vec<String>) {
|
||||
d.fields.insert("selected".into(), json!(names));
|
||||
}
|
||||
|
||||
/// A design's art drawn in `r` (cached by the art's identity).
|
||||
fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) {
|
||||
/// A design's art drawn in `r` (cached by the art's identity): the document's design `name`, or
|
||||
/// with `library` that loaded library's.
|
||||
fn preview(ui: &egui::Ui, app: &VectorcraftApp, library: Option<&str>, name: &str, r: egui::Rect) {
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
thread_local! {
|
||||
@@ -114,11 +140,18 @@ fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) {
|
||||
static CACHE: crate::graphics::TexCache<HashMap<usize, egui::TextureHandle>> = crate::graphics::TexCache::default();
|
||||
}
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let Some(art) = st.doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return };
|
||||
let doc = match library {
|
||||
Some(id) => match app.session.graph_design_libraries.get(id) {
|
||||
Some(l) => &l.doc,
|
||||
None => return,
|
||||
},
|
||||
None => &st.doc,
|
||||
};
|
||||
let Some(art) = doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return };
|
||||
let key = std::sync::Arc::as_ptr(&art) as usize;
|
||||
let px = (r.width() * ui.ctx().pixels_per_point()).round() as u32;
|
||||
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| {
|
||||
let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(&st.doc, &art, px.max(16), Some([255, 255, 255, 255])))?;
|
||||
let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(doc, &art, px.max(16), Some([255, 255, 255, 255])))?;
|
||||
let color = crate::canvas::color_image(&img);
|
||||
let tex = ui.ctx().load_texture(format!("graph-design-{key}"), color, egui::TextureOptions::LINEAR);
|
||||
CACHE.with(|c| {
|
||||
@@ -177,7 +210,7 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b
|
||||
let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover());
|
||||
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside);
|
||||
if let Some(n) = &one {
|
||||
preview(ui, app, n, r.shrink(4.0));
|
||||
preview(ui, app, None, n, r.shrink(4.0));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
let button =
|
||||
@@ -220,37 +253,66 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b
|
||||
false
|
||||
}
|
||||
|
||||
/// The list of Column and Marker: None, then the designs `names`; a click picks one into `selected` (null for None).
|
||||
fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], salt: &str) {
|
||||
/// The list of Column and Marker: None, the document's designs `names`, then each loaded library's
|
||||
/// name and the designs of it in `libraries` ([`library_designs`]); a click picks one into
|
||||
/// `selected` (null for None) and its library into `library` (null for the document's).
|
||||
fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], libraries: &[(String, String, Vec<String>)], salt: &str) {
|
||||
widgets::list_box(ui, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt(salt).min_scrolled_height(160.0).max_height(160.0).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.set_min_height(160.0);
|
||||
let current = d.fields.get("selected").and_then(Value::as_str).map(str::to_string);
|
||||
let from = library_of(d).map(str::to_string);
|
||||
let pick = |d: &mut Dialog, name: Option<&str>, library: Option<&str>| {
|
||||
d.fields.insert("selected".into(), json!(name));
|
||||
d.fields.insert("library".into(), json!(library));
|
||||
};
|
||||
if ui.selectable_label(current.is_none(), tl!("None")).clicked() {
|
||||
d.fields.insert("selected".into(), Value::Null);
|
||||
pick(d, None, None);
|
||||
}
|
||||
for n in names {
|
||||
if ui.selectable_label(current.as_deref() == Some(n.as_str()), n.as_str()).clicked() {
|
||||
d.fields.insert("selected".into(), json!(n));
|
||||
if ui.selectable_label(from.is_none() && current.as_deref() == Some(n.as_str()), n.as_str()).clicked() {
|
||||
pick(d, Some(n), None);
|
||||
}
|
||||
}
|
||||
for (id, library, designs) in libraries {
|
||||
ui.add_space(4.0);
|
||||
// The library's own name, not interface text.
|
||||
widgets::dim_name(ui, library);
|
||||
for n in designs {
|
||||
let on = from.as_deref() == Some(id.as_str()) && current.as_deref() == Some(n.as_str());
|
||||
if ui.selectable_label(on, n.as_str()).clicked() {
|
||||
pick(d, Some(n), Some(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The design Column or Marker has selected, with its library (`None`: the document's), when the
|
||||
/// document or that library still has it.
|
||||
fn shown_design(d: &Dialog, names: &[String], libraries: &[(String, String, Vec<String>)]) -> Option<(Option<String>, String)> {
|
||||
let n = d.fields.get("selected").and_then(Value::as_str)?;
|
||||
match library_of(d) {
|
||||
None => names.iter().any(|x| x == n).then(|| (None, n.to_string())),
|
||||
Some(id) => libraries.iter().any(|(l, _, designs)| l == id && designs.iter().any(|x| x == n)).then(|| (Some(id.to_string()), n.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn column_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let names = names(app).unwrap_or_default();
|
||||
let libraries = library_designs(app);
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(220.0);
|
||||
one_design_list(ui, d, &names, "graph-columns");
|
||||
one_design_list(ui, d, &names, &libraries, "graph-columns");
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover());
|
||||
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside);
|
||||
if let Some(n) = d.fields.get("selected").and_then(Value::as_str).filter(|n| names.iter().any(|x| x == n)) {
|
||||
preview(ui, app, n, r.shrink(4.0));
|
||||
if let Some((library, n)) = shown_design(d, &names, &libraries) {
|
||||
preview(ui, app, library.as_deref(), &n, r.shrink(4.0));
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
@@ -277,9 +339,10 @@ const EACH_RANGE: std::ops::RangeInclusive<f64> = 0.0001..=1_000_000_000.0;
|
||||
|
||||
fn marker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let names = names(app).unwrap_or_default();
|
||||
let libraries = library_designs(app);
|
||||
// A list as wide as Graph Design's, not the whole window.
|
||||
ui.set_width(220.0);
|
||||
one_design_list(ui, d, &names, "graph-markers");
|
||||
one_design_list(ui, d, &names, &libraries, "graph-markers");
|
||||
false
|
||||
}
|
||||
|
||||
@@ -377,4 +440,33 @@ mod tests {
|
||||
(super::COLUMN_SPEC.confirm)(&mut app, &d).unwrap();
|
||||
assert_eq!(app.session.execute("graph.column", &json!({})).unwrap()["design"], json!(null));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marker_lists_a_loaded_documents_designs_and_ok_copies_the_one_picked_in() {
|
||||
// A document with design "New Design", loaded as a swatch library (Other Library…).
|
||||
let src = app_with_design();
|
||||
let bytes = vectorcraft_format::save_file(&src.session.active().unwrap().doc);
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Dots.vectorcraft"});
|
||||
app.run("swatch.library.load", p).unwrap();
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let g = app.run("graph.create", json!({"type": "line", "x": 100, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [g]})).unwrap();
|
||||
let libraries = super::library_designs(&app);
|
||||
assert_eq!(libraries.len(), 1);
|
||||
let (id, _, designs) = &libraries[0];
|
||||
assert_eq!(designs, &["New Design".to_string()]);
|
||||
crate::menus::invoke(&mut app, "graph.marker", json!({}));
|
||||
frame(&mut app);
|
||||
let mut d: Dialog = app.ui.dialog.take().unwrap();
|
||||
d.fields.insert("selected".into(), json!("New Design"));
|
||||
d.fields.insert("library".into(), json!(id));
|
||||
app.ui.dialog = Some(d.clone());
|
||||
frame(&mut app);
|
||||
(super::MARKER_SPEC.confirm)(&mut app, &d).unwrap();
|
||||
assert_eq!(app.session.execute("graph.marker", &json!({})).unwrap()["design"], "New Design");
|
||||
assert_eq!(super::names(&app).unwrap(), ["New Design"]);
|
||||
// The document has it now, so the library lists it no more.
|
||||
assert!(super::library_designs(&app).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@
|
||||
//! an option or artboard choice the export refuses, or a save panel shown in line that is canceled,
|
||||
//! keeps the dialog open. A canceled save panel keeps the options remembered before. Opened by Export
|
||||
//! Selection, it checks and writes the selection alone. A typed Curve Tolerance is kept within 0.01
|
||||
//! to 10 points.
|
||||
//! to 10 points. OK after another document has become the active one closes the dialog and writes
|
||||
//! nothing.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE};
|
||||
@@ -42,6 +43,9 @@ const SET_ASIDE: &str = "__pens";
|
||||
/// Why Pen Table could not start from the art's pens, shown under the Pens row.
|
||||
const PEN_ERROR: &str = "__penError";
|
||||
|
||||
/// The field that holds the uid of the document the dialog was opened for.
|
||||
const DOC: &str = "__doc";
|
||||
|
||||
/// The Origin menu's names, in [`Origin::ALL`] order.
|
||||
pub(crate) const ORIGIN_NAMES: [&str; 2] = ["Bottom Left", "Center"];
|
||||
|
||||
@@ -71,6 +75,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) {
|
||||
}
|
||||
}
|
||||
fields.insert("format".into(), json!("hpgl"));
|
||||
fields.insert(DOC.into(), json!(app.session.active().map(|st| st.uid)));
|
||||
app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields)));
|
||||
}
|
||||
|
||||
@@ -236,8 +241,13 @@ fn rgb(hex: &str) -> Option<[u8; 3]> {
|
||||
Some([byte(0)?, byte(2)?, byte(4)?])
|
||||
}
|
||||
|
||||
/// Check the options, remember them, and write the file(s).
|
||||
/// Check the options, remember them, and write the file(s). When another document has become the
|
||||
/// active one since the dialog opened, it closes as Cancel does and writes nothing.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) {
|
||||
app.ui.dialog = None;
|
||||
return Ok(json!({}));
|
||||
}
|
||||
let params = super::form::params(d);
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
// A bad option or artboard choice, nothing selected, or no art to export keeps the dialog open.
|
||||
|
||||
@@ -258,6 +258,24 @@ fn pen_table_starts_from_the_pens_of_what_the_export_plots() {
|
||||
assert_eq!(seed(&app), on_board);
|
||||
}
|
||||
|
||||
/// OK after another document has become the active one closes HP-GL Options and writes nothing, so
|
||||
/// the other document is not written to the path chosen for the first.
|
||||
#[test]
|
||||
fn hpgl_options_write_nothing_after_another_document_became_active() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap();
|
||||
app.run("file.new", json!({"width": 60, "height": 40})).unwrap();
|
||||
assert_eq!(kind(&app), Some("hpglOptions"));
|
||||
assert_eq!(confirm(&mut app).unwrap(), json!({}));
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert!(written.borrow().is_empty(), "nothing is written over the first document's path");
|
||||
// Opened for the document that is active, OK writes it.
|
||||
app.run("window.nextDocument", json!({})).unwrap();
|
||||
app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(names(&written), ["/out/first.plt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hpgl_options_dialog_needs_a_document() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
//! Edit → Tracing Presets: every tracing preset in a list (built-in ones in brackets, protected,
|
||||
//! then the saved ones) with the selected one's settings beside it; New… (a preset starting from
|
||||
//! the selected one), Edit… and Delete (saved presets), Import… and Export… (every saved preset)
|
||||
//! under the list. New… and Edit… open the preset editor (kind `tracingPreset`): its OK saves the
|
||||
//! preset with `imageTrace.presets.save` and comes back here on it, and its Cancel comes back with
|
||||
//! nothing saved. An import whose file holds presets with the names of saved ones asks whether to
|
||||
//! replace them (kind `tracingPresetsReplace`); Cancel keeps the saved ones. The saved presets are
|
||||
//! the ones the Image Trace panel, the Control bar and Properties list.
|
||||
//!
|
||||
//! Fields: `selected` (a preset's name). The editor's: `name`, `params` (the tracing settings, as
|
||||
//! `imageTrace.presets.save` takes them) and `editing` (the saved preset it edits; empty for a new
|
||||
//! one). The question's: `names` (the presets the import skipped) and `file` (the file, as
|
||||
//! `imageTrace.presets.import` takes it: `{path}` or `{dataBase64}`). Opening a `.vctracepresets`
|
||||
//! file (File › Open, a drop, the web's Import… pick) imports it the same way.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES;
|
||||
use vectorcraft_engine::cmd::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES};
|
||||
|
||||
use super::{DialogSpec, form};
|
||||
use crate::panels::image_trace::{self, MODES, PALETTES, Preset};
|
||||
use crate::panels::swatches;
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// The dialog kind of Tracing Presets.
|
||||
pub const KIND: &str = "tracingPresets";
|
||||
|
||||
/// The dialog kind of the tracing preset editor.
|
||||
pub const PRESET_KIND: &str = "tracingPreset";
|
||||
|
||||
/// The dialog kind of the question whether an import replaces saved presets of the same names.
|
||||
pub const REPLACE_KIND: &str = "tracingPresetsReplace";
|
||||
|
||||
/// The editor's field naming the saved preset it edits.
|
||||
const EDITING: &str = "editing";
|
||||
|
||||
/// The tallest the tracing settings draw, in the manager and the editor, before they scroll (the
|
||||
/// height of the manager's preset list), so the dialog's buttons stay on short screens.
|
||||
const SETTINGS_HEIGHT: f32 = 300.0;
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Tracing Presets").into(),
|
||||
body,
|
||||
confirm: |app, _| {
|
||||
app.ui.dialog = None;
|
||||
Ok(Value::Null)
|
||||
},
|
||||
ok: None,
|
||||
min_width: 620.0,
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
|
||||
pub(super) const PRESET_SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Save Preset").into(),
|
||||
body: preset_body,
|
||||
confirm: confirm_preset,
|
||||
ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()),
|
||||
min_width: 380.0,
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
|
||||
pub(super) const REPLACE_SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Replace the saved presets that have these names?").into(),
|
||||
body: |_, ui, d| {
|
||||
let names: Vec<&str> = d.fields.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
// A long list scrolls, so Replace and Cancel stay on screen.
|
||||
super::modal::scrolled_rows(ui, "tracing-replace-names", |ui| {
|
||||
ui.label(egui::RichText::new(names.join("\n")).color(Tokens::get(ui.ctx()).text_dim));
|
||||
});
|
||||
false
|
||||
},
|
||||
confirm: confirm_replace,
|
||||
ok: Some("Replace"),
|
||||
max_width: Some(420.0),
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
|
||||
/// Open the presets manager on `selected` (default: the first preset, Default).
|
||||
pub fn open(app: &mut VectorcraftApp, selected: Option<&str>) {
|
||||
app.ui.dialog = Some(Dialog::new(KIND, json!({ "selected": selected.unwrap_or("Default") })));
|
||||
}
|
||||
|
||||
/// The index in `all` of the preset `selected` names, found as the engine finds presets (the first
|
||||
/// when none).
|
||||
fn shown(all: &[Preset], selected: &str) -> usize {
|
||||
image_trace::find_preset(all, selected).and_then(|p| all.iter().position(|q| std::ptr::eq(p, q))).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// A preset's name as the list shows it: a built-in one translated and in brackets, a saved one as
|
||||
/// the user named it.
|
||||
fn list_label(p: &Preset) -> String {
|
||||
if p.3 { format!("[{}]", image_trace::preset_label(&p.0)) } else { p.0.clone() }
|
||||
}
|
||||
|
||||
/// What a button asked for, done once the list and the settings are drawn.
|
||||
enum Action {
|
||||
Select(String),
|
||||
New,
|
||||
Edit,
|
||||
Delete,
|
||||
Import,
|
||||
Export,
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let all = image_trace::presets(app, ui.ctx());
|
||||
let i = shown(&all, &d.str("selected"));
|
||||
let Some(preset) = all.get(i).cloned() else { return false };
|
||||
let builtin = preset.3;
|
||||
let any_saved = all.iter().any(|p| !p.3);
|
||||
let mut act = None;
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(260.0);
|
||||
widgets::dim_label(ui, tl!("Presets:"));
|
||||
widgets::list_box(ui, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("tracing-presets").min_scrolled_height(300.0).max_height(300.0).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.set_min_height(300.0);
|
||||
for (k, p) in all.iter().enumerate() {
|
||||
if ui.selectable_label(k == i, list_label(p)).clicked() {
|
||||
act = Some(Action::Select(p.0.clone()));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
if widgets::flat_button(ui, tl!("New…"), 48.0).on_hover_text(tl!("A new preset starting from the selected one")).clicked() {
|
||||
act = Some(Action::New);
|
||||
}
|
||||
if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Edit…"), 48.0)).inner.clicked() {
|
||||
act = Some(Action::Edit);
|
||||
}
|
||||
if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Delete"), 52.0)).inner.clicked() {
|
||||
act = Some(Action::Delete);
|
||||
}
|
||||
if widgets::flat_button(ui, tl!("Import…"), 60.0).clicked() {
|
||||
act = Some(Action::Import);
|
||||
}
|
||||
if ui.add_enabled_ui(any_saved, |ui| widgets::flat_button(ui, tl!("Export…"), 60.0)).inner.clicked() {
|
||||
act = Some(Action::Export);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(18.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(320.0);
|
||||
ui.label(egui::RichText::new(list_label(&preset)).color(t.text_strong).strong());
|
||||
ui.add_space(8.0);
|
||||
// The selected preset's settings, as the editor shows them, to read only. They scroll
|
||||
// past the height of the preset list.
|
||||
let mut params = preset.1.clone();
|
||||
egui::ScrollArea::vertical().id_salt("tracing-preset-details").max_height(SETTINGS_HEIGHT).show(ui, |ui| {
|
||||
ui.add_enabled_ui(false, |ui| settings_editor(app, ui, "tracing-presets", &mut params));
|
||||
});
|
||||
if builtin {
|
||||
ui.add_space(6.0);
|
||||
ui.label(egui::RichText::new(tl!("Built-in presets don't change: New makes a copy you can edit.")).color(t.text_dim).size(11.5));
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(a) = act {
|
||||
let r = match a {
|
||||
// Their file dialogs, shown off the UI thread, import into or export from the dialog
|
||||
// as it is then.
|
||||
Action::Import | Action::Export => {
|
||||
let export = matches!(a, Action::Export);
|
||||
crate::picks::in_app_dialog(app, d, move |app, d| run(app, d, if export { Action::Export } else { Action::Import }, ""))
|
||||
}
|
||||
a => run(app, d, a, &preset.0),
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn select(d: &mut Dialog, name: &str) {
|
||||
d.fields.insert("selected".into(), json!(name));
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) -> Result<(), String> {
|
||||
match act {
|
||||
Action::Select(name) => select(d, &name),
|
||||
// The editor replaces this dialog; its OK and its Cancel come back here.
|
||||
Action::New => *d = editor(app, d, current, false)?,
|
||||
Action::Edit => *d = editor(app, d, current, true)?,
|
||||
Action::Delete => {
|
||||
let i = app.session.prefs.trace_presets.iter().position(|p| p.name == current);
|
||||
app.run("imageTrace.presets.delete", json!({ "name": current }))?;
|
||||
// The saved preset below it takes its place, else the one above it, else Default.
|
||||
let saved = &app.session.prefs.trace_presets;
|
||||
let next = i.and_then(|i| saved.get(i).or_else(|| i.checked_sub(1).and_then(|k| saved.get(k)))).map(|p| p.name.clone());
|
||||
select(d, next.as_deref().unwrap_or("Default"));
|
||||
}
|
||||
Action::Import => {
|
||||
// On the web the picked file arrives later and imports through `io::open_bytes`.
|
||||
if crate::picks::open_async(app) {
|
||||
return Ok(());
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Tracing presets", TRACE_PRESET_EXTS)], ..Default::default() };
|
||||
let path = crate::picks::open(app, &pick).ok_or("cancelled")?;
|
||||
import(app, d, json!({ "path": path }))?;
|
||||
}
|
||||
Action::Export => {
|
||||
crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Import the tracing presets file `file` (`{path}` or `{dataBase64}`) into the saved presets,
|
||||
/// keeping saved presets of the same names → the presets the file added and the names it skipped.
|
||||
fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec<Value>), String> {
|
||||
let r = crate::io::import_presets(app, "imageTrace.presets.import", "tracing presets", file.clone())?;
|
||||
let skipped = r["skipped"].as_array().cloned().unwrap_or_default();
|
||||
Ok((r["imported"].clone(), skipped))
|
||||
}
|
||||
|
||||
/// The question whether the import of `file` replaces the saved presets `skipped` kept, over the
|
||||
/// dialog `under` (Cancel shows it again).
|
||||
fn ask_replace(under: Option<&Dialog>, skipped: Vec<Value>, file: Value) -> Dialog {
|
||||
let under = under.and_then(|d| serde_json::to_value(d).ok()).unwrap_or(Value::Null);
|
||||
Dialog::new(REPLACE_KIND, json!({ "names": skipped, "file": file, super::PARENT: under }))
|
||||
}
|
||||
|
||||
/// The error for a tracing presets file over the size limit.
|
||||
fn too_big() -> String {
|
||||
format!("the tracing presets file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20)
|
||||
}
|
||||
|
||||
/// The tracing presets file `file` as `{dataBase64}`: a `{path}` is read here, once, so the
|
||||
/// question and its Replace act on the contents the first import checked.
|
||||
fn file_contents(app: &VectorcraftApp, file: Value) -> Result<Value, String> {
|
||||
let Some(path) = file.get("path").and_then(Value::as_str) else { return Ok(file) };
|
||||
vectorcraft_engine::file_access::check_read(path)?;
|
||||
if std::fs::metadata(path).is_ok_and(|m| m.len() > TRACE_PRESET_MAX_BYTES as u64) {
|
||||
return Err(too_big());
|
||||
}
|
||||
// One byte past the limit tells a larger file apart without reading all of it.
|
||||
let bytes = match (&app.services.read_head, &app.services.read) {
|
||||
(Some(read_head), _) => read_head(path, TRACE_PRESET_MAX_BYTES + 1)?,
|
||||
(None, Some(read)) => read(path)?,
|
||||
(None, None) => return Err("no file reader".into()),
|
||||
};
|
||||
if bytes.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(too_big());
|
||||
}
|
||||
Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(&bytes) }))
|
||||
}
|
||||
|
||||
/// Import… on the manager `d`: the import of `file` ([`import_file`]) selects the first preset it
|
||||
/// added, and when it kept saved presets of the file's names, `d` goes under the question whether
|
||||
/// to replace them.
|
||||
fn import(app: &mut VectorcraftApp, d: &mut Dialog, file: Value) -> Result<(), String> {
|
||||
let file = file_contents(app, file)?;
|
||||
let (imported, skipped) = import_file(app, &file)?;
|
||||
if let Some(first) = imported.get(0).and_then(Value::as_str) {
|
||||
select(d, first);
|
||||
}
|
||||
if !skipped.is_empty() {
|
||||
*d = ask_replace(Some(d), skipped, file);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A tracing presets file opened (File › Open, a drop, or the file picked for Import… on the web):
|
||||
/// it imports as Import… does, over the dialog open now (the manager selects the first preset it
|
||||
/// added), and asks whether to replace saved presets of the file's names.
|
||||
pub(crate) fn open_file(app: &mut VectorcraftApp, bytes: &[u8]) -> Result<(), String> {
|
||||
if bytes.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(too_big());
|
||||
}
|
||||
open_import(app, json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }))
|
||||
}
|
||||
|
||||
/// [`open_file`] for the tracing presets file at `path` (File › Open, a drop): the file is read no
|
||||
/// further than one byte past the size limit, as Import… reads it.
|
||||
pub(crate) fn open_path(app: &mut VectorcraftApp, path: &str) -> Result<(), String> {
|
||||
let file = file_contents(app, json!({ "path": path }))?;
|
||||
open_import(app, file)
|
||||
}
|
||||
|
||||
/// The import of an opened tracing presets file `file` (`{dataBase64}`), over the dialog open now.
|
||||
fn open_import(app: &mut VectorcraftApp, file: Value) -> Result<(), String> {
|
||||
let (imported, skipped) = import_file(app, &file)?;
|
||||
let mut under = app.ui.dialog.take();
|
||||
if let (Some(d), Some(first)) = (under.as_mut().filter(|d| d.kind == KIND), imported.get(0).and_then(Value::as_str)) {
|
||||
select(d, first);
|
||||
}
|
||||
app.ui.dialog = if skipped.is_empty() { under } else { Some(ask_replace(under.as_ref(), skipped, file)) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replace (the question's OK): the file imports again, replacing the saved presets of its names,
|
||||
/// and the dialog it was asked over shows again (the manager on the first of them).
|
||||
fn confirm_replace(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let mut p = d.fields.get("file").cloned().filter(Value::is_object).ok_or("no tracing presets file")?;
|
||||
p["replace"] = json!(true);
|
||||
let r = app.run("imageTrace.presets.import", p)?;
|
||||
let mut back = super::parent(d);
|
||||
if let (Some(b), Some(first)) = (back.as_mut().filter(|b| b.kind == KIND), d.fields.get("names").and_then(|n| n.get(0)).and_then(Value::as_str)) {
|
||||
select(b, first);
|
||||
}
|
||||
app.ui.dialog = back;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The preset editor over the manager `d`: on the saved preset `name` (`edit`), else on a new
|
||||
/// preset starting from the preset `name`, under the first free "Tracing Preset N".
|
||||
fn editor(app: &mut VectorcraftApp, d: &Dialog, name: &str, edit: bool) -> Result<Dialog, String> {
|
||||
let (editing, new_name, params) = if edit {
|
||||
let saved = app.session.trace_preset(name).ok_or_else(|| format!("no saved preset named `{name}`"))?;
|
||||
(saved.name.clone(), saved.name.clone(), serde_json::to_value(&saved.params).map_err(|e| e.to_string())?)
|
||||
} else {
|
||||
let params = app.session.execute("imageTrace.presets", &json!({})).map_err(|e| e.to_string())?["presets"]
|
||||
.as_array()
|
||||
.and_then(|all| {
|
||||
let found = |p: &&Value| p["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name));
|
||||
all.iter().find(|p| p["builtIn"] != false && found(p)).or_else(|| all.iter().find(found)).map(|p| p["params"].clone())
|
||||
})
|
||||
.ok_or_else(|| format!("no preset named `{name}`"))?;
|
||||
(String::new(), app.session.new_trace_preset_name(), params)
|
||||
};
|
||||
let under = serde_json::to_value(d).map_err(|e| e.to_string())?;
|
||||
Ok(Dialog::new(PRESET_KIND, json!({ "name": new_name, "params": params, EDITING: editing, super::PARENT: under })))
|
||||
}
|
||||
|
||||
fn preset_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Name:"));
|
||||
form::text(ui, d, "name", 240.0);
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
let mut params = d.fields.get("params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
|
||||
let changed = egui::ScrollArea::vertical()
|
||||
.id_salt("tracing-preset-settings")
|
||||
.max_height(SETTINGS_HEIGHT)
|
||||
.show(ui, |ui| settings_editor(app, ui, "tracing-preset", &mut params))
|
||||
.inner;
|
||||
if changed {
|
||||
d.fields.insert("params".into(), params);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Save Preset (the editor's OK): `imageTrace.presets.save`, then back to the manager on the
|
||||
/// preset. A preset may not take the name of a built-in preset, of Custom or of another saved
|
||||
/// preset: the editor stays open to change it.
|
||||
fn confirm_preset(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let (name, editing) = (d.str("name"), d.str(EDITING));
|
||||
let name = name.trim();
|
||||
let params = d.fields.get("params").cloned().unwrap_or(Value::Null);
|
||||
let p = if editing.is_empty() {
|
||||
if app.session.trace_preset(name).is_some() {
|
||||
return Err(format!("a preset named `{name}` exists"));
|
||||
}
|
||||
// The settings are whole: a new preset starts from none of the saved ones.
|
||||
json!({ "name": name, "preset": "Default", "params": params })
|
||||
} else {
|
||||
json!({ "name": editing, "newName": name, "params": params })
|
||||
};
|
||||
let r = app.run("imageTrace.presets.save", p)?;
|
||||
let mut back = super::parent(d).filter(|p| p.kind == KIND).unwrap_or_else(|| Dialog::new(KIND, json!({})));
|
||||
select(&mut back, r["name"].as_str().unwrap_or_default());
|
||||
app.ui.dialog = Some(back);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The tracing settings `params` as the Image Trace panel shows them (mode, palette, the count or
|
||||
/// threshold, Document Library's library and colors, and the Advanced settings), changed by the user
|
||||
/// → whether they changed.
|
||||
fn settings_editor(app: &VectorcraftApp, ui: &mut egui::Ui, id: &str, params: &mut Value) -> bool {
|
||||
let mut changed = false;
|
||||
let mode = params["mode"].as_str().unwrap_or("blackAndWhite").to_string();
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Mode:"));
|
||||
let label = MODES.iter().find(|m| m.0 == mode).map_or("Black and White", |m| m.1);
|
||||
let labels: Vec<&str> = MODES.iter().map(|m| m.1).collect();
|
||||
if let Some(i) = widgets::dropdown(ui, (id, "mode"), label, &labels, 170.0) {
|
||||
if MODES[i].0 != "color" {
|
||||
params["colorGroup"] = Value::Null;
|
||||
}
|
||||
params["mode"] = json!(MODES[i].0);
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
let palette = params["palette"].as_str().unwrap_or("limited").to_string();
|
||||
if mode == "color" {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Palette:"));
|
||||
let labels = PALETTES.map(image_trace::palette_label);
|
||||
if let Some(p) =
|
||||
widgets::dropdown_names(ui, (id, "palette"), image_trace::palette_label(&palette), &labels, 170.0).and_then(|i| PALETTES.get(i))
|
||||
{
|
||||
if *p != "documentLibrary" {
|
||||
params["colorGroup"] = Value::Null;
|
||||
}
|
||||
params["palette"] = json!(p);
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if palette == "documentLibrary" {
|
||||
let key = params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string();
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Library:"));
|
||||
let label = swatches::library_label(app, &key);
|
||||
if let Some(k) = widgets::combo(ui, (id, "library"), &label, 170.0, |ui| swatches::library_list(app, ui, &key)) {
|
||||
if k != DOCUMENT_SWATCHES {
|
||||
params["colorGroup"] = Value::Null;
|
||||
}
|
||||
params["library"] = json!(k);
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
// The document's swatches: every one, or one color group's (kept by name, so a preset
|
||||
// names a group the open document may not have).
|
||||
if key == DOCUMENT_SWATCHES {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Colors:"));
|
||||
let group = params["colorGroup"].as_str().filter(|g| !g.is_empty()).map(str::to_string);
|
||||
let label = group.clone().unwrap_or_else(|| tl!("All").to_string());
|
||||
if let Some(g) =
|
||||
widgets::combo(ui, (id, "color-group"), &label, 170.0, |ui| image_trace::color_group_list(app, ui, group.as_deref()))
|
||||
{
|
||||
params["colorGroup"] = json!(g);
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let (key, label, range, suffix) = match mode.as_str() {
|
||||
"blackAndWhite" => ("threshold", tl!("Threshold"), 0.0..=255.0, ""),
|
||||
"grayscale" => ("colors", tl!("Grays"), 2.0..=256.0, ""),
|
||||
"logo" => ("colors", tl!("Colors"), 2.0..=10.0, ""),
|
||||
_ if matches!(palette.as_str(), "fullTone" | "automatic") => ("colorDetail", tl!("Colors"), 0.0..=100.0, "%"),
|
||||
_ => ("colors", tl!("Colors"), 2.0..=256.0, ""),
|
||||
};
|
||||
let mut slider = |params: &mut Value, key: &str, label: &str, range: std::ops::RangeInclusive<f64>, suffix: &str, whole: bool| {
|
||||
let mut v = params[key].as_f64().unwrap_or(0.0);
|
||||
if image_trace::slider(ui, label, &mut v, range, suffix).0 {
|
||||
params[key] = if whole { json!(v.round() as u64) } else { json!(v.round()) };
|
||||
changed = true;
|
||||
}
|
||||
};
|
||||
slider(params, key, label, range, suffix, key != "colorDetail");
|
||||
for (key, label, range, suffix) in
|
||||
[("paths", tl!("Paths"), 0.0..=100.0, "%"), ("corners", tl!("Corners"), 0.0..=100.0, "%"), ("noise", tl!("Noise"), 1.0..=100.0, " px")]
|
||||
{
|
||||
slider(params, key, label, range, suffix, key == "noise");
|
||||
}
|
||||
if mode != "logo" {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Method:"));
|
||||
for (m, l) in [("abutting", tl!("Abutting")), ("overlapping", tl!("Overlapping"))] {
|
||||
if ui.selectable_label(params["method"] == m, l).clicked() && params["method"] != m {
|
||||
params["method"] = json!(m);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
// Create: Fills and/or Strokes (one of them stays on), and the widest line stroked.
|
||||
let create = |p: &Value, key: &str| p[key].as_bool().unwrap_or(key == "fills");
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Create:"));
|
||||
for (key, other, label) in [("fills", "strokes", tl!("Fills")), ("strokes", "fills", tl!("Strokes"))] {
|
||||
let on = create(params, key);
|
||||
if widgets::check(ui, label, on, !on || create(params, other)) {
|
||||
params[key] = json!(!on);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut v = params["strokeWidth"].as_f64().unwrap_or(10.0);
|
||||
let strokes = create(params, "strokes");
|
||||
if ui.add_enabled_ui(strokes, |ui| image_trace::slider(ui, tl!("Stroke"), &mut v, 1.0..=100.0, " px")).inner.0 {
|
||||
params["strokeWidth"] = json!(v.round());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
let gradients = mode == "grayscale" || mode == "color";
|
||||
for (key, label, enabled) in [
|
||||
("snapCurvesToLines", tl!("Snap Curves To Lines"), true),
|
||||
("shapes", tl!("Shapes"), true),
|
||||
("autoGrouping", tl!("Auto Grouping"), true),
|
||||
("gradients", tl!("Gradients"), gradients),
|
||||
] {
|
||||
let on = params[key].as_bool().unwrap_or(false);
|
||||
if widgets::check(ui, label, on, enabled) {
|
||||
params[key] = json!(!on);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let on = params["ignoreWhite"].as_bool().unwrap_or(false);
|
||||
if widgets::check(ui, tl!("Ignore Color"), on, true) {
|
||||
params["ignoreWhite"] = json!(!on);
|
||||
changed = true;
|
||||
}
|
||||
if on {
|
||||
let mut rgb = image_trace::ignore_color(params);
|
||||
if ui.color_edit_button_srgb(&mut rgb).changed() {
|
||||
params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,441 @@
|
||||
//! Edit → Tracing Presets: the menu item, New… and Edit… through the preset editor, Delete,
|
||||
//! Import… (with the question about saved presets of the same names) and Export….
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn frame(app: &mut VectorcraftApp) {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
/// Press a manager button on the preset `current`, as the body does.
|
||||
fn press(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), String> {
|
||||
let mut d = app.ui.dialog.take().expect("a dialog is open");
|
||||
let r = run(app, &mut d, act, current);
|
||||
app.ui.dialog = Some(d);
|
||||
frame(app);
|
||||
r
|
||||
}
|
||||
|
||||
/// The texts the dialog paints on a 1200 × 900 window, once it has taken its sizing frame and
|
||||
/// faded in (each frame is a quarter second on).
|
||||
fn frame_texts(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
fn walk(s: &egui::Shape, out: &mut Vec<String>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0));
|
||||
let mut texts = vec![];
|
||||
for k in 0..4 {
|
||||
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
texts.clear();
|
||||
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
fn kind(app: &VectorcraftApp) -> Option<&str> {
|
||||
app.ui.dialog.as_ref().map(|d| d.kind.as_str())
|
||||
}
|
||||
|
||||
fn field(app: &VectorcraftApp, k: &str) -> Value {
|
||||
app.ui.dialog.as_ref().and_then(|d| d.fields.get(k).cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn set(app: &mut VectorcraftApp, k: &str, v: Value) {
|
||||
app.ui.dialog.as_mut().expect("a dialog is open").fields.insert(k.into(), v);
|
||||
}
|
||||
|
||||
/// The tracing settings of the preset `name` as `imageTrace.presets` lists them.
|
||||
fn listed(app: &mut VectorcraftApp, name: &str) -> Value {
|
||||
let all = app.session.execute("imageTrace.presets", &json!({})).unwrap();
|
||||
all["presets"].as_array().unwrap().iter().find(|p| p["name"] == name).map(|p| p["params"].clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn saved_names(app: &VectorcraftApp) -> Vec<&str> {
|
||||
app.session.prefs.trace_presets.iter().map(|p| p.name.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_menu_opens_the_manager_without_a_document() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let entries = crate::menus::menu_entries(&app);
|
||||
let item = entries.iter().find(|e| e.command.as_deref() == Some("ui.tracingPresetsDialog")).expect("Edit → Tracing Presets…");
|
||||
assert!(item.path == ["Edit"] && item.label == "Tracing Presets…" && item.enabled);
|
||||
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Default")));
|
||||
app.run("ui.tracingPresetsDialog", json!({"selected": "[6 Colors]"})).unwrap();
|
||||
frame(&mut app);
|
||||
assert_eq!(field(&app, "selected"), json!("[6 Colors]"));
|
||||
// Built-in presets can't be edited or deleted.
|
||||
assert!(press(&mut app, Action::Edit, "6 Colors").is_err());
|
||||
assert!(press(&mut app, Action::Delete, "6 Colors").is_err());
|
||||
assert!(app.session.prefs.trace_presets.is_empty());
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none(), "Close");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_and_edit_save_through_the_editor_and_cancel_saves_nothing() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let revision = app.session.trace_presets_revision();
|
||||
app.run("ui.tracingPresetsDialog", json!({"selected": "6 Colors"})).unwrap();
|
||||
frame(&mut app);
|
||||
// New… starts from the selected built-in preset; Cancel comes back with nothing saved.
|
||||
press(&mut app, Action::New, "6 Colors").unwrap();
|
||||
assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!("Tracing Preset 1")));
|
||||
let six = listed(&mut app, "6 Colors");
|
||||
assert_eq!(field(&app, "params"), six);
|
||||
set(&mut app, "name", json!("Poster"));
|
||||
super::super::cancel(&mut app);
|
||||
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("6 Colors")), "back to the manager");
|
||||
assert!(app.session.prefs.trace_presets.is_empty());
|
||||
assert_eq!(app.session.trace_presets_revision(), revision);
|
||||
// OK saves the preset with the editor's settings and selects it.
|
||||
press(&mut app, Action::New, "6 Colors").unwrap();
|
||||
set(&mut app, "name", json!(" Poster "));
|
||||
let mut params = field(&app, "params");
|
||||
params["noise"] = json!(40);
|
||||
set(&mut app, "params", params);
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster")));
|
||||
assert_eq!(saved_names(&app), ["Poster"]);
|
||||
let poster = listed(&mut app, "Poster");
|
||||
assert_eq!((poster["noise"].clone(), poster["colors"].clone()), (json!(40), six["colors"].clone()));
|
||||
// The Image Trace panel's list (also the Control bar's and Properties') has it.
|
||||
let ctx = egui::Context::default();
|
||||
let all = crate::panels::image_trace::presets(&mut app, &ctx);
|
||||
assert!(all.iter().any(|p| p.0 == "Poster" && !p.3));
|
||||
// Edit… changes the saved preset; Cancel leaves it as it was.
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::Edit, "Poster").unwrap();
|
||||
assert_eq!((kind(&app), field(&app, "name"), field(&app, "params")), (Some(PRESET_KIND), json!("Poster"), poster.clone()));
|
||||
let mut params = field(&app, "params");
|
||||
params["noise"] = json!(3);
|
||||
set(&mut app, "params", params);
|
||||
super::super::cancel(&mut app);
|
||||
assert_eq!(listed(&mut app, "Poster"), poster);
|
||||
press(&mut app, Action::Edit, "Poster").unwrap();
|
||||
let mut params = field(&app, "params");
|
||||
params["noise"] = json!(3);
|
||||
params["mode"] = json!("grayscale");
|
||||
set(&mut app, "params", params);
|
||||
set(&mut app, "name", json!("Posters"));
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Posters")));
|
||||
assert_eq!(saved_names(&app), ["Posters"]);
|
||||
let edited = listed(&mut app, "Posters");
|
||||
assert_eq!((edited["noise"].clone(), edited["mode"].clone()), (json!(3), json!("grayscale")));
|
||||
// New… from a saved preset starts from its settings.
|
||||
press(&mut app, Action::New, "Posters").unwrap();
|
||||
assert_eq!((field(&app, "name"), field(&app, "params")), (json!("Tracing Preset 1"), edited));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_editor_shows_document_library_s_library_and_colors() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::New, "Default").unwrap();
|
||||
let mut params = field(&app, "params");
|
||||
params["mode"] = json!("color");
|
||||
params["palette"] = json!("documentLibrary");
|
||||
params["colorGroup"] = json!("Brand Colors");
|
||||
set(&mut app, "params", params.clone());
|
||||
let texts = frame_texts(&mut app);
|
||||
for t in ["Library:", "Colors:", "Brand Colors"] {
|
||||
assert!(texts.iter().any(|s| s == t), "{t}: {texts:?}");
|
||||
}
|
||||
// Another library's colors are all its swatches: no Colors menu.
|
||||
params["library"] = json!("lib:Other");
|
||||
params["colorGroup"] = Value::Null;
|
||||
set(&mut app, "params", params.clone());
|
||||
let texts = frame_texts(&mut app);
|
||||
assert!(texts.iter().any(|s| s == "Library:") && !texts.iter().any(|s| s == "Colors:"), "{texts:?}");
|
||||
// Other palettes show neither.
|
||||
params["palette"] = json!("limited");
|
||||
set(&mut app, "params", params);
|
||||
let texts = frame_texts(&mut app);
|
||||
assert!(!texts.iter().any(|s| s == "Library:" || s == "Colors:"), "{texts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_taken_or_protected_name_keeps_the_editor_open() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap();
|
||||
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap();
|
||||
let saved = app.session.prefs.trace_presets.clone();
|
||||
app.run("ui.tracingPresetsDialog", json!({"selected": "Ink"})).unwrap();
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::New, "Ink").unwrap();
|
||||
for name in ["Default", "[6 Colors]", "custom", "poster"] {
|
||||
set(&mut app, "name", json!(name));
|
||||
assert!(super::super::confirm(&mut app).is_err(), "{name}");
|
||||
assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!(name)), "{name}: stays open");
|
||||
}
|
||||
super::super::cancel(&mut app);
|
||||
press(&mut app, Action::Edit, "Ink").unwrap();
|
||||
for name in ["Poster", "Default", "Custom"] {
|
||||
set(&mut app, "name", json!(name));
|
||||
assert!(super::super::confirm(&mut app).is_err(), "{name}");
|
||||
assert_eq!(kind(&app), Some(PRESET_KIND), "{name}: stays open");
|
||||
}
|
||||
assert_eq!(app.session.prefs.trace_presets, saved, "nothing changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_selects_the_next_saved_preset_then_default() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
for name in ["A", "B", "C"] {
|
||||
app.run("imageTrace.presets.save", json!({ "name": name })).unwrap();
|
||||
}
|
||||
app.run("ui.tracingPresetsDialog", json!({"selected": "B"})).unwrap();
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::Delete, "B").unwrap();
|
||||
assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A", "C"], json!("C")));
|
||||
press(&mut app, Action::Delete, "C").unwrap();
|
||||
assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A"], json!("A")));
|
||||
press(&mut app, Action::Delete, "A").unwrap();
|
||||
assert!(app.session.prefs.trace_presets.is_empty());
|
||||
assert_eq!(field(&app, "selected"), json!("Default"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_asks_before_replacing_saved_presets_and_export_writes_every_saved_one() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-tracing-presets-ui-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("mine.vctracepresets").to_string_lossy().to_string();
|
||||
let picked = file.clone();
|
||||
let services = crate::Services {
|
||||
pick_save: Some(Box::new(move |_: &crate::FilePick| Some(picked.clone()))),
|
||||
write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),
|
||||
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = VectorcraftApp::new(Session::new(), services);
|
||||
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap();
|
||||
app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap();
|
||||
app.run("ui.tracingPresetsDialog", json!({"selected": "Default"})).unwrap();
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::Export, "").unwrap();
|
||||
let text = std::fs::read_to_string(&file).unwrap();
|
||||
let written: Value = serde_json::from_str(&text).unwrap();
|
||||
let names: Vec<&str> = written["presets"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect();
|
||||
assert_eq!((written["format"].as_str(), names), (Some(TRACE_PRESET_FORMAT), vec!["Poster", "Ink"]));
|
||||
// Saved presets of the same names stay unless the question's Replace is pressed.
|
||||
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap();
|
||||
app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap();
|
||||
let mut d = app.ui.dialog.take().unwrap();
|
||||
import(&mut app, &mut d, json!({ "path": file })).unwrap();
|
||||
app.ui.dialog = Some(d);
|
||||
frame(&mut app);
|
||||
assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"])));
|
||||
assert_eq!(saved_names(&app), ["Poster", "Ink"], "Ink came in");
|
||||
super::super::cancel(&mut app);
|
||||
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Ink")), "Cancel keeps the saved one");
|
||||
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7);
|
||||
let mut d = app.ui.dialog.take().unwrap();
|
||||
import(&mut app, &mut d, json!({ "path": file })).unwrap();
|
||||
app.ui.dialog = Some(d);
|
||||
// Replace acts on the contents the question was asked about, though the file changed since.
|
||||
let changed =
|
||||
r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Poster", "params": {"noise": 3}}, {"name": "Extra", "params": {}}]}"#;
|
||||
std::fs::write(&file, changed).unwrap();
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
std::fs::write(&file, &text).unwrap();
|
||||
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster")));
|
||||
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40);
|
||||
assert_eq!(saved_names(&app), ["Poster", "Ink"]);
|
||||
// Opening the file imports it, and asks the same question over the manager (also how the web's
|
||||
// picked file arrives).
|
||||
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap();
|
||||
app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap();
|
||||
let bytes = std::fs::read(&file).unwrap();
|
||||
crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap();
|
||||
assert_eq!(saved_names(&app), ["Poster", "Ink"]);
|
||||
assert!(app.ui.status.contains("tracing presets"), "{}", app.ui.status);
|
||||
assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"])));
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster")));
|
||||
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40);
|
||||
// With no dialog open, Cancel keeps the saved preset and leaves no dialog.
|
||||
app.ui.dialog = None;
|
||||
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap();
|
||||
crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap();
|
||||
assert_eq!(kind(&app), Some(REPLACE_KIND));
|
||||
super::super::cancel(&mut app);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_a_fault_changes_nothing() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-tracing-presets-bad-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("bad.vctracepresets");
|
||||
std::fs::write(
|
||||
&file,
|
||||
r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}, {"name": "Default", "params": {}}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
// The file is read no further than one byte past the limit.
|
||||
let read_head = |p: &str, max: usize| {
|
||||
use std::io::Read as _;
|
||||
assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1);
|
||||
let mut bytes = vec![];
|
||||
std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?;
|
||||
Ok(bytes)
|
||||
};
|
||||
let services = crate::Services { read_head: Some(Box::new(read_head)), ..Default::default() };
|
||||
let mut app = VectorcraftApp::new(Session::new(), services);
|
||||
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
let mut d = app.ui.dialog.take().unwrap();
|
||||
let e = import(&mut app, &mut d, json!({ "path": file.to_string_lossy() })).unwrap_err();
|
||||
assert!(e.contains("built-in preset"), "{e}");
|
||||
assert_eq!(d.kind, KIND, "no question");
|
||||
assert!(app.session.prefs.trace_presets.is_empty());
|
||||
app.ui.dialog = Some(d);
|
||||
// An opened file over the size limit is refused before its bytes are encoded for the import.
|
||||
let big = vec![b' '; TRACE_PRESET_MAX_BYTES + 1];
|
||||
let e = open_file(&mut app, &big).unwrap_err();
|
||||
assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}");
|
||||
assert_eq!(kind(&app), Some(KIND), "the manager stays open");
|
||||
let big_file = dir.join("big.vctracepresets");
|
||||
std::fs::write(&big_file, &big).unwrap();
|
||||
let mut d = app.ui.dialog.take().unwrap();
|
||||
let e = import(&mut app, &mut d, json!({ "path": big_file.to_string_lossy() })).unwrap_err();
|
||||
assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}");
|
||||
app.ui.dialog = Some(d);
|
||||
assert!(app.session.prefs.trace_presets.is_empty());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// File › Open reads a tracing presets file no further than one byte past the size limit, and
|
||||
/// refuses a larger one, without the whole-file reader.
|
||||
#[test]
|
||||
fn an_opened_file_is_read_no_further_than_the_limit() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-tracing-presets-open-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let fine = dir.join("fine.vctracepresets");
|
||||
std::fs::write(&fine, r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}]}"#).unwrap();
|
||||
let big = dir.join("big.vctracepresets");
|
||||
std::fs::write(&big, vec![b' '; TRACE_PRESET_MAX_BYTES + 1]).unwrap();
|
||||
let read_head = |p: &str, max: usize| {
|
||||
use std::io::Read as _;
|
||||
assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1);
|
||||
let mut bytes = vec![];
|
||||
std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?;
|
||||
Ok(bytes)
|
||||
};
|
||||
let read = |p: &str| -> Result<Vec<u8>, String> { Err(format!("`{p}` was read in full")) };
|
||||
let services = crate::Services { read_head: Some(Box::new(read_head)), read: Some(Box::new(read)), ..Default::default() };
|
||||
let mut app = VectorcraftApp::new(Session::new(), services);
|
||||
crate::io::open_path(&mut app, &fine.to_string_lossy()).unwrap();
|
||||
assert_eq!(saved_names(&app), ["Fine"]);
|
||||
let e = crate::io::open_path(&mut app, &big.to_string_lossy()).unwrap_err();
|
||||
assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}");
|
||||
assert_eq!(saved_names(&app), ["Fine"]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The question's list of names scrolls, so a long one keeps Replace and Cancel on a small screen.
|
||||
#[test]
|
||||
fn a_long_list_of_names_keeps_replace_on_screen() {
|
||||
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let names: Vec<Value> = (0..200).map(|i| json!(format!("Tracing Preset {i}"))).collect();
|
||||
app.ui.dialog = Some(ask_replace(None, names, json!({ "dataBase64": "" })));
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 600.0));
|
||||
let mut texts = vec![];
|
||||
for k in 0..6 {
|
||||
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| super::super::show(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
texts.clear();
|
||||
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
|
||||
}
|
||||
for button in ["Replace", "Cancel"] {
|
||||
let rect = texts.iter().find(|(t, _)| t == button).map(|(_, r)| *r);
|
||||
assert!(rect.is_some_and(|r| screen.contains_rect(r)), "{button} is drawn on screen: {rect:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The tracing settings scroll past the height of the preset list, in the manager and in the
|
||||
/// editor: a preset with every row shown (Color, Document Library, Ignore Color) makes neither
|
||||
/// dialog taller than a Black and White one does.
|
||||
#[test]
|
||||
fn tall_settings_scroll_instead_of_growing_the_dialog() {
|
||||
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// The height from the dialog's heading to the bottom of its button `button`.
|
||||
fn height(app: &mut VectorcraftApp, heading: &str, button: &str) -> f32 {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 2000.0));
|
||||
let mut texts = vec![];
|
||||
for k in 0..6 {
|
||||
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
texts.clear();
|
||||
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
|
||||
}
|
||||
let at = |t: &str| texts.iter().find(|(s, _)| s == t).map(|(_, r)| *r).unwrap_or_else(|| panic!("{t}: {texts:?}"));
|
||||
at(button).max.y - at(heading).min.y
|
||||
}
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let short = listed(&mut app, "Default");
|
||||
let mut tall = short.clone();
|
||||
tall["mode"] = json!("color");
|
||||
tall["palette"] = json!("documentLibrary");
|
||||
tall["colorGroup"] = json!("Brand Colors");
|
||||
tall["ignoreWhite"] = json!(true);
|
||||
for (name, params) in [("Short", &short), ("Tall", &tall)] {
|
||||
app.run("imageTrace.presets.save", json!({ "name": name, "preset": "Default", "params": params })).unwrap();
|
||||
}
|
||||
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
|
||||
let mut heights = vec![];
|
||||
for name in ["Short", "Tall"] {
|
||||
set(&mut app, "selected", json!(name));
|
||||
let manager = height(&mut app, "Tracing Presets", "Close");
|
||||
press(&mut app, Action::Edit, name).unwrap();
|
||||
assert_eq!(kind(&app), Some(PRESET_KIND));
|
||||
let editor = height(&mut app, "Save Preset", "OK");
|
||||
app.ui.dialog = super::super::parent(app.ui.dialog.as_ref().unwrap());
|
||||
heights.push((manager, editor));
|
||||
}
|
||||
let [(manager, editor), (tall_manager, tall_editor)] = heights[..] else { panic!("{heights:?}") };
|
||||
assert!(tall_manager <= manager + 0.5, "the manager grows from {manager} to {tall_manager}");
|
||||
assert!(tall_editor <= editor + 0.5, "the editor grows from {editor} to {tall_editor}");
|
||||
}
|
||||
@@ -489,6 +489,10 @@ font-technology Variable Променливи
|
||||
Circle Кръг
|
||||
Circle Tool Инструмент Кръг
|
||||
Circle too large Кръгът е твърде голям
|
||||
Show Radii Показване на радиуси
|
||||
Show Diameter Показване на диаметър
|
||||
Anchors at Standard Positions Опорни точки в стандартни позиции
|
||||
Third Point by Dragging Трета точка чрез плъзгане
|
||||
Classic Defaults Класически по подразбиране
|
||||
Clean Up… Почистване…
|
||||
Clear Изчистване
|
||||
@@ -590,6 +594,10 @@ font-technology Variable Променливи
|
||||
Box Channel Канал на квадрата
|
||||
Color box Цветови квадрат
|
||||
Color Wheel Options Опции на цветното колело
|
||||
Show Document Colors Показване на цветовете на документа
|
||||
Document Colors Цветове на документа
|
||||
Selection Colors Цветове на селекцията
|
||||
@plural Used {n} time|Used {n} times Използван {n} път|Използван {n} пъти
|
||||
Show Harmony Показване на хармонията
|
||||
Harmony Rule Правило за хармония
|
||||
Harmony color Цвят от хармонията
|
||||
@@ -1831,6 +1839,10 @@ font-technology Variable Променливи
|
||||
Rename Preset Преименуване на предварителна настройка
|
||||
Save Image Trace Preset Запази предварителна настройка за трасиране на изображения
|
||||
Delete Image Trace Preset Изтриване на предварителна настройка за трасиране на изображения
|
||||
Tracing Presets… Предварителни настройки за трасиране…
|
||||
Import Image Trace Presets Импортиране на предварителни настройки за трасиране на изображения
|
||||
Export Image Trace Presets Експортиране на предварителни настройки за трасиране на изображения
|
||||
Replace the saved presets that have these names? Да се заменят ли запазените предварителни настройки с тези имена?
|
||||
Image Trace Presets Предварителни настройки за трасиране на изображения
|
||||
Image: Изображение:
|
||||
Images: Изображения:
|
||||
@@ -2702,6 +2714,13 @@ font-technology Variable Променливи
|
||||
Pen Tool Инструмент „Перо“
|
||||
Quick Pen Tool Инструмент „Бързо перо“
|
||||
Quick Pen Бързо перо
|
||||
Quick Pen Toolbar Лента на бързото перо
|
||||
Continuous Arc Непрекъсната дъга
|
||||
Sharp Corner Arc Дъга с остър ъгъл
|
||||
Flip Arc Обръщане на дъгата
|
||||
Hide Toolbar Скриване на лентата с инструменти
|
||||
Pin Toolbar Position Закачане на позицията на лентата с инструменти
|
||||
Reset Toolbar Position Нулиране на позицията на лентата с инструменти
|
||||
Pencil Молив
|
||||
Pencil Tool Инструмент „Молив“
|
||||
per slice на отрязък
|
||||
@@ -7911,6 +7930,11 @@ breakText Glyphs Глифи
|
||||
@msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt.
|
||||
@msg Two panels pass through each other. Два панела минават един през друг.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
|
||||
Vector Packs Векторни пакети
|
||||
Compass Rose Роза на компаса
|
||||
Botanical Sprig Ботаническо клонче
|
||||
Facet Diamond Фасетиран ромб
|
||||
Tide Crest Гребен на вълна
|
||||
Leaf Vine Листна лоза
|
||||
Blossom Chain Цветна верига
|
||||
Pennant Garland Гирлянд от знаменца
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -823,6 +823,10 @@
|
||||
Box Channel Kanal kvadrata
|
||||
Color box Kvadrat boje
|
||||
Color Wheel Options Opcije kotača boja
|
||||
Show Document Colors Prikaži boje dokumenta
|
||||
Document Colors Boje dokumenta
|
||||
Selection Colors Boje odabira
|
||||
@plural Used {n} time|Used {n} times Korišteno {n} put|Korišteno {n} puta|Korišteno {n} puta
|
||||
Show Harmony Prikaži harmoniju
|
||||
Harmony Rule Pravilo harmonije
|
||||
Harmony color Boja harmonije
|
||||
@@ -2054,6 +2058,10 @@ digits Malayalam Malajalam
|
||||
Rename Preset Preimenuj unaprijed postavljeno
|
||||
Save Image Trace Preset Sačuvaj unaprijed postavljeno praćenje slike
|
||||
Delete Image Trace Preset Izbriši unaprijed postavljeno praćenje slike
|
||||
Tracing Presets… Predlošci praćenja…
|
||||
Import Image Trace Presets Uvezi predloške praćenja slike
|
||||
Export Image Trace Presets Izvezi predloške praćenja slike
|
||||
Replace the saved presets that have these names? Zamijeniti sačuvane predloške s ovim imenima?
|
||||
Method: Metoda:
|
||||
Pad Produži
|
||||
Repeats Broj ponavljanja
|
||||
@@ -4211,6 +4219,13 @@ theme Appearance Izgled
|
||||
Pen Tool Alat pero
|
||||
Quick Pen Tool Alat brzo pero
|
||||
Quick Pen Brzo pero
|
||||
Quick Pen Toolbar Traka Brzog pera
|
||||
Continuous Arc Neprekidni luk
|
||||
Sharp Corner Arc Luk s oštrim uglom
|
||||
Flip Arc Preokreni luk
|
||||
Hide Toolbar Sakrij traku s alatima
|
||||
Pin Toolbar Position Prikvači položaj trake s alatima
|
||||
Reset Toolbar Position Vrati položaj trake s alatima na početno
|
||||
Picas Pice
|
||||
Portuguese Portugalski
|
||||
Preserve Appearance and Overprints Očuvaj izgled i pretiske
|
||||
@@ -4860,6 +4875,10 @@ font-technology Variable Varijabilni
|
||||
Circle Krug
|
||||
Circle Tool Alat za krug
|
||||
Circle too large Krug je prevelik
|
||||
Show Radii Prikaži poluprečnike
|
||||
Show Diameter Prikaži prečnik
|
||||
Anchors at Standard Positions Sidrene tačke na standardnim položajima
|
||||
Third Point by Dragging Treća tačka povlačenjem
|
||||
Clip to Art Isijeci prema crtežu
|
||||
Colorize Oboji
|
||||
Gamma Gama
|
||||
@@ -7966,6 +7985,11 @@ shape Open Otvoren
|
||||
@msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt.
|
||||
@msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine"
|
||||
Vector Packs Vektorski paketi
|
||||
Compass Rose Ruža kompasa
|
||||
Botanical Sprig Botanička grančica
|
||||
Facet Diamond Fasetirani romb
|
||||
Tide Crest Vrh vala
|
||||
Leaf Vine Lisnata loza
|
||||
Blossom Chain Cvjetni lanac
|
||||
Pennant Garland Girlanda zastavica
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -734,6 +734,10 @@ arrowhead Target Diana
|
||||
Cusp Punta
|
||||
Straight segment Segment recte
|
||||
Circle too large El cercle és massa gran
|
||||
Show Radii Mostra els radis
|
||||
Show Diameter Mostra el diàmetre
|
||||
Anchors at Standard Positions Punts d’ancoratge en posicions estàndard
|
||||
Third Point by Dragging Tercer punt arrossegant
|
||||
Circle (open) Cercle (obert)
|
||||
Classic Clàssic
|
||||
Classic Defaults Valors predeterminats clàssics
|
||||
@@ -891,6 +895,10 @@ arrowhead Target Diana
|
||||
Box Channel Canal del quadre
|
||||
Color box Quadre de color
|
||||
Color Wheel Options Opcions de la roda de colors
|
||||
Show Document Colors Mostra els colors del document
|
||||
Document Colors Colors del document
|
||||
Selection Colors Colors de la selecció
|
||||
@plural Used {n} time|Used {n} times Utilitzat {n} vegada|Utilitzat {n} vegades
|
||||
Show Harmony Mostra l’harmonia
|
||||
Harmony Rule Regla d’harmonia
|
||||
Harmony color Color de l’harmonia
|
||||
@@ -1222,6 +1230,10 @@ arrowhead Target Diana
|
||||
Delete Guide Suprimeix la guia
|
||||
Delete Guides Suprimeix les guies
|
||||
Delete Image Trace Preset Suprimeix el preajust de traçat d’imatge
|
||||
Tracing Presets… Preajustos de traçat…
|
||||
Import Image Trace Presets Importa preajustos de traçat d’imatge
|
||||
Export Image Trace Presets Exporta els preajustos de traçat d’imatge
|
||||
Replace the saved presets that have these names? Voleu substituir els preajustos desats que tenen aquests noms?
|
||||
Delete Layer Suprimeix la capa
|
||||
Delete Library Suprimeix la biblioteca
|
||||
Delete Library Group Suprimeix el grup de biblioteca
|
||||
@@ -3458,6 +3470,13 @@ digits Malayalam Malaiàlam
|
||||
Pen Tool Eina de ploma
|
||||
Quick Pen Tool Eina de ploma ràpida
|
||||
Quick Pen Ploma ràpida
|
||||
Quick Pen Toolbar Barra d’eines de la ploma ràpida
|
||||
Continuous Arc Arc continu
|
||||
Sharp Corner Arc Arc de cantonada aguda
|
||||
Flip Arc Inverteix l’arc
|
||||
Hide Toolbar Amaga la barra d’eines
|
||||
Pin Toolbar Position Fixa la posició de la barra d’eines
|
||||
Reset Toolbar Position Restableix la posició de la barra d’eines
|
||||
Pencil Llapis
|
||||
Pencil Tool Eina de llapis
|
||||
Pentagram Pentagrama
|
||||
@@ -8954,6 +8973,11 @@ breakText Glyphs Glifs
|
||||
@msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt.
|
||||
@msg Two panels pass through each other. Dos panells es travessen l’un a l’altre.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
|
||||
Vector Packs Paquets vectorials
|
||||
Compass Rose Rosa dels vents
|
||||
Botanical Sprig Branqueta botànica
|
||||
Facet Diamond Diamant facetat
|
||||
Tide Crest Cresta de l'onada
|
||||
Leaf Vine Enfiladissa de fulles
|
||||
Blossom Chain Cadena de flors
|
||||
Pennant Garland Garlanda de banderins
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -835,6 +835,10 @@
|
||||
Box Channel Kanál čtverce
|
||||
Color box Barevný čtverec
|
||||
Color Wheel Options Možnosti barevného kola
|
||||
Show Document Colors Zobrazit barvy dokumentu
|
||||
Document Colors Barvy dokumentu
|
||||
Selection Colors Barvy výběru
|
||||
@plural Used {n} time|Used {n} times Použito {n}krát|Použito {n}krát|Použito {n}krát
|
||||
Show Harmony Zobrazit harmonii
|
||||
Harmony Rule Pravidlo harmonie
|
||||
Harmony color Barva harmonie
|
||||
@@ -2126,6 +2130,10 @@ digits Malayalam Malajálamské
|
||||
Rename Preset Přejmenovat přednastavení
|
||||
Save Image Trace Preset Uložit přednastavení vektorizace obrazu
|
||||
Delete Image Trace Preset Odstranit přednastavení vektorizace obrazu
|
||||
Tracing Presets… Přednastavení vektorizace…
|
||||
Import Image Trace Presets Importovat přednastavení vektorizace obrazu
|
||||
Export Image Trace Presets Exportovat přednastavení vektorizace obrazu
|
||||
Replace the saved presets that have these names? Nahradit uložená přednastavení s těmito názvy?
|
||||
Method: Metoda:
|
||||
Pad Prodloužit
|
||||
Repeats Počet opakování
|
||||
@@ -4318,6 +4326,13 @@ theme Appearance Motiv
|
||||
Pen Tool Nástroj Pero
|
||||
Quick Pen Tool Nástroj Rychlé pero
|
||||
Quick Pen Rychlé pero
|
||||
Quick Pen Toolbar Panel nástrojů rychlého pera
|
||||
Continuous Arc Plynulý oblouk
|
||||
Sharp Corner Arc Oblouk s ostrým rohem
|
||||
Flip Arc Překlopit oblouk
|
||||
Hide Toolbar Skrýt panel nástrojů
|
||||
Pin Toolbar Position Připnout polohu panelu nástrojů
|
||||
Reset Toolbar Position Obnovit polohu panelu nástrojů
|
||||
Picas Pica
|
||||
Portuguese Portugalština
|
||||
Preserve Appearance and Overprints Zachovat vzhled a přetisky
|
||||
@@ -4969,6 +4984,10 @@ font-technology Variable Variabilní
|
||||
Cusp Hrot
|
||||
Straight segment Přímý segment
|
||||
Circle too large Kruh je příliš velký
|
||||
Show Radii Zobrazit poloměry
|
||||
Show Diameter Zobrazit průměr
|
||||
Anchors at Standard Positions Kotevní body ve standardních polohách
|
||||
Third Point by Dragging Třetí bod tažením
|
||||
Clip to Art Oříznout podle kresby
|
||||
Colorize Obarvit
|
||||
Gamma Gama
|
||||
@@ -10778,6 +10797,11 @@ breakText Glyphs Glyfy
|
||||
@msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu.
|
||||
@msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings}
|
||||
Vector Packs Vektorové balíčky
|
||||
Compass Rose Směrová růžice
|
||||
Botanical Sprig Botanická větvička
|
||||
Facet Diamond Fazetový diamant
|
||||
Tide Crest Hřeben vlny
|
||||
Leaf Vine Listová liána
|
||||
Blossom Chain Květinový řetěz
|
||||
Pennant Garland Girlanda praporků
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3535,6 +3535,10 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
Box Channel Kvadratets kanal
|
||||
Color box Farvekvadrat
|
||||
Color Wheel Options Indstillinger for farvehjul
|
||||
Show Document Colors Vis dokumentfarver
|
||||
Document Colors Dokumentfarver
|
||||
Selection Colors Markeringens farver
|
||||
@plural Used {n} time|Used {n} times Brugt {n} gang|Brugt {n} gange
|
||||
Show Harmony Vis harmoni
|
||||
Harmony Rule Harmoniregel
|
||||
Harmony color Harmonifarve
|
||||
@@ -4696,6 +4700,10 @@ digits Malayalam Malayalam
|
||||
Rename Preset Omdøb forudindstilling
|
||||
Save Image Trace Preset Gem forudindstilling til billedsporing
|
||||
Delete Image Trace Preset Slet forudindstilling til billedsporing
|
||||
Tracing Presets… Vektoriseringsforudindstillinger…
|
||||
Import Image Trace Presets Importér forudindstillinger til billedsporing
|
||||
Export Image Trace Presets Eksportér forudindstillinger til billedsporing
|
||||
Replace the saved presets that have these names? Vil du erstatte de gemte forudindstillinger med disse navne?
|
||||
Method: Metode:
|
||||
Pad Forlæng
|
||||
Repeats Gentagelser
|
||||
@@ -6775,6 +6783,13 @@ theme Appearance Udseende
|
||||
Pen Tool Pen-værktøj
|
||||
Quick Pen Tool Hurtigpen-værktøj
|
||||
Quick Pen Hurtigpen
|
||||
Quick Pen Toolbar Hurtigpennens værktøjslinje
|
||||
Continuous Arc Fortløbende bue
|
||||
Sharp Corner Arc Bue med skarpt hjørne
|
||||
Flip Arc Vend bue
|
||||
Hide Toolbar Skjul værktøjslinjen
|
||||
Pin Toolbar Position Fastgør værktøjslinjens placering
|
||||
Reset Toolbar Position Nulstil værktøjslinjens placering
|
||||
Picas Pica
|
||||
Portuguese Portugisisk
|
||||
Preserve Appearance and Overprints Bevar udseende og overprint
|
||||
@@ -7415,6 +7430,10 @@ font-technology Variable Variable
|
||||
Cusp Spids
|
||||
Straight segment Lige segment
|
||||
Circle too large Cirklen er for stor
|
||||
Show Radii Vis radier
|
||||
Show Diameter Vis diameter
|
||||
Anchors at Standard Positions Ankerpunkter i standardpositioner
|
||||
Third Point by Dragging Tredje punkt ved træk
|
||||
Clip to Art Beskær til grafik
|
||||
Colorize Farvelæg
|
||||
Gamma Gamma
|
||||
@@ -10840,6 +10859,11 @@ breakText Glyphs Glyffer
|
||||
@msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt.
|
||||
@msg Two panels pass through each other. To paneler går gennem hinanden.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine"
|
||||
Vector Packs Vektorpakker
|
||||
Compass Rose Kompasrose
|
||||
Botanical Sprig Botanisk kvist
|
||||
Facet Diamond Facetteret diamant
|
||||
Tide Crest Bølgetop
|
||||
Leaf Vine Bladranke
|
||||
Blossom Chain Blomsterkæde
|
||||
Pennant Garland Vimpelguirlande
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -484,6 +484,11 @@ font-technology Variable Variabel
|
||||
Cusp Spitze
|
||||
Straight segment Gerades Segment
|
||||
Circle too large Kreis zu groß
|
||||
Show Radii Radien anzeigen
|
||||
Show Diameter Durchmesser anzeigen
|
||||
Anchors at Standard Positions Ankerpunkte an Standardpositionen
|
||||
Third Point by Dragging Dritter Punkt durch Ziehen
|
||||
Gray Grau
|
||||
Classic Defaults Klassische Standardwerte
|
||||
Clean Up… Aufräumen…
|
||||
Clear Löschen
|
||||
@@ -594,6 +599,10 @@ font-technology Variable Variabel
|
||||
Box Channel Kanal des Quadrats
|
||||
Color box Farbquadrat
|
||||
Color Wheel Options Optionen für den Farbkreis
|
||||
Show Document Colors Dokumentfarben einblenden
|
||||
Document Colors Dokumentfarben
|
||||
Selection Colors Farben der Auswahl
|
||||
@plural Used {n} time|Used {n} times {n}-mal verwendet|{n}-mal verwendet
|
||||
Show Harmony Harmonie einblenden
|
||||
Harmony Rule Harmonieregel
|
||||
Harmony color Harmoniefarbe
|
||||
@@ -1908,6 +1917,10 @@ file-filter Templates Vorlagen
|
||||
Rename Preset Vorgabe umbenennen
|
||||
Save Image Trace Preset Bildnachzeichner-Vorgabe speichern
|
||||
Delete Image Trace Preset Bildnachzeichner-Vorgabe löschen
|
||||
Tracing Presets… Nachzeichnervorgaben…
|
||||
Import Image Trace Presets Bildnachzeichner-Vorgaben importieren
|
||||
Export Image Trace Presets Bildnachzeichner-Vorgaben exportieren
|
||||
Replace the saved presets that have these names? Gespeicherte Vorgaben mit diesen Namen ersetzen?
|
||||
Image Trace Presets Bildnachzeichner-Vorgaben
|
||||
Image: Bild:
|
||||
Images: Bilder:
|
||||
@@ -2763,6 +2776,13 @@ file-filter Templates Vorlagen
|
||||
Pen Tool Zeichenstift-Werkzeug
|
||||
Quick Pen Tool Schnellzeichenstift-Werkzeug
|
||||
Quick Pen Schnellzeichenstift
|
||||
Quick Pen Toolbar Schnellzeichenstift-Werkzeugleiste
|
||||
Continuous Arc Fortlaufender Bogen
|
||||
Sharp Corner Arc Bogen mit scharfer Ecke
|
||||
Flip Arc Bogen spiegeln
|
||||
Hide Toolbar Werkzeugleiste ausblenden
|
||||
Pin Toolbar Position Position der Werkzeugleiste fixieren
|
||||
Reset Toolbar Position Position der Werkzeugleiste zurücksetzen
|
||||
Pencil Buntstift
|
||||
Pencil Tool Buntstift-Werkzeug
|
||||
per slice pro Slice
|
||||
@@ -10419,6 +10439,11 @@ breakText Glyphs Glyphen
|
||||
@msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden.
|
||||
@msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings}
|
||||
Vector Packs Vektorpakete
|
||||
Compass Rose Kompassrose
|
||||
Botanical Sprig Botanischer Zweig
|
||||
Facet Diamond Facettierter Diamant
|
||||
Tide Crest Wellenkamm
|
||||
Leaf Vine Blätterranke
|
||||
Blossom Chain Blütenkette
|
||||
Pennant Garland Wimpelgirlande
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -477,6 +477,10 @@ font-technology Variable Μεταβλητές
|
||||
Cusp Ακίδα
|
||||
Straight segment Ευθύ τμήμα
|
||||
Circle too large Ο κύκλος είναι πολύ μεγάλος
|
||||
Show Radii Εμφάνιση ακτίνων
|
||||
Show Diameter Εμφάνιση διαμέτρου
|
||||
Anchors at Standard Positions Σημεία αγκύρωσης σε τυπικές θέσεις
|
||||
Third Point by Dragging Τρίτο σημείο με σύρσιμο
|
||||
Classic Defaults Κλασικές προεπιλογές
|
||||
Clean Up… Εκκαθάριση…
|
||||
Clear Εκκαθάριση
|
||||
@@ -569,6 +573,10 @@ font-technology Variable Μεταβλητές
|
||||
Box Channel Κανάλι τετραγώνου
|
||||
Color box Τετράγωνο χρώματος
|
||||
Color Wheel Options Επιλογές χρωματικού τροχού
|
||||
Show Document Colors Εμφάνιση χρωμάτων εγγράφου
|
||||
Document Colors Χρώματα εγγράφου
|
||||
Selection Colors Χρώματα επιλογής
|
||||
@plural Used {n} time|Used {n} times Χρησιμοποιείται {n} φορά|Χρησιμοποιείται {n} φορές
|
||||
Show Harmony Εμφάνιση αρμονίας
|
||||
Harmony Rule Κανόνας χρωματικής αρμονίας
|
||||
Harmony color Χρώμα αρμονίας
|
||||
@@ -1817,6 +1825,10 @@ font-technology Variable Μεταβλητές
|
||||
Rename Preset Μετονομασία προεπιλογής
|
||||
Save Image Trace Preset Αποθήκευση προεπιλογής ανίχνευσης περιγραμμάτων εικόνας
|
||||
Delete Image Trace Preset Διαγραφή προεπιλογής ανίχνευσης περιγραμμάτων εικόνας
|
||||
Tracing Presets… Προεπιλογές ανίχνευσης περιγραμμάτων…
|
||||
Import Image Trace Presets Εισαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας
|
||||
Export Image Trace Presets Εξαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας
|
||||
Replace the saved presets that have these names? Αντικατάσταση των αποθηκευμένων προεπιλογών με αυτά τα ονόματα;
|
||||
Image Trace Presets Προεπιλογές ανίχνευσης περιγραμμάτων εικόνας
|
||||
Image: Εικόνα:
|
||||
Images: Εικόνες:
|
||||
@@ -2168,6 +2180,13 @@ font-technology Variable Μεταβλητές
|
||||
Pen Tool Πένα (Pen Tool)
|
||||
Quick Pen Tool Εργαλείο γρήγορης πένας
|
||||
Quick Pen Γρήγορη πένα
|
||||
Quick Pen Toolbar Γραμμή εργαλείων γρήγορης πένας
|
||||
Continuous Arc Συνεχές τόξο
|
||||
Sharp Corner Arc Τόξο με αιχμηρή γωνία
|
||||
Flip Arc Αναστροφή τόξου
|
||||
Hide Toolbar Απόκρυψη γραμμής εργαλείων
|
||||
Pin Toolbar Position Σταθεροποίηση θέσης γραμμής εργαλείων
|
||||
Reset Toolbar Position Επαναφορά θέσης γραμμής εργαλείων
|
||||
Pencil Μολύβι
|
||||
Pencil Tool Μολύβι (Pencil Tool)
|
||||
Percent: Ποσοστό:
|
||||
@@ -8927,6 +8946,11 @@ breakText Glyphs Γλύφοι
|
||||
@msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt.
|
||||
@msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine"
|
||||
Vector Packs Διανυσματικά πακέτα
|
||||
Compass Rose Ρόδο πυξίδας
|
||||
Botanical Sprig Βοτανικό κλαδάκι
|
||||
Facet Diamond Πολυεδρικό διαμάντι
|
||||
Tide Crest Κορυφή κύματος
|
||||
Leaf Vine Κληματίδα φύλλων
|
||||
Blossom Chain Αλυσίδα λουλουδιών
|
||||
Pennant Garland Γιρλάντα σημαιών
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -507,6 +507,10 @@ font-technology Variable Variables
|
||||
Cusp Cúspide
|
||||
Straight segment Segmento recto
|
||||
Circle too large Círculo demasiado grande
|
||||
Show Radii Mostrar radios
|
||||
Show Diameter Mostrar diámetro
|
||||
Anchors at Standard Positions Puntos de ancla en posiciones estándar
|
||||
Third Point by Dragging Tercer punto arrastrando
|
||||
Classic Defaults Valores predeterminados clásicos
|
||||
Clean Up… Limpiar…
|
||||
Clear Borrar
|
||||
@@ -614,6 +618,10 @@ font-technology Variable Variables
|
||||
Box Channel Canal del cuadro
|
||||
Color box Cuadro de color
|
||||
Color Wheel Options Opciones de la rueda de color
|
||||
Show Document Colors Mostrar colores del documento
|
||||
Document Colors Colores del documento
|
||||
Selection Colors Colores de la selección
|
||||
@plural Used {n} time|Used {n} times Usado {n} vez|Usado {n} veces
|
||||
Show Harmony Mostrar armonía
|
||||
Harmony Rule Regla de armonía
|
||||
Harmony color Color de la armonía
|
||||
@@ -1909,6 +1917,10 @@ font-technology Variable Variables
|
||||
Rename Preset Cambiar nombre del preajuste
|
||||
Save Image Trace Preset Guardar preajuste de calco de imagen
|
||||
Delete Image Trace Preset Eliminar preajuste de calco de imagen
|
||||
Tracing Presets… Preajustes de calco…
|
||||
Import Image Trace Presets Importar preajustes de calco de imagen
|
||||
Export Image Trace Presets Exportar preajustes de calco de imagen
|
||||
Replace the saved presets that have these names? ¿Reemplazar los preajustes guardados que tienen estos nombres?
|
||||
Image Trace Presets Preajustes de calco de imagen
|
||||
Image: Imagen:
|
||||
Images: Imágenes:
|
||||
@@ -2805,6 +2817,13 @@ font-technology Variable Variables
|
||||
Pen Tool Herramienta Pluma
|
||||
Quick Pen Tool Herramienta Pluma rápida
|
||||
Quick Pen Pluma rápida
|
||||
Quick Pen Toolbar Barra de herramientas de Pluma rápida
|
||||
Continuous Arc Arco continuo
|
||||
Sharp Corner Arc Arco de esquina aguda
|
||||
Flip Arc Voltear arco
|
||||
Hide Toolbar Ocultar barra de herramientas
|
||||
Pin Toolbar Position Fijar posición de la barra de herramientas
|
||||
Reset Toolbar Position Restablecer posición de la barra de herramientas
|
||||
Pencil Lápiz
|
||||
Pencil Tool Herramienta Lápiz
|
||||
per slice por sector
|
||||
@@ -10671,6 +10690,11 @@ breakText Glyphs Glifos
|
||||
@msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt.
|
||||
@msg Two panels pass through each other. Dos paneles se atraviesan entre sí.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
|
||||
Vector Packs Paquetes vectoriales
|
||||
Compass Rose Rosa de los vientos
|
||||
Botanical Sprig Ramita botánica
|
||||
Facet Diamond Diamante facetado
|
||||
Tide Crest Cresta de ola
|
||||
Leaf Vine Enredadera de hojas
|
||||
Blossom Chain Cadena de flores
|
||||
Pennant Garland Guirnalda de banderines
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -821,6 +821,10 @@
|
||||
Box Channel Ruudun kanava
|
||||
Color box Väriruutu
|
||||
Color Wheel Options Väriympyrän asetukset
|
||||
Show Document Colors Näytä asiakirjan värit
|
||||
Document Colors Asiakirjan värit
|
||||
Selection Colors Valinnan värit
|
||||
@plural Used {n} time|Used {n} times Käytetty {n} kerran|Käytetty {n} kertaa
|
||||
Show Harmony Näytä harmonia
|
||||
Harmony Rule Harmoniasääntö
|
||||
Harmony color Harmonian väri
|
||||
@@ -2097,6 +2101,10 @@ digits Malayalam Malajalam
|
||||
Rename Preset Nimeä esiasetus uudelleen
|
||||
Save Image Trace Preset Tallenna kuvan jäljityksen esiasetus
|
||||
Delete Image Trace Preset Poista kuvan jäljityksen esiasetus
|
||||
Tracing Presets… Jäljityksen esiasetukset…
|
||||
Import Image Trace Presets Tuo kuvan jäljityksen esiasetukset
|
||||
Export Image Trace Presets Vie kuvan jäljityksen esiasetukset
|
||||
Replace the saved presets that have these names? Korvataanko tallennetut esiasetukset, joilla on nämä nimet?
|
||||
Method: Menetelmä:
|
||||
Pad Jatka
|
||||
Repeats Toistokerrat
|
||||
@@ -4235,6 +4243,13 @@ theme Appearance Ulkoasu
|
||||
Pen Tool Kynätyökalu
|
||||
Quick Pen Tool Pikakynätyökalu
|
||||
Quick Pen Pikakynä
|
||||
Quick Pen Toolbar Pikakynän työkalurivi
|
||||
Continuous Arc Jatkuva kaari
|
||||
Sharp Corner Arc Terävän kulman kaari
|
||||
Flip Arc Käännä kaari
|
||||
Hide Toolbar Piilota työkalurivi
|
||||
Pin Toolbar Position Kiinnitä työkalurivin sijainti
|
||||
Reset Toolbar Position Palauta työkalurivin sijainti
|
||||
Picas Picat
|
||||
Portuguese Portugali
|
||||
Preserve Appearance and Overprints Säilytä ulkoasu ja päällepainatukset
|
||||
@@ -4879,6 +4894,10 @@ font-technology Variable Muuttuvat
|
||||
Cusp Kärki
|
||||
Straight segment Suora segmentti
|
||||
Circle too large Ympyrä on liian suuri
|
||||
Show Radii Näytä säteet
|
||||
Show Diameter Näytä halkaisija
|
||||
Anchors at Standard Positions Ankkuripisteet vakiokohdissa
|
||||
Third Point by Dragging Kolmas piste vetämällä
|
||||
Clip to Art Rajaa kuvitukseen
|
||||
Colorize Väritä
|
||||
Gamma Gamma
|
||||
@@ -9010,6 +9029,11 @@ breakText Glyphs Merkit
|
||||
@msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt.
|
||||
@msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine"
|
||||
Vector Packs Vektoripaketit
|
||||
Compass Rose Kompassiruusu
|
||||
Botanical Sprig Kasvinoksa
|
||||
Facet Diamond Särmätty timantti
|
||||
Tide Crest Aallonharja
|
||||
Leaf Vine Lehtiköynnös
|
||||
Blossom Chain Kukkaketju
|
||||
Pennant Garland Viiririvistö
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -508,6 +508,10 @@ font-technology Variable Variables
|
||||
Cusp Point de rebroussement
|
||||
Straight segment Segment droit
|
||||
Circle too large Cercle trop grand
|
||||
Show Radii Afficher les rayons
|
||||
Show Diameter Afficher le diamètre
|
||||
Anchors at Standard Positions Points d’ancrage aux positions standard
|
||||
Third Point by Dragging Troisième point par glissement
|
||||
Classic Defaults Valeurs par défaut classiques
|
||||
Clean Up… Nettoyer…
|
||||
Clear Effacer
|
||||
@@ -615,6 +619,10 @@ font-technology Variable Variables
|
||||
Box Channel Couche du carré
|
||||
Color box Carré de couleur
|
||||
Color Wheel Options Options de la roue chromatique
|
||||
Show Document Colors Afficher les couleurs du document
|
||||
Document Colors Couleurs du document
|
||||
Selection Colors Couleurs de la sélection
|
||||
@plural Used {n} time|Used {n} times Utilisée {n} fois|Utilisée {n} fois
|
||||
Show Harmony Afficher l’harmonie
|
||||
Harmony Rule Règle d’harmonie
|
||||
Harmony color Couleur de l’harmonie
|
||||
@@ -1899,6 +1907,10 @@ font-technology Variable Variables
|
||||
Rename Preset Renommer le paramètre prédéfini
|
||||
Save Image Trace Preset Enregistrer le paramètre prédéfini de vectorisation de l’image
|
||||
Delete Image Trace Preset Supprimer le paramètre prédéfini de vectorisation de l’image
|
||||
Tracing Presets… Paramètres prédéfinis de vectorisation…
|
||||
Import Image Trace Presets Importer des paramètres prédéfinis de vectorisation de l’image
|
||||
Export Image Trace Presets Exporter les paramètres prédéfinis de vectorisation de l’image
|
||||
Replace the saved presets that have these names? Remplacer les paramètres prédéfinis enregistrés qui portent ces noms ?
|
||||
Image Trace Presets Paramètres prédéfinis de vectorisation de l’image
|
||||
Image: Image :
|
||||
Images: Images :
|
||||
@@ -2793,6 +2805,13 @@ font-technology Variable Variables
|
||||
Pen Tool Outil Plume
|
||||
Quick Pen Tool Outil Plume rapide
|
||||
Quick Pen Plume rapide
|
||||
Quick Pen Toolbar Barre d’outils Plume rapide
|
||||
Continuous Arc Arc continu
|
||||
Sharp Corner Arc Arc à angle vif
|
||||
Flip Arc Retourner l’arc
|
||||
Hide Toolbar Masquer la barre d’outils
|
||||
Pin Toolbar Position Épingler la position de la barre d’outils
|
||||
Reset Toolbar Position Réinitialiser la position de la barre d’outils
|
||||
Pencil Crayon
|
||||
Pencil Tool Outil Crayon
|
||||
per slice par tranche
|
||||
@@ -10741,6 +10760,11 @@ breakText Glyphs Glyphes
|
||||
@msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt.
|
||||
@msg Two panels pass through each other. Deux panneaux se traversent.
|
||||
@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution
|
||||
Vector Packs Packs vectoriels
|
||||
Compass Rose Rose des vents
|
||||
Botanical Sprig Rameau botanique
|
||||
Facet Diamond Diamant facetté
|
||||
Tide Crest Crête de vague
|
||||
Leaf Vine Liane feuillue
|
||||
Blossom Chain Chaîne de fleurs
|
||||
Pennant Garland Guirlande de fanions
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -606,6 +606,11 @@
|
||||
Circle વર્તુળ
|
||||
Circle Tool વર્તુળ ટૂલ
|
||||
Circle too large વર્તુળ ખૂબ મોટું છે
|
||||
Show Radii ત્રિજ્યાઓ બતાવો
|
||||
Show Diameter વ્યાસ બતાવો
|
||||
Anchors at Standard Positions પ્રમાણભૂત સ્થાનો પર એન્કર બિંદુઓ
|
||||
Third Point by Dragging ખેંચીને ત્રીજું બિંદુ
|
||||
Gray રાખોડી
|
||||
Circle: વર્તુળ:
|
||||
Classic ક્લાસિક
|
||||
Clean Up સાફ કરો
|
||||
@@ -2818,6 +2823,13 @@
|
||||
Pen Tool પેન ટૂલ
|
||||
Quick Pen Tool ક્વિક પેન ટૂલ
|
||||
Quick Pen ક્વિક પેન
|
||||
Quick Pen Toolbar ક્વિક પેન ટૂલબાર
|
||||
Continuous Arc સતત આર્ક
|
||||
Sharp Corner Arc તીક્ષ્ણ ખૂણાવાળો આર્ક
|
||||
Flip Arc આર્ક ફ્લિપ કરો
|
||||
Hide Toolbar ટૂલબાર છુપાવો
|
||||
Pin Toolbar Position ટૂલબાર સ્થિતિ પિન કરો
|
||||
Reset Toolbar Position ટૂલબાર સ્થિતિ રીસેટ કરો
|
||||
Pencil પેન્સિલ
|
||||
Pencil Tool પેન્સિલ ટૂલ
|
||||
Percent: ટકા:
|
||||
@@ -4820,6 +4832,10 @@ arrowhead Feather પીંછું
|
||||
Box Channel બૉક્સ ચેનલ
|
||||
Color box રંગ બૉક્સ
|
||||
Color Wheel Options રંગ વ્હીલ વિકલ્પો
|
||||
Show Document Colors દસ્તાવેજના રંગો બતાવો
|
||||
Document Colors દસ્તાવેજના રંગો
|
||||
Selection Colors પસંદગીના રંગો
|
||||
@plural Used {n} time|Used {n} times {n} વાર વપરાયો|{n} વાર વપરાયો
|
||||
Show Harmony હાર્મની બતાવો
|
||||
Harmony Rule હાર્મની નિયમ
|
||||
Harmony color હાર્મની રંગ
|
||||
@@ -5653,6 +5669,11 @@ swatch [Registration] [રજિસ્ટ્રેશન]
|
||||
Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર
|
||||
Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine"
|
||||
Vector Packs વેક્ટર પૅક
|
||||
Compass Rose દિશાસૂચક ગુલાબ
|
||||
Botanical Sprig વનસ્પતિ ડાળી
|
||||
Facet Diamond પાસાદાર હીરો
|
||||
Tide Crest તરંગ શિખર
|
||||
Leaf Vine પાંદડાની વેલ
|
||||
Blossom Chain ફૂલોની સાંકળ
|
||||
Pennant Garland ધ્વજપટ્ટીની માળા
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -1108,6 +1108,10 @@ arrowhead Feather पंख
|
||||
Cusp नुकीला बिंदु
|
||||
Straight segment सीधा सेगमेंट
|
||||
Circle too large वृत्त बहुत बड़ा है
|
||||
Show Radii त्रिज्याएँ दिखाएँ
|
||||
Show Diameter व्यास दिखाएँ
|
||||
Anchors at Standard Positions मानक स्थानों पर एंकर पॉइंट्स
|
||||
Third Point by Dragging खींचकर तीसरा बिंदु
|
||||
Circle (open) सर्किल (ओपन)
|
||||
Circle: वृत्त:
|
||||
Classic क्लासिक
|
||||
@@ -1277,6 +1281,10 @@ arrowhead Feather पंख
|
||||
Box Channel बॉक्स चैनल
|
||||
Color box कलर बॉक्स
|
||||
Color Wheel Options कलर व्हील ऑप्शन्स
|
||||
Show Document Colors डॉक्यूमेंट के रंग दिखाएँ
|
||||
Document Colors डॉक्यूमेंट के रंग
|
||||
Selection Colors चयन के रंग
|
||||
@plural Used {n} time|Used {n} times {n} बार उपयोग किया गया|{n} बार उपयोग किया गया
|
||||
Show Harmony सद्भाव दिखाएँ
|
||||
Harmony Rule सद्भाव नियम
|
||||
Harmony color सद्भाव रंग
|
||||
@@ -1641,6 +1649,10 @@ arrowhead Feather पंख
|
||||
Delete Guide गाइड हटाएँ
|
||||
Delete Guides गाइड्स हटाएँ
|
||||
Delete Image Trace Preset डिलीट इमेज ट्रेस प्रीसेट
|
||||
Tracing Presets… ट्रेसिंग प्रीसेट…
|
||||
Import Image Trace Presets आयात इमेज ट्रेस प्रीसेट्स
|
||||
Export Image Trace Presets निर्यात इमेज ट्रेस प्रीसेट्स
|
||||
Replace the saved presets that have these names? इन नामों वाले सेव किए गए प्रीसेट बदलें?
|
||||
Delete Instances इंस्टेंस हटाएँ
|
||||
Delete Layer लेयर हटाएँ
|
||||
Delete Library लाइब्रेरी हटाएँ
|
||||
@@ -4005,6 +4017,13 @@ arrowhead Feather पंख
|
||||
Pen Tool पेन टूल
|
||||
Quick Pen Tool क्विक पेन टूल
|
||||
Quick Pen क्विक पेन
|
||||
Quick Pen Toolbar क्विक पेन टूलबार
|
||||
Continuous Arc सतत आर्क
|
||||
Sharp Corner Arc तीखे कोने वाला आर्क
|
||||
Flip Arc आर्क पलटें
|
||||
Hide Toolbar टूलबार छिपाएँ
|
||||
Pin Toolbar Position टूलबार स्थिति पिन करें
|
||||
Reset Toolbar Position टूलबार स्थिति रीसेट करें
|
||||
Pencil पेंसिल
|
||||
Pencil Tool पेंसिल टूल
|
||||
Pentagram पेंटाग्राम
|
||||
@@ -10384,6 +10403,11 @@ theme Appearance अपीयरेंस
|
||||
@msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है।
|
||||
@msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है।
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings}
|
||||
Vector Packs वेक्टर पैक
|
||||
Compass Rose दिशासूचक गुलाब
|
||||
Botanical Sprig वनस्पति टहनी
|
||||
Facet Diamond पहलूदार हीरा
|
||||
Tide Crest लहर की चोटी
|
||||
Leaf Vine पत्तों की बेल
|
||||
Blossom Chain फूलों की शृंखला
|
||||
Pennant Garland झंडियों की माला
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -673,6 +673,10 @@ arrowhead Target Céltábla
|
||||
Cusp Csúcspont
|
||||
Straight segment Egyenes szakasz
|
||||
Circle too large A kör túl nagy
|
||||
Show Radii Sugarak megjelenítése
|
||||
Show Diameter Átmérő megjelenítése
|
||||
Anchors at Standard Positions Horgonypontok szabványos helyeken
|
||||
Third Point by Dragging Harmadik pont húzással
|
||||
Circle (open) Kör (nyitott)
|
||||
Classic Defaults Klasszikus alapértékek
|
||||
Clean Up… Tisztítás…
|
||||
@@ -818,6 +822,10 @@ arrowhead Target Céltábla
|
||||
Box Channel Négyzet csatornája
|
||||
Color box Színnégyzet
|
||||
Color Wheel Options Színkör beállításai
|
||||
Show Document Colors Dokumentumszínek megjelenítése
|
||||
Document Colors Dokumentumszínek
|
||||
Selection Colors A kijelölés színei
|
||||
@plural Used {n} time|Used {n} times {n} alkalommal használva
|
||||
Show Harmony Harmónia megjelenítése
|
||||
Harmony Rule Harmóniaszabály
|
||||
Harmony color Harmóniaszín
|
||||
@@ -3338,6 +3346,13 @@ file-filter Templates Sablonok
|
||||
Pen Tool Toll
|
||||
Quick Pen Tool Gyorstoll
|
||||
Quick Pen Gyorstoll
|
||||
Quick Pen Toolbar Gyorstoll eszköztár
|
||||
Continuous Arc Folytonos ív
|
||||
Sharp Corner Arc Éles sarkú ív
|
||||
Flip Arc Ív tükrözése
|
||||
Hide Toolbar Eszköztár elrejtése
|
||||
Pin Toolbar Position Eszköztár helyének rögzítése
|
||||
Reset Toolbar Position Eszköztár helyének visszaállítása
|
||||
Pencil Ceruza
|
||||
Pencil Tool Ceruza
|
||||
Pentagram Pentagram
|
||||
@@ -5095,6 +5110,10 @@ mark-style Japanese Japán
|
||||
Rename Preset Előbeállítás átnevezése
|
||||
Save Image Trace Preset Képvektorizálási előbeállítás mentése
|
||||
Delete Image Trace Preset Képvektorizálási előbeállítás törlése
|
||||
Tracing Presets… Vektorizálási előbeállítások…
|
||||
Import Image Trace Presets Képvektorizálási előbeállítások importálása
|
||||
Export Image Trace Presets Képvektorizálási előbeállítások exportálása
|
||||
Replace the saved presets that have these names? Lecseréli az ilyen nevű mentett előbeállításokat?
|
||||
Tracing Result Vektorizálás eredménye
|
||||
Tracing Result with Outlines Vektorizálás eredménye vázlattal
|
||||
Tracking Betűköz
|
||||
@@ -10767,6 +10786,11 @@ breakText Glyphs Glifák
|
||||
@msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez.
|
||||
@msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings}
|
||||
Vector Packs Vektorcsomagok
|
||||
Compass Rose Iránytűrózsa
|
||||
Botanical Sprig Növényi ágacska
|
||||
Facet Diamond Csiszolt gyémánt
|
||||
Tide Crest Hullámhegy
|
||||
Leaf Vine Leveles inda
|
||||
Blossom Chain Virágfüzér
|
||||
Pennant Garland Zászlófüzér
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1412,6 +1412,10 @@
|
||||
Box Channel Saluran kotak
|
||||
Color box Kotak warna
|
||||
Color Wheel Options Opsi roda warna
|
||||
Show Document Colors Tampilkan warna dokumen
|
||||
Document Colors Warna dokumen
|
||||
Selection Colors Warna pilihan
|
||||
@plural Used {n} time|Used {n} times Dipakai {n} kali
|
||||
Show Harmony Tampilkan harmoni
|
||||
Harmony Rule Aturan harmoni
|
||||
Harmony color Warna harmoni
|
||||
@@ -2575,6 +2579,10 @@ digits Malayalam Malayalam
|
||||
Rename Preset Ganti nama preset
|
||||
Save Image Trace Preset Simpan preset telusur gambar
|
||||
Delete Image Trace Preset Hapus preset telusur gambar
|
||||
Tracing Presets… Preset penelusuran…
|
||||
Import Image Trace Presets Impor preset telusur gambar
|
||||
Export Image Trace Presets Ekspor preset telusur gambar
|
||||
Replace the saved presets that have these names? Ganti preset tersimpan yang memiliki nama-nama ini?
|
||||
Method: Metode:
|
||||
Pad Perpanjang
|
||||
Repeats Jumlah ulangan
|
||||
@@ -4643,6 +4651,13 @@ theme Appearance Tampilan
|
||||
Pen Tool Alat pena
|
||||
Quick Pen Tool Alat pena cepat
|
||||
Quick Pen Pena cepat
|
||||
Quick Pen Toolbar Bilah alat Pena cepat
|
||||
Continuous Arc Busur bersambung
|
||||
Sharp Corner Arc Busur sudut tajam
|
||||
Flip Arc Balik busur
|
||||
Hide Toolbar Sembunyikan bilah alat
|
||||
Pin Toolbar Position Sematkan posisi bilah alat
|
||||
Reset Toolbar Position Atur ulang posisi bilah alat
|
||||
Picas Pica
|
||||
Portuguese Portugis
|
||||
Preserve Appearance and Overprints Pertahankan tampilan dan overprint
|
||||
@@ -5281,6 +5296,10 @@ font-technology Variable Variabel
|
||||
Circle Lingkaran
|
||||
Circle Tool Alat lingkaran
|
||||
Circle too large Lingkaran terlalu besar
|
||||
Show Radii Tampilkan jari-jari
|
||||
Show Diameter Tampilkan diameter
|
||||
Anchors at Standard Positions Titik jangkar di posisi standar
|
||||
Third Point by Dragging Titik ketiga dengan menyeret
|
||||
Clip to Art Pangkas ke karya seni
|
||||
Colorize Warnai
|
||||
Gamma Gamma
|
||||
@@ -8612,6 +8631,11 @@ breakText Glyphs Glif
|
||||
@msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt.
|
||||
@msg Two panels pass through each other. Dua panel saling menembus.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine"
|
||||
Vector Packs Paket Vektor
|
||||
Compass Rose Mawar Kompas
|
||||
Botanical Sprig Ranting Botani
|
||||
Facet Diamond Berlian Berfaset
|
||||
Tide Crest Puncak Gelombang
|
||||
Leaf Vine Sulur Daun
|
||||
Blossom Chain Rangkaian Bunga
|
||||
Pennant Garland Untaian Panji
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -509,6 +509,11 @@ font-technology Variable Variabili
|
||||
Cusp Cuspide
|
||||
Straight segment Segmento diritto
|
||||
Circle too large Cerchio troppo grande
|
||||
Show Radii Mostra raggi
|
||||
Show Diameter Mostra diametro
|
||||
Anchors at Standard Positions Punti di ancoraggio in posizioni standard
|
||||
Third Point by Dragging Terzo punto trascinando
|
||||
Gray Grigio
|
||||
Classic Defaults Valori predefiniti classici
|
||||
Clean Up… Pulisci…
|
||||
Clear Cancella
|
||||
@@ -616,6 +621,10 @@ font-technology Variable Variabili
|
||||
Box Channel Canale del riquadro
|
||||
Color box Riquadro colore
|
||||
Color Wheel Options Opzioni ruota dei colori
|
||||
Show Document Colors Mostra colori del documento
|
||||
Document Colors Colori del documento
|
||||
Selection Colors Colori della selezione
|
||||
@plural Used {n} time|Used {n} times Usato {n} volta|Usato {n} volte
|
||||
Show Harmony Mostra armonia
|
||||
Harmony Rule Regola di armonia
|
||||
Harmony color Colore dell’armonia
|
||||
@@ -1947,6 +1956,10 @@ file-filter Templates Modelli
|
||||
Rename Preset Rinomina preset
|
||||
Save Image Trace Preset Salva preset ricalco immagine
|
||||
Delete Image Trace Preset Elimina preset ricalco immagine
|
||||
Tracing Presets… Preset di ricalco…
|
||||
Import Image Trace Presets Importa preset ricalco immagine
|
||||
Export Image Trace Presets Esporta preset ricalco immagine
|
||||
Replace the saved presets that have these names? Sostituire i preset salvati con questi nomi?
|
||||
Image Trace Presets Preset ricalco immagine
|
||||
Image: Immagine:
|
||||
Images: Immagini:
|
||||
@@ -2848,6 +2861,13 @@ file-filter Templates Modelli
|
||||
Pen Tool Strumento Penna
|
||||
Quick Pen Tool Strumento Penna rapida
|
||||
Quick Pen Penna rapida
|
||||
Quick Pen Toolbar Barra degli strumenti Penna rapida
|
||||
Continuous Arc Arco continuo
|
||||
Sharp Corner Arc Arco ad angolo vivo
|
||||
Flip Arc Capovolgi arco
|
||||
Hide Toolbar Nascondi barra degli strumenti
|
||||
Pin Toolbar Position Fissa posizione barra degli strumenti
|
||||
Reset Toolbar Position Ripristina posizione barra degli strumenti
|
||||
Pencil Matita
|
||||
Pencil Tool Strumento Matita
|
||||
per slice per sezione
|
||||
@@ -10453,6 +10473,11 @@ breakText Glyphs Glifi
|
||||
@msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura.
|
||||
@msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings}
|
||||
Vector Packs Pacchetti vettoriali
|
||||
Compass Rose Rosa dei venti
|
||||
Botanical Sprig Rametto botanico
|
||||
Facet Diamond Diamante sfaccettato
|
||||
Tide Crest Cresta dell'onda
|
||||
Leaf Vine Tralcio di foglie
|
||||
Blossom Chain Catena di fiori
|
||||
Pennant Garland Ghirlanda di bandierine
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -399,6 +399,10 @@ digits Malayalam マラヤーラム数字
|
||||
Rename Preset プリセット名を変更
|
||||
Save Image Trace Preset 画像トレースプリセットを保存
|
||||
Delete Image Trace Preset 画像トレースプリセットを削除
|
||||
Tracing Presets… トレースプリセット…
|
||||
Import Image Trace Presets 画像トレースプリセットを読み込み
|
||||
Export Image Trace Presets 画像トレースプリセットを書き出し
|
||||
Replace the saved presets that have these names? これらの名前の保存済みプリセットを置き換えますか?
|
||||
Text Wrap テキストの回り込み
|
||||
Text Wrap Options… テキストの回り込みオプション…
|
||||
Clipping Mask クリッピングマスク
|
||||
@@ -872,6 +876,10 @@ digits Malayalam マラヤーラム数字
|
||||
Box Channel ボックスのチャンネル
|
||||
Color box カラーボックス
|
||||
Color Wheel Options カラーホイールオプション
|
||||
Show Document Colors ドキュメントのカラーを表示
|
||||
Document Colors ドキュメントのカラー
|
||||
Selection Colors 選択範囲のカラー
|
||||
@plural Used {n} time|Used {n} times {n} 回使用
|
||||
Show Harmony ハーモニーを表示
|
||||
Harmony Rule ハーモニールール
|
||||
Harmony color ハーモニーカラー
|
||||
@@ -1415,6 +1423,11 @@ antiAlias Sharp シャープ
|
||||
Cusp 尖点
|
||||
Straight segment 直線セグメント
|
||||
Circle too large 円が大きすぎます
|
||||
Show Radii 半径を表示
|
||||
Show Diameter 直径を表示
|
||||
Anchors at Standard Positions アンカーポイントを標準位置に配置
|
||||
Third Point by Dragging 3 点目をドラッグで指定
|
||||
Gray グレー
|
||||
Clear All Tabs すべてのタブを消去
|
||||
Above Text テキストの上
|
||||
Position Panel Above Text テキストの上にパネルを配置
|
||||
@@ -2938,6 +2951,13 @@ antiAlias Sharp シャープ
|
||||
Pen Tool ペンツール
|
||||
Quick Pen Tool クイックペンツール
|
||||
Quick Pen クイックペン
|
||||
Quick Pen Toolbar クイックペンツールバー
|
||||
Continuous Arc 連続円弧
|
||||
Sharp Corner Arc 鋭角円弧
|
||||
Flip Arc 円弧を反転
|
||||
Hide Toolbar ツールバーを隠す
|
||||
Pin Toolbar Position ツールバーの位置を固定
|
||||
Reset Toolbar Position ツールバーの位置をリセット
|
||||
Pencil 鉛筆
|
||||
Pencil Tool 鉛筆ツール
|
||||
Percent: パーセント:
|
||||
@@ -10516,6 +10536,11 @@ breakText Glyphs 字形
|
||||
@msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。
|
||||
@msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings}
|
||||
Vector Packs ベクターパック
|
||||
Compass Rose 羅針盤のバラ
|
||||
Botanical Sprig 植物の小枝
|
||||
Facet Diamond 多面体ダイヤ
|
||||
Tide Crest 波の頂
|
||||
Leaf Vine 葉のつる
|
||||
Blossom Chain 花の連なり
|
||||
Pennant Garland 三角旗のガーランド
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2945,6 +2945,10 @@
|
||||
Box Channel კვადრატის არხი
|
||||
Color box ფერის კვადრატი
|
||||
Color Wheel Options ფერთა წრის პარამეტრები
|
||||
Show Document Colors დოკუმენტის ფერების ჩვენება
|
||||
Document Colors დოკუმენტის ფერები
|
||||
Selection Colors მონიშნულის ფერები
|
||||
@plural Used {n} time|Used {n} times გამოყენებულია {n}-ჯერ
|
||||
Show Harmony ჰარმონიის ჩვენება
|
||||
Harmony Rule ჰარმონიის წესი
|
||||
Harmony color ჰარმონიის ფერი
|
||||
@@ -4077,6 +4081,10 @@ digits Malayalam მალაიალამური
|
||||
Rename Preset პრესეტის სახელის შეცვლა
|
||||
Save Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის შენახვა
|
||||
Delete Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის წაშლა
|
||||
Tracing Presets… ვექტორიზაციის პრესეტები…
|
||||
Import Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტების იმპორტირება
|
||||
Export Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტების ექსპორტირება
|
||||
Replace the saved presets that have these names? ჩავანაცვლოთ ამ სახელების მქონე შენახული პრესეტები?
|
||||
Cancel Image Trace გამოსახულების ვექტორიზაციის გაუქმება
|
||||
Method: მეთოდი:
|
||||
Pad გაგრძელება
|
||||
@@ -6056,6 +6064,13 @@ theme Appearance იერსახე
|
||||
Pen Tool კალმის ხელსაწყო
|
||||
Quick Pen Tool სწრაფი კალმის ხელსაწყო
|
||||
Quick Pen სწრაფი კალამი
|
||||
Quick Pen Toolbar სწრაფი კალმის ხელსაწყოთა ზოლი
|
||||
Continuous Arc უწყვეტი რკალი
|
||||
Sharp Corner Arc მახვილკუთხიანი რკალი
|
||||
Flip Arc რკალის არეკვლა
|
||||
Hide Toolbar ხელსაწყოთა ზოლის დამალვა
|
||||
Pin Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამაგრება
|
||||
Reset Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამოყრა
|
||||
Picas პიკები
|
||||
Portuguese პორტუგალიური
|
||||
Preserve Appearance and Overprints იერსახისა და ზედდაბეჭდვების შენარჩუნება
|
||||
@@ -6671,6 +6686,10 @@ font-technology Variable ცვლადი
|
||||
Cusp წვეტი
|
||||
Straight segment სწორი სეგმენტი
|
||||
Circle too large წრე ზედმეტად დიდია
|
||||
Show Radii რადიუსების ჩვენება
|
||||
Show Diameter დიამეტრის ჩვენება
|
||||
Anchors at Standard Positions საყრდენი წერტილები სტანდარტულ პოზიციებზე
|
||||
Third Point by Dragging მესამე წერტილი გადათრევით
|
||||
Clip to Art ნახატზე მოჭრა
|
||||
Colorize გაფერადება
|
||||
Gamma გამა
|
||||
@@ -11064,6 +11083,11 @@ font-script Japanese იაპონური
|
||||
@msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით.
|
||||
@msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის.
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine"
|
||||
Vector Packs ვექტორული პაკეტები
|
||||
Compass Rose კომპასის ვარდი
|
||||
Botanical Sprig ბოტანიკური ტოტი
|
||||
Facet Diamond წახნაგოვანი ბრილიანტი
|
||||
Tide Crest ტალღის ქედი
|
||||
Leaf Vine ფოთლების ვაზი
|
||||
Blossom Chain ყვავილების ჯაჭვი
|
||||
Pennant Garland ალმების გირლანდა
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -392,6 +392,10 @@ digits Malayalam 말라얄람어
|
||||
Rename Preset 프리셋 이름 바꾸기
|
||||
Save Image Trace Preset 이미지 추적 프리셋 저장
|
||||
Delete Image Trace Preset 이미지 추적 프리셋 삭제
|
||||
Tracing Presets… 추적 프리셋…
|
||||
Import Image Trace Presets 이미지 추적 프리셋 가져오기
|
||||
Export Image Trace Presets 이미지 추적 프리셋 내보내기
|
||||
Replace the saved presets that have these names? 이 이름을 가진 저장된 프리셋을 대체하시겠습니까?
|
||||
Text Wrap 문자 감싸기
|
||||
Text Wrap Options… 문자 감싸기 옵션…
|
||||
Clipping Mask 클리핑 마스크
|
||||
@@ -865,6 +869,10 @@ digits Malayalam 말라얄람어
|
||||
Box Channel 상자 채널
|
||||
Color box 색상 상자
|
||||
Color Wheel Options 색상환 옵션
|
||||
Show Document Colors 문서 색상 표시
|
||||
Document Colors 문서 색상
|
||||
Selection Colors 선택 영역 색상
|
||||
@plural Used {n} time|Used {n} times {n}회 사용
|
||||
Show Harmony 하모니 표시
|
||||
Harmony Rule 하모니 규칙
|
||||
Harmony color 하모니 색상
|
||||
@@ -1405,6 +1413,11 @@ antiAlias Sharp 날카롭게
|
||||
Cusp 뾰족점
|
||||
Straight segment 직선 세그먼트
|
||||
Circle too large 원이 너무 큽니다
|
||||
Show Radii 반지름 표시
|
||||
Show Diameter 지름 표시
|
||||
Anchors at Standard Positions 표준 위치에 앵커 포인트
|
||||
Third Point by Dragging 드래그로 세 번째 점 지정
|
||||
Gray 회색
|
||||
Clear All Tabs 모든 탭 지우기
|
||||
Above Text 문자 위
|
||||
Position Panel Above Text 패널을 문자 위에 배치
|
||||
@@ -2928,6 +2941,13 @@ antiAlias Sharp 날카롭게
|
||||
Pen Tool 펜 도구
|
||||
Quick Pen Tool 빠른 펜 도구
|
||||
Quick Pen 빠른 펜
|
||||
Quick Pen Toolbar 빠른 펜 도구 모음
|
||||
Continuous Arc 연속 호
|
||||
Sharp Corner Arc 뾰족한 모서리 호
|
||||
Flip Arc 호 뒤집기
|
||||
Hide Toolbar 도구 모음 숨기기
|
||||
Pin Toolbar Position 도구 모음 위치 고정
|
||||
Reset Toolbar Position 도구 모음 위치 재설정
|
||||
Pencil 연필
|
||||
Pencil Tool 연필 도구
|
||||
Percent: 퍼센트:
|
||||
@@ -10416,6 +10436,11 @@ breakText Glyphs 글리프
|
||||
@msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다.
|
||||
@msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings}
|
||||
Vector Packs 벡터 팩
|
||||
Compass Rose 나침반 장미
|
||||
Botanical Sprig 식물 가지
|
||||
Facet Diamond 패싯 다이아몬드
|
||||
Tide Crest 파도 마루
|
||||
Leaf Vine 잎 덩굴
|
||||
Blossom Chain 꽃사슬
|
||||
Pennant Garland 깃발 장식
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1401,6 +1401,10 @@ liquify-list-end {0}, {1} {0} en {1}
|
||||
Box Channel Kanaal van het vak
|
||||
Color box Kleurvak
|
||||
Color Wheel Options Opties voor kleurenwiel
|
||||
Show Document Colors Documentkleuren tonen
|
||||
Document Colors Documentkleuren
|
||||
Selection Colors Kleuren van de selectie
|
||||
@plural Used {n} time|Used {n} times {n} keer gebruikt|{n} keer gebruikt
|
||||
Show Harmony Harmonie tonen
|
||||
Harmony Rule Harmonieregel
|
||||
Harmony color Harmoniekleur
|
||||
@@ -2564,6 +2568,10 @@ digits Malayalam Malayalam
|
||||
Rename Preset Voorinstelling hernoemen
|
||||
Save Image Trace Preset Voorinstelling voor afbeeldingtracering opslaan
|
||||
Delete Image Trace Preset Voorinstelling voor afbeeldingtracering verwijderen
|
||||
Tracing Presets… Traceervoorinstellingen…
|
||||
Import Image Trace Presets Voorinstellingen voor afbeeldingtracering importeren
|
||||
Export Image Trace Presets Voorinstellingen voor afbeeldingtracering exporteren
|
||||
Replace the saved presets that have these names? Opgeslagen voorinstellingen met deze namen vervangen?
|
||||
Method: Methode:
|
||||
Pad Doortrekken
|
||||
Repeats Herhalingen
|
||||
@@ -4643,6 +4651,13 @@ theme Appearance Vormgeving
|
||||
Pen Tool Pen-gereedschap
|
||||
Quick Pen Tool Snelpen-gereedschap
|
||||
Quick Pen Snelpen
|
||||
Quick Pen Toolbar Snelpen-werkbalk
|
||||
Continuous Arc Doorlopende boog
|
||||
Sharp Corner Arc Boog met scherpe hoek
|
||||
Flip Arc Boog spiegelen
|
||||
Hide Toolbar Werkbalk verbergen
|
||||
Pin Toolbar Position Werkbalkpositie vastzetten
|
||||
Reset Toolbar Position Werkbalkpositie herstellen
|
||||
Picas Pica's
|
||||
Portuguese Portugees
|
||||
Preserve Appearance and Overprints Vormgeving en overprint behouden
|
||||
@@ -5283,6 +5298,10 @@ font-technology Variable Variabel
|
||||
Cusp Keerpunt
|
||||
Straight segment Recht segment
|
||||
Circle too large Cirkel te groot
|
||||
Show Radii Stralen tonen
|
||||
Show Diameter Diameter tonen
|
||||
Anchors at Standard Positions Ankerpunten op standaardposities
|
||||
Third Point by Dragging Derde punt door slepen
|
||||
Clip to Art Clippen op artwork
|
||||
Colorize Inkleuren
|
||||
Gamma Gamma
|
||||
@@ -10817,6 +10836,11 @@ breakText Glyphs Glyphs
|
||||
@msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden.
|
||||
@msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings}
|
||||
Vector Packs Vectorpakketten
|
||||
Compass Rose Kompasroos
|
||||
Botanical Sprig Botanisch takje
|
||||
Facet Diamond Gefacetteerde diamant
|
||||
Tide Crest Golfkam
|
||||
Leaf Vine Bladrank
|
||||
Blossom Chain Bloemenketting
|
||||
Pennant Garland Vlaggetjesslinger
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -784,6 +784,10 @@
|
||||
Box Channel Kanał kwadratu
|
||||
Color box Kwadrat koloru
|
||||
Color Wheel Options Opcje koła kolorów
|
||||
Show Document Colors Pokaż kolory dokumentu
|
||||
Document Colors Kolory dokumentu
|
||||
Selection Colors Kolory zaznaczenia
|
||||
@plural Used {n} time|Used {n} times Użyty {n} raz|Użyty {n} razy|Użyty {n} razy
|
||||
Show Harmony Pokaż harmonię
|
||||
Harmony Rule Reguła harmonii
|
||||
Harmony color Kolor harmonii
|
||||
@@ -2044,6 +2048,10 @@ digits Malayalam Malajalam
|
||||
Rename Preset Zmień nazwę ustawienia
|
||||
Save Image Trace Preset Zapisz ustawienie obrysu obrazu
|
||||
Delete Image Trace Preset Usuń ustawienie obrysu obrazu
|
||||
Tracing Presets… Ustawienia obrysu…
|
||||
Import Image Trace Presets Importuj ustawienia obrysu obrazu
|
||||
Export Image Trace Presets Eksportuj ustawienia obrysu obrazu
|
||||
Replace the saved presets that have these names? Zastąpić zapisane ustawienia o tych nazwach?
|
||||
Method: Metoda:
|
||||
Pad Przedłuż
|
||||
Repeats Liczba powtórzeń
|
||||
@@ -4183,6 +4191,13 @@ theme Appearance Wygląd
|
||||
Pen Tool Narzędzie Pióro
|
||||
Quick Pen Tool Narzędzie Szybkie pióro
|
||||
Quick Pen Szybkie pióro
|
||||
Quick Pen Toolbar Pasek narzędzi szybkiego pióra
|
||||
Continuous Arc Łuk ciągły
|
||||
Sharp Corner Arc Łuk z ostrym narożnikiem
|
||||
Flip Arc Odwróć łuk
|
||||
Hide Toolbar Ukryj pasek narzędzi
|
||||
Pin Toolbar Position Przypnij położenie paska narzędzi
|
||||
Reset Toolbar Position Resetuj położenie paska narzędzi
|
||||
Picas Pica
|
||||
Portuguese Portugalski
|
||||
Preserve Appearance and Overprints Zachowaj wygląd i nadruki
|
||||
@@ -4813,6 +4828,11 @@ font-technology Variable Zmienne
|
||||
Cusp Ostrze
|
||||
Straight segment Prosty segment
|
||||
Circle too large Okrąg jest za duży
|
||||
Show Radii Pokaż promienie
|
||||
Show Diameter Pokaż średnicę
|
||||
Anchors at Standard Positions Punkty kontrolne w standardowych położeniach
|
||||
Third Point by Dragging Trzeci punkt przez przeciągnięcie
|
||||
Gray Szary
|
||||
Clip to Art Przytnij do kompozycji
|
||||
Colorize Koloruj
|
||||
Gamma Gamma
|
||||
@@ -10642,6 +10662,11 @@ breakText Glyphs Glify
|
||||
@msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania.
|
||||
@msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings}
|
||||
Vector Packs Pakiety wektorowe
|
||||
Compass Rose Róża wiatrów
|
||||
Botanical Sprig Gałązka botaniczna
|
||||
Facet Diamond Fasetowany diament
|
||||
Tide Crest Grzbiet fali
|
||||
Leaf Vine Liściasta winorośl
|
||||
Blossom Chain Łańcuch kwiatów
|
||||
Pennant Garland Girlanda proporczyków
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -474,6 +474,10 @@ antiAlias Sharp Nítido
|
||||
Cusp Cúspide
|
||||
Straight segment Segmento reto
|
||||
Circle too large Círculo grande demais
|
||||
Show Radii Mostrar Raios
|
||||
Show Diameter Mostrar Diâmetro
|
||||
Anchors at Standard Positions Pontos de Ancoragem em Posições Padrão
|
||||
Third Point by Dragging Terceiro Ponto Arrastando
|
||||
Clean Up… Limpar…
|
||||
Clear Limpar
|
||||
Clear All Tabs Limpar Todas as Paradas de Tabulação
|
||||
@@ -553,6 +557,10 @@ antiAlias Sharp Nítido
|
||||
Box Channel Canal da Caixa
|
||||
Color box Caixa de cor
|
||||
Color Wheel Options Opções da Roda de Cores
|
||||
Show Document Colors Mostrar Cores do Documento
|
||||
Document Colors Cores do Documento
|
||||
Selection Colors Cores da Seleção
|
||||
@plural Used {n} time|Used {n} times Usada {n} vez|Usada {n} vezes
|
||||
Show Harmony Mostrar Harmonia
|
||||
Harmony Rule Regra de Harmonia
|
||||
Harmony color Cor da harmonia
|
||||
@@ -2311,6 +2319,13 @@ antiAlias Sharp Nítido
|
||||
Pen Tool Ferramenta Caneta
|
||||
Quick Pen Tool Ferramenta Caneta rápida
|
||||
Quick Pen Caneta rápida
|
||||
Quick Pen Toolbar Barra de Ferramentas da Caneta rápida
|
||||
Continuous Arc Arco Contínuo
|
||||
Sharp Corner Arc Arco de Canto Agudo
|
||||
Flip Arc Virar Arco
|
||||
Hide Toolbar Ocultar Barra de Ferramentas
|
||||
Pin Toolbar Position Fixar Posição da Barra de Ferramentas
|
||||
Reset Toolbar Position Redefinir Posição da Barra de Ferramentas
|
||||
Pencil Lápis
|
||||
Pencil Tool Ferramenta Lápis
|
||||
Percent: Porcentagem:
|
||||
@@ -4111,6 +4126,10 @@ font-technology Variable Variáveis
|
||||
Rename Preset Renomear Predefinido
|
||||
Save Image Trace Preset Salvar Predefinido de Rastreamento de Imagem
|
||||
Delete Image Trace Preset Excluir Predefinido de Rastreamento de Imagem
|
||||
Tracing Presets… Predefinições de vetorização…
|
||||
Import Image Trace Presets Importar Predefinidos de Rastreamento de Imagem
|
||||
Export Image Trace Presets Exportar Predefinidos de Rastreamento de Imagem
|
||||
Replace the saved presets that have these names? Substituir os predefinidos salvos que têm esses nomes?
|
||||
Japanese Japonês
|
||||
Keep a link to an image file instead of only embedding it Manter um link para o arquivo de imagem em vez de apenas incorporá-lo
|
||||
Latin Latim
|
||||
@@ -10850,6 +10869,11 @@ swatch Yellow Green Verde-amarelado
|
||||
@msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco.
|
||||
@msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings}
|
||||
Vector Packs Pacotes vetoriais
|
||||
Compass Rose Rosa dos ventos
|
||||
Botanical Sprig Ramo botânico
|
||||
Facet Diamond Diamante facetado
|
||||
Tide Crest Crista da onda
|
||||
Leaf Vine Trepadeira de folhas
|
||||
Blossom Chain Corrente de flores
|
||||
Pennant Garland Guirlanda de bandeirolas
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -505,6 +505,10 @@ font-technology Variable Вариативные
|
||||
Cusp Точка возврата
|
||||
Straight segment Прямой сегмент
|
||||
Circle too large Круг слишком большой
|
||||
Show Radii Показать радиусы
|
||||
Show Diameter Показать диаметр
|
||||
Anchors at Standard Positions Опорные точки в стандартных позициях
|
||||
Third Point by Dragging Третья точка перетаскиванием
|
||||
Classic Defaults Классические значения по умолчанию
|
||||
Clean Up… Очистить…
|
||||
Clear Очистить
|
||||
@@ -612,6 +616,10 @@ font-technology Variable Вариативные
|
||||
Box Channel Канал квадрата
|
||||
Color box Цветовой квадрат
|
||||
Color Wheel Options Параметры цветового круга
|
||||
Show Document Colors Показать цвета документа
|
||||
Document Colors Цвета документа
|
||||
Selection Colors Цвета выделения
|
||||
@plural Used {n} time|Used {n} times Используется {n} раз|Используется {n} раза|Используется {n} раз
|
||||
Show Harmony Показать гармонию
|
||||
Harmony Rule Правило гармонии
|
||||
Harmony color Цвет гармонии
|
||||
@@ -1933,6 +1941,10 @@ file-filter Templates Шаблоны
|
||||
Rename Preset Переименовать набор
|
||||
Save Image Trace Preset Сохранить набор трассировки изображения
|
||||
Delete Image Trace Preset Удалить набор трассировки изображения
|
||||
Tracing Presets… Наборы трассировки…
|
||||
Import Image Trace Presets Импортировать наборы трассировки изображения
|
||||
Export Image Trace Presets Экспортировать наборы трассировки изображения
|
||||
Replace the saved presets that have these names? Заменить сохранённые наборы с этими именами?
|
||||
Image Trace Presets Наборы трассировки изображения
|
||||
Image: Изображение:
|
||||
Images: Изображения:
|
||||
@@ -2831,6 +2843,13 @@ file-filter Templates Шаблоны
|
||||
Pen Tool Инструмент «Перо»
|
||||
Quick Pen Tool Инструмент «Быстрое перо»
|
||||
Quick Pen Быстрое перо
|
||||
Quick Pen Toolbar Панель быстрого пера
|
||||
Continuous Arc Непрерывная дуга
|
||||
Sharp Corner Arc Дуга с острым углом
|
||||
Flip Arc Отразить дугу
|
||||
Hide Toolbar Скрыть панель инструментов
|
||||
Pin Toolbar Position Закрепить положение панели инструментов
|
||||
Reset Toolbar Position Сбросить положение панели инструментов
|
||||
Pencil Карандаш
|
||||
Pencil Tool Инструмент «Карандаш»
|
||||
per slice на фрагмент
|
||||
@@ -10834,6 +10853,11 @@ shape Open Открытый
|
||||
@msg Two panels pass through each other. Две панели проходят друг сквозь друга.
|
||||
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение
|
||||
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
|
||||
Vector Packs Векторные наборы
|
||||
Compass Rose Роза ветров
|
||||
Botanical Sprig Ботаническая ветвь
|
||||
Facet Diamond Гранёный бриллиант
|
||||
Tide Crest Гребень волны
|
||||
Leaf Vine Лиственная лоза
|
||||
Blossom Chain Цветочная цепочка
|
||||
Pennant Garland Гирлянда флажков
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -496,6 +496,10 @@ font-technology Variable Variabla
|
||||
Cusp Spets
|
||||
Straight segment Rakt segment
|
||||
Circle too large Cirkeln är för stor
|
||||
Show Radii Visa radier
|
||||
Show Diameter Visa diameter
|
||||
Anchors at Standard Positions Ankarpunkter på standardpositioner
|
||||
Third Point by Dragging Tredje punkt genom att dra
|
||||
Classic Defaults Klassiska standardvärden
|
||||
Clean Up… Rensa upp…
|
||||
Clear Rensa
|
||||
@@ -597,6 +601,10 @@ font-technology Variable Variabla
|
||||
Box Channel Rutans kanal
|
||||
Color box Färgruta
|
||||
Color Wheel Options Alternativ för färghjulet
|
||||
Show Document Colors Visa dokumentfärger
|
||||
Document Colors Dokumentfärger
|
||||
Selection Colors Markeringens färger
|
||||
@plural Used {n} time|Used {n} times Används {n} gång|Används {n} gånger
|
||||
Show Harmony Visa harmoni
|
||||
Harmony Rule Harmoniregel
|
||||
Harmony color Harmonifärg
|
||||
@@ -1855,6 +1863,10 @@ font-technology Variable Variabla
|
||||
Rename Preset Byt namn på förinställning
|
||||
Save Image Trace Preset Spara förinställning för bildkalkering
|
||||
Delete Image Trace Preset Radera förinställning för bildkalkering
|
||||
Tracing Presets… Förinställningar för vektorisering…
|
||||
Import Image Trace Presets Importera förinställningar för bildkalkering
|
||||
Export Image Trace Presets Exportera förinställningar för bildkalkering
|
||||
Replace the saved presets that have these names? Ersätta sparade förinställningar med dessa namn?
|
||||
Image Trace Presets Förinställningar för bildkalkering
|
||||
Image: Bild:
|
||||
Images: Bilder:
|
||||
@@ -2726,6 +2738,13 @@ font-technology Variable Variabla
|
||||
Pen Tool Pennverktyg
|
||||
Quick Pen Tool Snabbpennverktyg
|
||||
Quick Pen Snabbpenna
|
||||
Quick Pen Toolbar Snabbpennans verktygsfält
|
||||
Continuous Arc Kontinuerlig båge
|
||||
Sharp Corner Arc Båge med skarpt hörn
|
||||
Flip Arc Vänd båge
|
||||
Hide Toolbar Dölj verktygsfältet
|
||||
Pin Toolbar Position Fäst verktygsfältets position
|
||||
Reset Toolbar Position Återställ verktygsfältets position
|
||||
Pencil Blyertspenna
|
||||
Pencil Tool Blyertsverktyg
|
||||
per slice per skiva
|
||||
@@ -10871,6 +10890,11 @@ digits Hindi Hindi
|
||||
@msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt.
|
||||
@msg Two panels pass through each other. Två paneler går igenom varandra.
|
||||
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen
|
||||
Vector Packs Vektorpaket
|
||||
Compass Rose Kompassros
|
||||
Botanical Sprig Botanisk kvist
|
||||
Facet Diamond Fasetterad diamant
|
||||
Tide Crest Vågkam
|
||||
Leaf Vine Bladranka
|
||||
Blossom Chain Blomkedja
|
||||
Pennant Garland Vimpelgirlang
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -489,6 +489,10 @@ font-technology Variable Değişken
|
||||
Cusp Sivri nokta
|
||||
Straight segment Düz segment
|
||||
Circle too large Daire çok büyük
|
||||
Show Radii Yarıçapları Göster
|
||||
Show Diameter Çapı Göster
|
||||
Anchors at Standard Positions Standart Konumlarda Bağlantı Noktaları
|
||||
Third Point by Dragging Sürükleyerek Üçüncü Nokta
|
||||
Classic Defaults Klasik Varsayılanlar
|
||||
Clean Up… Temizleme…
|
||||
Clear Temizle
|
||||
@@ -595,6 +599,10 @@ font-technology Variable Değişken
|
||||
Box Channel Kutu Kanalı
|
||||
Color box Renk kutusu
|
||||
Color Wheel Options Renk Tekerleği Seçenekleri
|
||||
Show Document Colors Belge Renklerini Göster
|
||||
Document Colors Belge Renkleri
|
||||
Selection Colors Seçim Renkleri
|
||||
@plural Used {n} time|Used {n} times {n} kez kullanıldı
|
||||
Show Harmony Uyumu Göster
|
||||
Harmony Rule Uyum Kuralı
|
||||
Harmony color Uyum rengi
|
||||
@@ -1733,6 +1741,10 @@ font-technology Variable Değişken
|
||||
Rename Preset Ön Ayarı Yeniden Adlandır
|
||||
Save Image Trace Preset Görüntü İzleme Ön Ayarını Kaydet
|
||||
Delete Image Trace Preset Görüntü İzleme Ön Ayarını Sil
|
||||
Tracing Presets… İzleme Ön Ayarları…
|
||||
Import Image Trace Presets Görüntü İzleme Ön Ayarlarını İçe Aktar
|
||||
Export Image Trace Presets Görüntü İzleme Ön Ayarlarını Dışa Aktar
|
||||
Replace the saved presets that have these names? Bu adlara sahip kayıtlı ön ayarlar değiştirilsin mi?
|
||||
Image Trace Presets Görüntü İzleme Ön Ayarları
|
||||
Image: Resim:
|
||||
Images: Görseller:
|
||||
@@ -2575,6 +2587,13 @@ shape Open Açık
|
||||
Pen Tool Kalem Aracı
|
||||
Quick Pen Tool Hızlı Kalem Aracı
|
||||
Quick Pen Hızlı Kalem
|
||||
Quick Pen Toolbar Hızlı Kalem Araç Çubuğu
|
||||
Continuous Arc Sürekli Yay
|
||||
Sharp Corner Arc Keskin Köşeli Yay
|
||||
Flip Arc Yayı Çevir
|
||||
Hide Toolbar Araç Çubuğunu Gizle
|
||||
Pin Toolbar Position Araç Çubuğu Konumunu Sabitle
|
||||
Reset Toolbar Position Araç Çubuğu Konumunu Sıfırla
|
||||
Pencil Kalem
|
||||
Pencil Tool Kurşun Kalem Aracı
|
||||
per slice dilim başına
|
||||
@@ -10736,6 +10755,11 @@ breakText Glyphs Glifler
|
||||
@msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil.
|
||||
@msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings}
|
||||
Vector Packs Vektör Paketleri
|
||||
Compass Rose Pusula Gülü
|
||||
Botanical Sprig Botanik Dal
|
||||
Facet Diamond Fasetli Elmas
|
||||
Tide Crest Dalga Tepesi
|
||||
Leaf Vine Yapraklı sarmaşık
|
||||
Blossom Chain Çiçek zinciri
|
||||
Pennant Garland Bayrak süsü
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -503,6 +503,11 @@ font-technology Variable Варіативні
|
||||
Cusp Точка звороту
|
||||
Straight segment Прямий сегмент
|
||||
Circle too large Коло завелике
|
||||
Show Radii Показати радіуси
|
||||
Show Diameter Показати діаметр
|
||||
Anchors at Standard Positions Опорні точки в стандартних позиціях
|
||||
Third Point by Dragging Третя точка перетягуванням
|
||||
Gray Сірий
|
||||
Classic Defaults Класичні значення за промовчанням
|
||||
Clean Up… Очистити…
|
||||
Clear Очистити
|
||||
@@ -610,6 +615,10 @@ font-technology Variable Варіативні
|
||||
Box Channel Канал квадрата
|
||||
Color box Колірний квадрат
|
||||
Color Wheel Options Параметри колірного кола
|
||||
Show Document Colors Показати кольори документа
|
||||
Document Colors Кольори документа
|
||||
Selection Colors Кольори виділення
|
||||
@plural Used {n} time|Used {n} times Використано {n} раз|Використано {n} рази|Використано {n} разів
|
||||
Show Harmony Показати гармонію
|
||||
Harmony Rule Правило гармонії
|
||||
Harmony color Колір гармонії
|
||||
@@ -1941,6 +1950,10 @@ file-filter Templates Шаблони
|
||||
Rename Preset Перейменувати набір
|
||||
Save Image Trace Preset Зберегти набір трасування зображення
|
||||
Delete Image Trace Preset Видалити набір трасування зображення
|
||||
Tracing Presets… Набори трасування…
|
||||
Import Image Trace Presets Імпортувати набори трасування зображення
|
||||
Export Image Trace Presets Експортувати набори трасування зображення
|
||||
Replace the saved presets that have these names? Замінити збережені набори з цими назвами?
|
||||
Image Trace Presets Набір трасування зображення
|
||||
Image: Зображення:
|
||||
Images: Зображення:
|
||||
@@ -2840,6 +2853,13 @@ file-filter Templates Шаблони
|
||||
Pen Tool Інструмент «Перо»
|
||||
Quick Pen Tool Інструмент «Швидке перо»
|
||||
Quick Pen Швидке перо
|
||||
Quick Pen Toolbar Панель швидкого пера
|
||||
Continuous Arc Неперервна дуга
|
||||
Sharp Corner Arc Дуга з гострим кутом
|
||||
Flip Arc Відобразити дугу
|
||||
Hide Toolbar Сховати панель інструментів
|
||||
Pin Toolbar Position Закріпити положення панелі інструментів
|
||||
Reset Toolbar Position Скинути положення панелі інструментів
|
||||
Pencil Олівець
|
||||
Pencil Tool Інструмент «Олівець»
|
||||
per slice на фрагмент
|
||||
@@ -10429,6 +10449,11 @@ breakText Glyphs Гліфи
|
||||
@msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки.
|
||||
@msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується.
|
||||
@msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings}
|
||||
Vector Packs Векторні набори
|
||||
Compass Rose Роза вітрів
|
||||
Botanical Sprig Ботанічна гілочка
|
||||
Facet Diamond Гранований діамант
|
||||
Tide Crest Гребінь хвилі
|
||||
Leaf Vine Листяна лоза
|
||||
Blossom Chain Квітковий ланцюжок
|
||||
Pennant Garland Гірлянда прапорців
|
||||
|
||||
|
Can't render this file because it is too large.
|
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user