mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 17:15:56 +00:00
Merge main into #8336
# Conflicts: # crates/ui-egui/src/i18n/bg.tsv # crates/ui-egui/src/i18n/bs.tsv # crates/ui-egui/src/i18n/ca.tsv # crates/ui-egui/src/i18n/cs.tsv # crates/ui-egui/src/i18n/da.tsv # crates/ui-egui/src/i18n/de.tsv # crates/ui-egui/src/i18n/el.tsv # crates/ui-egui/src/i18n/es.tsv # crates/ui-egui/src/i18n/fi.tsv # crates/ui-egui/src/i18n/fr.tsv # crates/ui-egui/src/i18n/gu.tsv # crates/ui-egui/src/i18n/hi.tsv # crates/ui-egui/src/i18n/hu.tsv # crates/ui-egui/src/i18n/id.tsv # crates/ui-egui/src/i18n/it.tsv # crates/ui-egui/src/i18n/ja.tsv # crates/ui-egui/src/i18n/ka.tsv # crates/ui-egui/src/i18n/ko.tsv # crates/ui-egui/src/i18n/nl.tsv # crates/ui-egui/src/i18n/pl.tsv # crates/ui-egui/src/i18n/pt-br.tsv # crates/ui-egui/src/i18n/ru.tsv # crates/ui-egui/src/i18n/sv.tsv # crates/ui-egui/src/i18n/tests.rs # crates/ui-egui/src/i18n/tr.tsv # crates/ui-egui/src/i18n/uk.tsv # crates/ui-egui/src/i18n/vi.tsv # crates/ui-egui/src/i18n/zh-hans.tsv # crates/ui-egui/src/i18n/zh-hant.tsv
This commit is contained in:
@@ -8,6 +8,7 @@ pub mod arrowheads;
|
||||
mod artboardalign;
|
||||
mod assets;
|
||||
mod attributes;
|
||||
pub mod bevels;
|
||||
pub mod brushlib;
|
||||
mod brushsym;
|
||||
mod buildcmds;
|
||||
@@ -321,6 +322,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(draw2::specs());
|
||||
v.extend(xform::specs());
|
||||
v.extend(effectcmd::specs());
|
||||
v.extend(bevels::specs());
|
||||
v.extend(wireframe::specs());
|
||||
v.extend(pathops::specs());
|
||||
v.extend(compoundshape::specs());
|
||||
@@ -890,6 +892,9 @@ pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
/// The Pathfinder Options a new Pathfinder effect takes (`effect.apply`).
|
||||
pub use effectcmd::pathfinder_effect_options;
|
||||
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps.
|
||||
pub use attributes::RECENT_URLS;
|
||||
pub use overprint::AttributesInfo;
|
||||
|
||||
@@ -109,11 +109,11 @@ impl<'a> Reader<'a> {
|
||||
Ok(union(parts))
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let (w, h) = (f64::from(im.width), f64::from(im.height));
|
||||
let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| im.xf * p);
|
||||
self.polygon(&corners)
|
||||
}
|
||||
// A distorted image's frame joins its corners.
|
||||
NodeKind::Image(_) => match n.image_corners() {
|
||||
Some(corners) => self.polygon(&corners),
|
||||
None => Ok(None),
|
||||
},
|
||||
// An instance of a symbol the document doesn't have draws nothing.
|
||||
NodeKind::SymbolInstance { .. } => match vectorcraft_render::effects::outline_object(Some(self.doc), n) {
|
||||
Some(art) => self.node(&art, depth + 1),
|
||||
|
||||
@@ -663,6 +663,29 @@ fn an_image_is_measured_by_its_frame_as_turned() {
|
||||
assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_distorted_image_is_measured_by_the_frame_through_its_corners() {
|
||||
let mut s = session();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "image".into(),
|
||||
width: 100,
|
||||
height: 100,
|
||||
xf: Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
insert(&mut s, |id| {
|
||||
let mut n = Node::new(id, NodeKind::Image(Box::new(im)));
|
||||
n.set_image_corners([Point::new(40.0, 0.0), Point::new(60.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]).unwrap();
|
||||
n
|
||||
});
|
||||
let (b, end) = diamond_weeding(&mut s);
|
||||
assert!((b.x0 + 10.0).abs() < 1e-3 && (b.y1 - 110.0).abs() < 1e-3, "{b:?}");
|
||||
// A quarter of the box down (y = 20), the line meets the side from (40, 0) to (0, 100).
|
||||
assert!((end - 32.0).abs() < 0.01, "{end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_file_is_measured_by_the_art_it_shows() {
|
||||
let dir = crate::tests_links::Folder::new("weed-placed");
|
||||
|
||||
@@ -378,13 +378,14 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn same_file(a: &str, b: &str) -> bool {
|
||||
pub(super) fn same_file(a: &str, b: &str) -> bool {
|
||||
let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p));
|
||||
std::path::Path::new(a) == std::path::Path::new(b) || canon(a) == canon(b)
|
||||
}
|
||||
|
||||
/// The document in the arrowheads file at `path`; `None` when there is no file.
|
||||
fn read(path: &str) -> std::result::Result<Option<Document>, String> {
|
||||
/// The document in the arrowheads file at `path` (or another such file of the user's, as the
|
||||
/// bevels file); `None` when there is no file.
|
||||
pub(super) fn read(path: &str) -> std::result::Result<Option<Document>, String> {
|
||||
let size = match std::fs::metadata(path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(format!("{path}: {e}")),
|
||||
@@ -412,13 +413,13 @@ fn skipped(s: &Session) -> Vec<Value> {
|
||||
/// The arrowheads file at `path` checked for reading against the automation roots in force: an agent
|
||||
/// confined to read roots reaches the file only inside them. The error names the file by its file
|
||||
/// name outside them.
|
||||
fn may_reach(path: &str) -> Result<()> {
|
||||
pub(super) fn may_reach(path: &str) -> Result<()> {
|
||||
crate::file_access::check_read(path).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), path))
|
||||
}
|
||||
|
||||
/// `msg`, an error about the arrowheads file at `path`, as the request being served may see it: the
|
||||
/// file named whole inside the read roots, else by its file name.
|
||||
fn shown_error(msg: &str, path: Option<&str>) -> String {
|
||||
pub(super) fn shown_error(msg: &str, path: Option<&str>) -> String {
|
||||
let Some(path) = path else { return msg.to_string() };
|
||||
match super::fileio::naming_in_error(EngineError::Other(msg.to_string()), path) {
|
||||
EngineError::Other(m) => m,
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! Custom bevels for Extrude & Bevel and Extrude & Bevel (Classic). The bevels file is a native
|
||||
//! document kept next to the preferences ([`Session::attach_bevels_file`]). Each of its symbols
|
||||
//! whose art is one open path is one bevel, listed by the symbol's name after the built-in shapes
|
||||
//! in the Bevel Shape menus. The path runs from its first anchor, at the cap's edge, to its last,
|
||||
//! at the side wall: across the page is across the bevel's width and down the page is along its
|
||||
//! height, whichever way the path is drawn, and points past its ends are held to them. Curves are
|
||||
//! cut into straight lines, at most [`BevelProfile::MAX_POINTS`] points in all. Saving the file
|
||||
//! reloads the bevels. An effect that uses a custom bevel carries a copy of its points
|
||||
//! (`bevelProfile`), so its document draws it anywhere.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol};
|
||||
use vectorcraft_geom::{Affine, PathData, PathEl, Point, SubPath};
|
||||
use vectorcraft_render::effects::{BEVEL_NAME, BEVEL_PROFILE, BevelProfile};
|
||||
|
||||
use super::arrowheads::{may_reach, read, same_file, shown_error};
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd};
|
||||
|
||||
/// The bevels file's name, in the folder of the preferences.
|
||||
pub const FILE_NAME: &str = "Bevels.vectorcraft";
|
||||
/// The most bevels read from the file; symbols past it are skipped.
|
||||
pub const MAX_BEVELS: usize = 256;
|
||||
/// The most anchors a bevel's path may have; a symbol past it is skipped.
|
||||
pub const MAX_ANCHORS: usize = 4096;
|
||||
/// The most points a bevel's path is cut into before it is simplified; a symbol past it is skipped.
|
||||
pub const MAX_LINE_POINTS: usize = 8192;
|
||||
/// The most point-to-line distances simplifying the bevels of one file may measure; a symbol that
|
||||
/// needs more than is left is skipped as too detailed.
|
||||
pub const MAX_SIMPLIFY_WORK: u64 = 40_000_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "threeD.bevels.list",
|
||||
"Bevels",
|
||||
[],
|
||||
None,
|
||||
"{} → {bevels: [{name (effect.apply and effect.setParams take Extrude & Bevel's and Extrude & Bevel (Classic)'s `bevel` as {custom: name}), points: [[x, y]…] (shares of the bevel's width and height from the cap's edge [0, 0] to the side wall [1, 1])}], file: the bevels file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not bevels, error: why the file could not be read, or null} the custom bevels, listed after the built-in shapes in the Bevel Shape menus",
|
||||
always,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
"threeD.bevels.edit",
|
||||
"Edit Bevels",
|
||||
[],
|
||||
None,
|
||||
"{} open the bevels file (a native document next to the preferences; created first with one example bevel when it is missing). Each symbol in it whose art is one open path is one custom bevel named after the symbol: the path runs from its first anchor at the cap's edge to its last at the side wall, across the page across the bevel's width and down the page along its height. Saving the file reloads the bevels → {path, created: whether the file was made now}",
|
||||
has_file,
|
||||
edit
|
||||
),
|
||||
cmd!(
|
||||
"threeD.bevels.reload",
|
||||
"Reload Bevels",
|
||||
[],
|
||||
None,
|
||||
"{} read the bevels file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}",
|
||||
has_file,
|
||||
reload
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// A custom bevel: its name and its points, (share of the width, share of the height).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CustomBevel {
|
||||
pub name: String,
|
||||
pub points: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl CustomBevel {
|
||||
/// The points as `bevelProfile` holds them.
|
||||
pub fn profile_json(&self) -> Value {
|
||||
json!(self.points.iter().map(|&(x, y)| [x, y]).collect::<Vec<_>>())
|
||||
}
|
||||
}
|
||||
|
||||
/// The custom bevels read from the bevels file.
|
||||
#[derive(Default)]
|
||||
pub struct Bevels {
|
||||
path: Option<String>,
|
||||
bevels: Vec<Arc<CustomBevel>>,
|
||||
skipped: Vec<(String, String)>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl Bevels {
|
||||
/// The bevels file's path; `None` without one (the web, runs without preferences).
|
||||
pub fn path(&self) -> Option<&str> {
|
||||
self.path.as_deref()
|
||||
}
|
||||
/// The bevels, in the order of the file's symbols.
|
||||
pub fn bevels(&self) -> &[Arc<CustomBevel>] {
|
||||
&self.bevels
|
||||
}
|
||||
/// Bevel `name`.
|
||||
pub fn get(&self, name: &str) -> Option<Arc<CustomBevel>> {
|
||||
self.bevels.iter().find(|b| b.name == name).cloned()
|
||||
}
|
||||
fn set(&mut self, read: Read) {
|
||||
(self.bevels, self.skipped) = (read.bevels.into_iter().map(Arc::new).collect(), read.skipped);
|
||||
self.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The bevels a document holds, and the symbols that are not bevels with the reason.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Read {
|
||||
pub bevels: Vec<CustomBevel>,
|
||||
pub skipped: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The bevels of document `doc`: one per symbol, up to [`MAX_BEVELS`] (see the module docs).
|
||||
pub fn bevels_of(doc: &Document) -> Read {
|
||||
bevels_within(doc, MAX_SIMPLIFY_WORK)
|
||||
}
|
||||
|
||||
/// [`bevels_of`] with `work` point-to-line distances to simplify the paths with.
|
||||
pub fn bevels_within(doc: &Document, mut work: u64) -> Read {
|
||||
let mut out = Read::default();
|
||||
for (i, sym) in doc.symbols.iter().enumerate() {
|
||||
if i >= MAX_BEVELS {
|
||||
out.skipped.push((sym.name.clone(), format!("only the first {MAX_BEVELS} symbols are read")));
|
||||
continue;
|
||||
}
|
||||
if out.bevels.iter().any(|b| b.name == sym.name) {
|
||||
out.skipped.push((sym.name.clone(), "another symbol has this name".into()));
|
||||
continue;
|
||||
}
|
||||
match points_of(&sym.art, &mut work) {
|
||||
Ok(points) => out.bevels.push(CustomBevel { name: sym.name.clone(), points }),
|
||||
Err(why) => out.skipped.push((sym.name.clone(), why.into())),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The one open path of art `n`: `n` itself, or the one member of groups that hold one member each.
|
||||
fn open_path(n: &Node) -> Option<&PathData> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1 && !path.subpaths[0].closed => Some(path),
|
||||
NodeKind::Group { children, clip: false } if children.len() == 1 => open_path(&children[0]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The profile points of a bevel symbol's art `n` (see the module docs), simplified within `work`
|
||||
/// point-to-line distances, which it uses up.
|
||||
fn points_of(n: &Node, work: &mut u64) -> std::result::Result<Vec<(f64, f64)>, &'static str> {
|
||||
let path = open_path(n).ok_or("its art is not one open path")?;
|
||||
if path.anchor_count() > MAX_ANCHORS {
|
||||
return Err("its path has too many anchors for a bevel");
|
||||
}
|
||||
let mut line: Vec<Point> = vec![];
|
||||
let tolerance = path.bounds().map_or(1.0, |b| b.width().hypot(b.height()) / 2000.0).max(1e-9);
|
||||
// One segment at a time, so a path past the limit stops being cut at the segment that passes it.
|
||||
let mut at: Option<Point> = None;
|
||||
for &el in path.to_bezpath().elements() {
|
||||
if line.len() > MAX_LINE_POINTS {
|
||||
return Err("its path is too detailed for a bevel");
|
||||
}
|
||||
match (el, at) {
|
||||
(PathEl::MoveTo(p), _) => line.push(p),
|
||||
(_, Some(start)) => vectorcraft_geom::flatten([PathEl::MoveTo(start), el], tolerance, |e| {
|
||||
if let PathEl::LineTo(p) = e {
|
||||
line.push(p);
|
||||
}
|
||||
}),
|
||||
(_, None) => {}
|
||||
}
|
||||
at = el.end_point().or(at);
|
||||
}
|
||||
if line.len() > MAX_LINE_POINTS {
|
||||
return Err("its path is too detailed for a bevel");
|
||||
}
|
||||
let (Some(&first), Some(&last)) = (line.first(), line.last()) else { return Err("its path has no length") };
|
||||
let (dx, dy) = (last.x - first.x, last.y - first.y);
|
||||
let size = path.bounds().map_or(0.0, |b| b.width().hypot(b.height()));
|
||||
if !(dx.abs() > size * 1e-6 && dy.abs() > size * 1e-6 && size.is_finite()) {
|
||||
return Err("its ends are not apart both across and down");
|
||||
}
|
||||
let mut pts: Vec<(f64, f64)> = line.iter().map(|p| (((p.x - first.x) / dx).clamp(0.0, 1.0), ((p.y - first.y) / dy).clamp(0.0, 1.0))).collect();
|
||||
pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9);
|
||||
if pts.len() < 2 {
|
||||
return Err("its ends are not apart both across and down");
|
||||
}
|
||||
// The ends map to the corners exactly.
|
||||
let last = pts.len() - 1;
|
||||
(pts[0], pts[last]) = ((0.0, 0.0), (1.0, 1.0));
|
||||
let pts = simplified(&pts, work).ok_or("its path is too detailed for a bevel")?;
|
||||
BevelProfile::new(&pts).ok_or("its path is too detailed for a bevel")?;
|
||||
Ok(pts)
|
||||
}
|
||||
|
||||
/// `pts` with the fewest points the Ramer-Douglas-Peucker rule keeps at a tolerance (from a
|
||||
/// thousandth of the bevel, doubled until they fit) that leaves at most
|
||||
/// [`BevelProfile::MAX_POINTS`]. The first and last points are always kept. `None` when that
|
||||
/// measures more point-to-line distances than `work` has left.
|
||||
fn simplified(pts: &[(f64, f64)], work: &mut u64) -> Option<Vec<(f64, f64)>> {
|
||||
let mut eps = 1e-3;
|
||||
loop {
|
||||
let out = rdp(pts, eps, work)?;
|
||||
if out.len() <= BevelProfile::MAX_POINTS || eps > 2.0 {
|
||||
return Some(out);
|
||||
}
|
||||
eps *= 2.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of `pts` Ramer-Douglas-Peucker keeps at tolerance `eps`; `None` when that measures
|
||||
/// more point-to-line distances than `work` has left.
|
||||
fn rdp(pts: &[(f64, f64)], eps: f64, work: &mut u64) -> Option<Vec<(f64, f64)>> {
|
||||
if pts.len() < 3 {
|
||||
return Some(pts.to_vec());
|
||||
}
|
||||
let mut keep = vec![false; pts.len()];
|
||||
keep[0] = true;
|
||||
keep[pts.len() - 1] = true;
|
||||
let mut stack = vec![(0, pts.len() - 1)];
|
||||
while let Some((a, b)) = stack.pop() {
|
||||
*work = work.checked_sub((b - a).saturating_sub(1) as u64)?;
|
||||
let (p, q) = (pts[a], pts[b]);
|
||||
let (vx, vy) = (q.0 - p.0, q.1 - p.1);
|
||||
let len = vx.hypot(vy);
|
||||
let far = (a + 1..b)
|
||||
.map(|i| {
|
||||
let (wx, wy) = (pts[i].0 - p.0, pts[i].1 - p.1);
|
||||
let d = if len > 0.0 { (vx * wy - vy * wx).abs() / len } else { wx.hypot(wy) };
|
||||
(i, d)
|
||||
})
|
||||
.fold(None, |best: Option<(usize, f64)>, (i, d)| if best.is_none_or(|(_, bd)| d > bd) { Some((i, d)) } else { best });
|
||||
if let Some((i, d)) = far
|
||||
&& d > eps
|
||||
{
|
||||
keep[i] = true;
|
||||
stack.push((a, i));
|
||||
stack.push((i, b));
|
||||
}
|
||||
}
|
||||
Some(pts.iter().zip(keep).filter_map(|(p, k)| k.then_some(*p)).collect())
|
||||
}
|
||||
|
||||
/// The document a missing bevels file starts as: one example bevel, a chamfer with a notch.
|
||||
pub fn starter() -> Document {
|
||||
let mut doc = Document::new(612.0, 792.0);
|
||||
doc.title = "Bevels".into();
|
||||
let name = "Example Bevel";
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(10.0, 40.0), Point::new(55.0, 30.0), Point::new(100.0, 100.0)];
|
||||
let art =
|
||||
Node::path(NodeId(0), PathData::single(SubPath::polyline(&pts, false)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
|
||||
let art = doc.reid(&art);
|
||||
doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false });
|
||||
let id = doc.alloc_id();
|
||||
let instance = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate((256.0, 346.0)) });
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let _ = doc.insert(layer, 0, instance);
|
||||
doc
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Keep the custom bevels in the file at `path` and read the bevels it holds (none while it is
|
||||
/// missing; an unreadable file is reported by `threeD.bevels.list`).
|
||||
pub fn attach_bevels_file(&mut self, path: String) {
|
||||
self.bevels.path = Some(path);
|
||||
self.reload_bevels();
|
||||
}
|
||||
|
||||
/// Read the bevels file again.
|
||||
fn reload_bevels(&mut self) {
|
||||
let Some(path) = self.bevels.path.clone() else { return };
|
||||
match read(&path) {
|
||||
Ok(Some(doc)) => self.bevels.set(bevels_of(&doc)),
|
||||
Ok(None) => self.bevels.set(Read::default()),
|
||||
Err(e) => {
|
||||
self.bevels.set(Read::default());
|
||||
self.bevels.error = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document was saved to `path`: when that is the bevels file, its bevels are read back from
|
||||
/// what was written.
|
||||
pub(crate) fn bevels_saved(&mut self, path: &str) {
|
||||
if self.bevels.path.as_deref().is_some_and(|b| same_file(b, path)) {
|
||||
self.reload_bevels();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The command parameter that holds the points a custom bevel given by name had when the command
|
||||
/// ran. The journal records it, so a replay draws the same bevel after the bevels file changes or
|
||||
/// loses that name.
|
||||
pub const SAVED_BEVEL: &str = "savedBevel";
|
||||
|
||||
/// `params` of an effect with `bevel` given as `{custom: name}`: the bevel of the bevels file named
|
||||
/// so, stored as `bevel` `"custom"` with its `bevelName` and `bevelProfile`. The command's
|
||||
/// [`SAVED_BEVEL`] points (`p`), when given, are used in place of the file's, and the points used
|
||||
/// join the journal entry as [`SAVED_BEVEL`]. Other values are left for the effect to check.
|
||||
pub(crate) fn resolve_custom(s: &mut Session, p: &Value, params: &mut Value, cmd: &str) -> Result<()> {
|
||||
let Some(Value::Object(o)) = params.get("bevel") else { return Ok(()) };
|
||||
let name = match (o.len(), o.get("custom")) {
|
||||
(1, Some(Value::String(name))) => name.clone(),
|
||||
_ => return Err(bad(cmd, "bevel: give a shape id, or {custom: name} for a bevel of the bevels file (threeD.bevels.list)")),
|
||||
};
|
||||
let points = match p.get(SAVED_BEVEL).filter(|v| !v.is_null()) {
|
||||
Some(saved) => saved.clone(),
|
||||
None => s.bevels.get(&name).ok_or_else(|| bad(cmd, format!("no custom bevel {name} (see threeD.bevels.list)")))?.profile_json(),
|
||||
};
|
||||
s.note_journal(SAVED_BEVEL, points.clone());
|
||||
params["bevel"] = json!("custom");
|
||||
params[BEVEL_NAME] = json!(name);
|
||||
params[BEVEL_PROFILE] = points;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_file(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.bevels.path.is_some() { Ok(()) } else { Err("no bevels file here".into()) }
|
||||
}
|
||||
|
||||
fn skipped(s: &Session) -> Vec<Value> {
|
||||
s.bevels.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect()
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let bevels: Vec<Value> = s.bevels.bevels.iter().map(|b| json!({"name": b.name, "points": b.profile_json()})).collect();
|
||||
// Under automation read roots, a file outside them is not shown and its error names it by its file name.
|
||||
let path = s.bevels.path.as_deref();
|
||||
let file = path.filter(|p| crate::file_access::check_read(p).is_ok());
|
||||
let error = s.bevels.error.as_deref().map(|e| shown_error(e, path));
|
||||
Ok(json!({"bevels": bevels, "file": file, "skipped": skipped(s), "error": error}))
|
||||
}
|
||||
|
||||
fn reload(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "threeD.bevels.reload";
|
||||
if let Some(path) = &s.bevels.path {
|
||||
may_reach(path)?;
|
||||
}
|
||||
s.reload_bevels();
|
||||
if let Some(e) = &s.bevels.error {
|
||||
return Err(bad(C, e.clone()));
|
||||
}
|
||||
Ok(json!({"count": s.bevels.bevels.len(), "skipped": skipped(s)}))
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "threeD.bevels.edit";
|
||||
let path = s.bevels.path.clone().ok_or_else(|| bad(C, "no bevels file here"))?;
|
||||
// Checked before anything is made, brought to the front or opened.
|
||||
may_reach(&path)?;
|
||||
if let Some(dir) = std::path::Path::new(&path).parent() {
|
||||
let dir = dir.to_string_lossy();
|
||||
std::fs::create_dir_all(&*dir).map_err(|e| super::fileio::naming_in_error(bad(C, format!("{dir}: {e}")), &dir))?;
|
||||
}
|
||||
// Made only when no file is there, also when another run makes one at the same moment.
|
||||
let bytes = vectorcraft_format::save_file(&starter());
|
||||
let created = match crate::file_access::unconfined(|| super::fileio::write_new_file(&path, &bytes)) {
|
||||
Ok(()) => true,
|
||||
Err(_) if std::path::Path::new(&path).exists() => false,
|
||||
Err(e) => return Err(bad(C, e.to_string())),
|
||||
};
|
||||
if created {
|
||||
s.reload_bevels();
|
||||
}
|
||||
// Already open: that document comes to the front.
|
||||
let open = s.documents().iter().position(|st| st.path.as_deref().is_some_and(|p| same_file(p, &path)));
|
||||
match open {
|
||||
Some(i) => {
|
||||
s.set_active(i);
|
||||
}
|
||||
None => {
|
||||
// Opened in the request's own scope, so the document keeps the roots it was opened under.
|
||||
s.execute("document.open", &json!({ "path": path }))?;
|
||||
}
|
||||
}
|
||||
Ok(json!({"path": path, "created": created}))
|
||||
}
|
||||
@@ -177,6 +177,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
|
||||
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
@@ -186,6 +187,8 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
|
||||
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.
|
||||
@@ -239,6 +242,42 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// Artistic: four original vector compositions that stretch along a path and take its color.
|
||||
fn artistic() -> BrushLibrary {
|
||||
let orbit = group(vec![
|
||||
black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
|
||||
black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
|
||||
]);
|
||||
let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))];
|
||||
for i in 0..6 {
|
||||
let x = 9.0 + 16.0 * i as f64;
|
||||
let side = if i % 2 == 0 { 1.0 } else { -1.0 };
|
||||
petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)])));
|
||||
}
|
||||
let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))];
|
||||
for i in 0..5 {
|
||||
let x = 20.0 * i as f64;
|
||||
lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)])));
|
||||
lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)])));
|
||||
}
|
||||
let mut facets = Vec::new();
|
||||
for i in 0..8 {
|
||||
let x = 12.5 * i as f64;
|
||||
let high = if i % 2 == 0 { 6.0 } else { 3.5 };
|
||||
facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)])));
|
||||
}
|
||||
built(
|
||||
"Artistic Brushes",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
art("Orbit Lines", orbit, Colorization::Tints),
|
||||
art("Petal Garland", group(petals), Colorization::Tints),
|
||||
art("Lattice Braid", group(lattice), Colorization::Tints),
|
||||
art("Facet Sweep", group(facets), Colorization::Tints),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Original fine-line art for an engraving-style brush library.
|
||||
fn engraving() -> BrushLibrary {
|
||||
let lines = |count: usize, width: f64, spacing: f64| {
|
||||
@@ -653,6 +692,47 @@ fn pattern_borders() -> BrushLibrary {
|
||||
built("Pattern Borders", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// Decorative: repeating plant, flower and hanging ornaments drawn as original vector tiles.
|
||||
/// Every tile joins the next at x = 0 and 48 so open and closed paths stay continuous.
|
||||
fn decorative() -> BrushLibrary {
|
||||
let stem = || black(shapes::rectangle(Rect::new(0.0, -0.65, 48.0, 0.65)));
|
||||
let vine = group(vec![
|
||||
stem(),
|
||||
black(polygon(&[(8.0, -0.2), (12.0, -5.0), (24.0, -8.0), (20.0, -1.0)])),
|
||||
black(polygon(&[(28.0, 0.2), (32.0, 5.0), (44.0, 8.0), (40.0, 1.0)])),
|
||||
]);
|
||||
let mut blossoms = vec![stem()];
|
||||
for x in [12.0, 36.0] {
|
||||
for (dx, dy) in [(0.0, -4.0), (4.0, 0.0), (0.0, 4.0), (-4.0, 0.0)] {
|
||||
blossoms.push(black(shapes::ellipse(Rect::new(x + dx - 2.5, dy - 2.5, x + dx + 2.5, dy + 2.5))));
|
||||
}
|
||||
blossoms.push(black(shapes::ellipse(Rect::new(x - 1.3, -1.3, x + 1.3, 1.3))));
|
||||
}
|
||||
let flowers = group(blossoms);
|
||||
let pennants = group(vec![
|
||||
black(shapes::rectangle(Rect::new(0.0, -5.2, 48.0, -4.2))),
|
||||
black(polygon(&[(4.0, -4.2), (20.0, -4.2), (12.0, 10.0)])),
|
||||
black(polygon(&[(28.0, -4.2), (44.0, -4.2), (36.0, 10.0)])),
|
||||
]);
|
||||
let lanterns = group(vec![
|
||||
black(shapes::rectangle(Rect::new(0.0, -5.0, 48.0, -4.0))),
|
||||
black(shapes::rectangle(Rect::new(11.4, -4.0, 12.6, -1.0))),
|
||||
black(shapes::ellipse(Rect::new(7.0, -1.0, 17.0, 9.0))),
|
||||
black(shapes::rectangle(Rect::new(35.4, -4.0, 36.6, -1.0))),
|
||||
black(shapes::ellipse(Rect::new(31.0, -1.0, 41.0, 9.0))),
|
||||
]);
|
||||
built(
|
||||
"Decorative",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
border("Leaf Vine", vine, None, PatternFit::Stretch),
|
||||
border("Blossom Chain", flowers, None, PatternFit::Stretch),
|
||||
border("Pennant Garland", pennants, None, PatternFit::Stretch),
|
||||
border("Lantern String", lanterns, None, PatternFit::Stretch),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
|
||||
}
|
||||
@@ -787,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| {
|
||||
@@ -1076,10 +1188,14 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
return Some((builtin_info(b), builtin_library(b.id)?));
|
||||
}
|
||||
let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id;
|
||||
library(s, &id)
|
||||
if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) {
|
||||
return library(s, &id);
|
||||
}
|
||||
// Keep the short built-in alias, but let a user or loaded library own its display name.
|
||||
let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?;
|
||||
Some((builtin_info(b), builtin_library(b.id)?))
|
||||
}
|
||||
|
||||
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<BrushLibrary>)> {
|
||||
|
||||
@@ -362,7 +362,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Sprayer",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
|
||||
"{points: [[x,y]…] (a third value is a number or null and is not used), name?, radius?: 40, density?: 1..10 (5; a number outside 1..10 is taken as the nearer end), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one with an amount above 0, at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
|
||||
has_doc,
|
||||
symbol_spray
|
||||
),
|
||||
@@ -380,7 +380,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbolism Tool",
|
||||
[],
|
||||
None,
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error",
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way; style without `shift`: from none to the userDefined amount); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size as it is. With `proportional` false a drag resizes along its own direction, the width by the drag's horizontal share and the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. The style goes on by the brush's strength at each sample, and a stroke's samples add up. With `alt` and without `shift`, userDefined and random style remove all of an instance's appearance items under the brush at once, whatever the brush's strength. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, each already at the tool's limit, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error",
|
||||
has_doc,
|
||||
symbol_adjust
|
||||
),
|
||||
|
||||
@@ -86,8 +86,9 @@ pub(super) fn spacing(density: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written
|
||||
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it.
|
||||
const SET_DENSITY_KEY: &str = "symbolSetDensity";
|
||||
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it, and copied to a
|
||||
/// copy of a set by [`Document::reid`].
|
||||
const SET_DENSITY_KEY: &str = Document::SYMBOL_SET_DENSITY_KEY;
|
||||
|
||||
/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded).
|
||||
fn set_density_of(d: &Document, set: NodeId) -> Option<f64> {
|
||||
@@ -261,7 +262,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option<Mean> {
|
||||
cos += l.angle.cos();
|
||||
opacity += l.opacity;
|
||||
middle += l.center.to_vec2();
|
||||
if let Some((p, o)) = &l.fill {
|
||||
// A fill at no opacity shows nothing: it is no stain or style, and its paint is not taken.
|
||||
if let Some((p, o)) = &l.fill
|
||||
&& *o > 0.0
|
||||
{
|
||||
amount += o;
|
||||
let far = l.center.distance(at);
|
||||
if paint.is_none_or(|(_, nearest)| far < nearest) {
|
||||
|
||||
@@ -118,6 +118,20 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The symbol instances in `nodes` and inside them, each once, in the order a walk of each node in
|
||||
/// turn first reaches them.
|
||||
fn instances_in<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> Vec<NodeId> {
|
||||
let (mut v, mut seen) = (vec![], std::collections::HashSet::new());
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && seen.insert(c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`.
|
||||
fn art_symbols(n: &Node, out: &mut Vec<String>) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
@@ -917,11 +931,12 @@ fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
|
||||
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?;
|
||||
let mut v = Vec::with_capacity(a.len());
|
||||
for q in a {
|
||||
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
|
||||
// The pressure is checked first: a point skipped for its coordinates still has a bad one refused.
|
||||
let pressure = match q.get(2) {
|
||||
None | Some(Value::Null) => 1.0,
|
||||
Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?,
|
||||
};
|
||||
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
|
||||
v.push((Point::new(x, y), pressure.clamp(0.0, 1.0)));
|
||||
}
|
||||
if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) {
|
||||
@@ -930,13 +945,15 @@ fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The fill of the graphic style `p` names with `style`, else of the document's first style after
|
||||
/// the default one.
|
||||
/// The fill of the graphic style `p` names with `style`, else (no name, or one the document has no
|
||||
/// style for, such as the Symbol Styler's style from another document) of the document's first
|
||||
/// style after the default one.
|
||||
fn style_paint(d: &Document, p: &Value) -> Option<Paint> {
|
||||
match str_param(p, "style") {
|
||||
Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()),
|
||||
None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()),
|
||||
}
|
||||
str_param(p, "style")
|
||||
.and_then(|n| d.graphic_styles.iter().find(|g| g.name == n))
|
||||
.or(d.graphic_styles.get(1))
|
||||
.or(d.graphic_styles.first())
|
||||
.map(|g| g.appearance.fill_paint())
|
||||
}
|
||||
|
||||
/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree).
|
||||
@@ -976,7 +993,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let style = style_paint(&st.doc, p);
|
||||
// Style: User Defined uses the style `style` names, so one the document does not have is an error.
|
||||
if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) {
|
||||
if let Some(n) = str_param(p, "style").filter(|n| !modes.style && !st.doc.graphic_styles.iter().any(|g| g.name == *n)) {
|
||||
return Err(bad(C, format!("unknown graphic style `{n}`")));
|
||||
}
|
||||
let size = natural_size(&st.doc, &name);
|
||||
@@ -1129,6 +1146,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let use_pressure = switch_or(p, "usePressure", false, C)?;
|
||||
let proportional = switch_or(p, "proportional", true, C)?;
|
||||
let affects_density = switch_or(p, "affectsDensity", false, C)?;
|
||||
let shift = switch_or(p, "shift", false, C)?;
|
||||
// The Symbol Shifter has no Method.
|
||||
let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? };
|
||||
// Refused while an object of a dynamic instance's art is selected: the instance stays as it is.
|
||||
@@ -1141,20 +1159,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let style_paint = style_paint(&st.doc, p);
|
||||
let candidates: Vec<NodeId> = {
|
||||
let d = &st.doc;
|
||||
let mut v = vec![];
|
||||
if st.selection.is_empty() {
|
||||
v = instances_of(d, None);
|
||||
} else {
|
||||
for id in &st.selection.objects {
|
||||
if let Some(n) = d.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut v =
|
||||
if st.selection.is_empty() { instances_of(d, None) } else { instances_in(st.selection.objects.iter().filter_map(|id| d.node(*id))) };
|
||||
let editable = d.editable();
|
||||
v.retain(|id| editable(*id));
|
||||
v
|
||||
@@ -1172,12 +1178,39 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// for the whole stroke (and for every preview of it).
|
||||
let first = pts.first().map_or(Point::ZERO, |(q, _)| *q);
|
||||
let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 };
|
||||
// Shift with the Symbol Shifter: the instances under the brush come one place forward among
|
||||
// their siblings (with `alt`, go one place backward), once for the whole stroke.
|
||||
if tool == "shift" && shift {
|
||||
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| {
|
||||
let under: std::collections::HashSet<NodeId> = candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
d.node(*id).and_then(instance_center).is_some_and(|c| {
|
||||
pts.iter().any(|(q, pressure)| (if use_pressure { *pressure } else { intensity }) > 0.0 && c.distance(*q) < radius)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let moved = restack(d, &under, alt)?;
|
||||
Ok((moved, moved > 0))
|
||||
})?;
|
||||
return Ok(json!({ "count": count }));
|
||||
}
|
||||
// Shift with the Symbol Stainer or the Symbol Styler: the paint an instance's stain or style
|
||||
// moves toward, and the share of the brush's strength it moves by. Shift with the Symbol Sizer
|
||||
// keeps the instances where they are, Resizing Affects Density included.
|
||||
let recolor = match tool.as_str() {
|
||||
"stain" if shift => Some((Paint::solid(color), 0.15)),
|
||||
"style" if shift => Some((style_paint.clone().unwrap_or(Paint::solid(color)), 1.0)),
|
||||
_ => None,
|
||||
};
|
||||
let spread = affects_density && !shift;
|
||||
// No undo step when no instance changes (none under the brush, or Average with each at the mean).
|
||||
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| {
|
||||
let mut touched = std::collections::BTreeSet::new();
|
||||
let mut sides = Sides::new();
|
||||
for (j, (q, pressure)) in pts.iter().enumerate() {
|
||||
let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO };
|
||||
let delta = j.checked_sub(1).and_then(|i| pts.get(i)).map_or(Vec2::ZERO, |(prev, _)| *q - *prev);
|
||||
// Use Pressure Pen: the pen's pressure at the point is the intensity there.
|
||||
let strength = if use_pressure { *pressure } else { intensity };
|
||||
// Average: the mean of the instances under the brush, as they are at this point.
|
||||
@@ -1198,6 +1231,14 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if w <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
// Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount
|
||||
// of its stain or style, and its paint moves toward the color or the style. An
|
||||
// instance without one, or without a size, is left as it is.
|
||||
if let Some((to, step)) = &recolor {
|
||||
let fill = d.node(*id).and_then(|n| look(d, n, &mut sides)).and_then(|l| l.fill);
|
||||
touched.extend(recolor_keeping_amount(d, *id, fill, to, step * w).then_some(*id));
|
||||
continue;
|
||||
}
|
||||
// Average needs the instance's own values, so it leaves an instance without a size
|
||||
// as it is; the other methods change it as before.
|
||||
// The instance's own values are read for Average only.
|
||||
@@ -1261,8 +1302,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
n.transform(about(Affine::scale_non_uniform(kx, ky)), false);
|
||||
// Resizing Affects Density: instances move away from the brush's center as
|
||||
// they grow and toward it as they shrink.
|
||||
if affects_density {
|
||||
// they grow and toward it as they shrink. Shift keeps the instances where
|
||||
// they are, so the set's density stays as it was.
|
||||
if spread {
|
||||
n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false);
|
||||
}
|
||||
}
|
||||
@@ -1280,9 +1322,10 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"stain" | "style" => {
|
||||
let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) };
|
||||
let (paint, o) = match &avg {
|
||||
// Toward the mean amount, keeping the stain or style the instance has.
|
||||
// Toward the mean amount, keeping the stain or style the instance has
|
||||
// (one at no opacity is none).
|
||||
Some((t, look)) => {
|
||||
let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o));
|
||||
let (own, cur) = look.fill.clone().filter(|(_, o)| *o > 0.0).map_or((None, 0.0), |(p, o)| (Some(p), o));
|
||||
(own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32)
|
||||
}
|
||||
// Alt with the Symbol Styler removes the instance's appearance.
|
||||
@@ -1292,11 +1335,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => {
|
||||
let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0);
|
||||
// The style goes on gradually, by the brush's strength there: in
|
||||
// full at the center at full intensity or pressure.
|
||||
let step = match (tool.as_str(), method) {
|
||||
// Random: the instance's share of the style, scaled by the
|
||||
// brush strength there.
|
||||
("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32,
|
||||
("style", _) => 1.0,
|
||||
("style", Method::Random) => (w * share / 2.0) as f32,
|
||||
("style", _) => w as f32,
|
||||
_ => (0.15 * w * share) as f32,
|
||||
};
|
||||
(paint, if alt { cur - step } else { cur + step })
|
||||
@@ -1324,9 +1367,108 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// An instance the stroke moved away and back again is not counted.
|
||||
// An instance the stroke moved away and back again, or reached but left as it was (at a
|
||||
// limit already), is not counted.
|
||||
touched.retain(|id| d.node(*id) != orig.node(*id));
|
||||
Ok((touched.len(), !touched.is_empty()))
|
||||
})?;
|
||||
Ok(json!({ "count": count }))
|
||||
}
|
||||
|
||||
/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount)
|
||||
/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's
|
||||
/// other appearance items stay as they are. A paint with no form between it and `to` (a solid
|
||||
/// color and a pattern, say) takes `to` at once, so repeated strokes below half strength still
|
||||
/// reach it. An instance without a stain or style, or one whose paint does not change, is left as
|
||||
/// it is. Returns whether it changed.
|
||||
fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool {
|
||||
use vectorcraft_doc::blend::lerp_paint;
|
||||
let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false };
|
||||
let t = t.clamp(0.0, 1.0) as f32;
|
||||
let mut paint = lerp_paint(&own, to, t);
|
||||
// `lerp_paint` switches such a pair halfway, so just below half it still gives `own`.
|
||||
if paint == own && t > 0.0 && lerp_paint(&own, to, 0.49) == own {
|
||||
paint = to.clone();
|
||||
}
|
||||
if paint == own {
|
||||
return false;
|
||||
}
|
||||
let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false };
|
||||
f.paint = paint;
|
||||
true
|
||||
}
|
||||
|
||||
/// Bring each of `ids` one place forward among its siblings past a sibling that is not one of them
|
||||
/// (`back`: one place backward). Ones already in front of (behind) every other sibling stay, and
|
||||
/// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how
|
||||
/// many moved.
|
||||
fn restack(d: &mut Document, ids: &std::collections::HashSet<NodeId>, back: bool) -> Result<usize> {
|
||||
let parents: std::collections::BTreeSet<Option<NodeId>> = ids.iter().map(|id| d.parent_of(*id)).collect();
|
||||
let mut moved = 0;
|
||||
for par in parents {
|
||||
let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips));
|
||||
let ch = d.children_mut(par)?;
|
||||
let len = Node::guide_run_start(ch);
|
||||
if len <= floor + 1 {
|
||||
continue;
|
||||
}
|
||||
let picked = |n: &Arc<Node>| ids.contains(&n.id);
|
||||
if back {
|
||||
for i in floor + 1..len {
|
||||
if picked(&ch[i]) && !picked(&ch[i - 1]) {
|
||||
ch.swap(i - 1, i);
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i in (floor..len - 1).rev() {
|
||||
if picked(&ch[i]) && !picked(&ch[i + 1]) {
|
||||
ch.swap(i, i + 1);
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn instance(id: u64) -> Arc<Node> {
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }))
|
||||
}
|
||||
|
||||
/// The instances come out in the order a search of the list built so far gives: nested
|
||||
/// groups, a group listed twice, a member listed after its group and one listed before it.
|
||||
#[test]
|
||||
fn instances_in_matches_searching_the_list_so_far() {
|
||||
let groups: Vec<Node> = (0..40u64)
|
||||
.map(|g| {
|
||||
let base = g * 100;
|
||||
let mut children: Vec<Arc<Node>> = (0..40).map(|i| instance(base + i)).collect();
|
||||
let inner = (40..50).map(|i| instance(base + i)).collect();
|
||||
children.insert(20, Arc::new(Node::group(NodeId(base + 90), inner)));
|
||||
children.push(Arc::new(Node::group(NodeId(base + 91), vec![])));
|
||||
Node::group(NodeId(base + 99), children)
|
||||
})
|
||||
.collect();
|
||||
let early = Node::new(NodeId(1_245), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
|
||||
let late = Node::new(NodeId(305), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
|
||||
let nodes: Vec<&Node> = std::iter::once(&early).chain(&groups).chain([&groups[0], &late, &groups[7]]).collect();
|
||||
let mut searched = vec![];
|
||||
for n in &nodes {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !searched.contains(&c.id) {
|
||||
searched.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
let found = instances_in(nodes.iter().copied());
|
||||
assert_eq!(found, searched);
|
||||
assert_eq!(found.len(), 2_000);
|
||||
assert_eq!(found[0], NodeId(1_245));
|
||||
assert!(instances_in([]).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,9 +58,10 @@ fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
|
||||
}
|
||||
|
||||
/// The `split` param (the Split view's divider, 0 to 1), if given.
|
||||
/// The `split` param (the Split view's divider, 0 to 1), if given. A null divider is an error, as
|
||||
/// any other value that is not such a number is; only an omitted one keeps the divider.
|
||||
fn split_param(cmd: &str, p: &Value) -> Result<Option<f64>> {
|
||||
let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let Some(v) = p.get("split") else { return Ok(None) };
|
||||
v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1"))
|
||||
}
|
||||
|
||||
@@ -649,7 +650,16 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(),
|
||||
None => "Custom".to_string(),
|
||||
};
|
||||
// The image (inside a trace group, or selected directly).
|
||||
let (target, image) = target_image(s, c, p)?;
|
||||
// The traced shapes are placed by the image's transform, which a distortion overrides: the
|
||||
// command stops before any pixels are read.
|
||||
let distorted = s.doc()?.doc.node(target).is_some_and(|n| {
|
||||
n.is_distorted_image() || (is_trace_group(n) && n.children().and_then(|c| c.first()).is_some_and(|i| i.is_distorted_image()))
|
||||
});
|
||||
if distorted {
|
||||
return Err(crate::cmd::xform::distorted_image_error(c, target));
|
||||
}
|
||||
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
|
||||
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
|
||||
}
|
||||
|
||||
@@ -109,6 +109,9 @@ pub struct Clipboard {
|
||||
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
|
||||
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
|
||||
pub guides: Vec<vectorcraft_doc::Guide>,
|
||||
/// The Symbol Set Density recorded at Copy for each copied symbol set, by its id in
|
||||
/// [`Self::nodes`]: a pasted set packs from it.
|
||||
pub set_densities: BTreeMap<NodeId, Value>,
|
||||
/// The RGB and CMYK profiles the objects' colors showed through in the document they were
|
||||
/// copied from (its assigned profiles, else the working spaces then), by name; none for objects
|
||||
/// from outside an open document. Paste compares them with the destination's
|
||||
@@ -484,6 +487,7 @@ impl Clipboard {
|
||||
})
|
||||
.collect(),
|
||||
guides: self.guides.clone(),
|
||||
set_densities: self.set_densities.clone(),
|
||||
source_profiles: self.source_profiles.clone(),
|
||||
colors_converted: self.colors_converted,
|
||||
}
|
||||
|
||||
@@ -1161,6 +1161,7 @@ impl Clipboard {
|
||||
char_styles: pick(Res::CharStyle, &src.char_styles),
|
||||
para_styles: pick(Res::ParaStyle, &src.para_styles),
|
||||
brushes,
|
||||
set_densities: src.set_densities_of(&nodes),
|
||||
nodes,
|
||||
..Default::default()
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Color",
|
||||
[],
|
||||
None,
|
||||
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
|
||||
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first",
|
||||
always,
|
||||
convert_color
|
||||
),
|
||||
@@ -1362,10 +1362,15 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
|
||||
let lab = c.lab(&col);
|
||||
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
|
||||
"rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
|
||||
"cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
|
||||
"gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
|
||||
"lab" => ("lab", vec![lab.l, lab.a, lab.b]),
|
||||
"rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))),
|
||||
"cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))),
|
||||
"gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))),
|
||||
"lab" => ("lab", json!([lab.l, lab.a, lab.b])),
|
||||
"oklch" => {
|
||||
// RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them.
|
||||
let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0)));
|
||||
("oklch", json!([l * 100.0, ch, h]))
|
||||
}
|
||||
other => return Err(bad(C, format!("unknown model `{other}`"))),
|
||||
};
|
||||
let de = c.gamut_error(&col);
|
||||
|
||||
@@ -1568,6 +1568,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for xf in placements {
|
||||
for (k, n) in clip.nodes.iter().enumerate() {
|
||||
let mut c = d.reid(n);
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c);
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
|
||||
@@ -52,7 +52,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Apply Effect",
|
||||
[],
|
||||
None,
|
||||
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
|
||||
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (with params bevel {custom: name}: the custom bevel's points, used in place of the bevels file's; the journal records them so a replay draws the same bevel after the file changes)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -79,7 +79,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Effect Options",
|
||||
[],
|
||||
None,
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} → {ids}",
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}",
|
||||
has_doc,
|
||||
set_params
|
||||
),
|
||||
@@ -442,6 +442,17 @@ fn check_revolve_count(n: &Node, cmd: &str) -> Result<()> {
|
||||
|
||||
pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existing effect's options, or remove it first.";
|
||||
|
||||
/// The Pathfinder Options that `effect.apply` gives a Pathfinder effect for the keys its `params`
|
||||
/// leave out: the preferences' Pathfinder Options in force.
|
||||
pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOptions {
|
||||
let current = super::pathops::current_pf_options(s);
|
||||
effects::PathfinderEffectOptions {
|
||||
precision: current.precision,
|
||||
remove_redundant_points: current.remove_redundant_points,
|
||||
remove_unpainted: current.remove_unpainted,
|
||||
}
|
||||
}
|
||||
|
||||
/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the
|
||||
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one;
|
||||
/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
|
||||
@@ -465,13 +476,30 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::params::check_effect_color(C, id, ¶ms)?;
|
||||
super::params::check_effect_channel(C, id, ¶ms)?;
|
||||
super::params::check_effect_center(C, id, ¶ms)?;
|
||||
super::params::check_effect_pathfinder(C, id, ¶ms)?;
|
||||
// Crop Marks take their style from the preferences when applied.
|
||||
if id == effects::CROP_MARKS && params.get("style").is_none() {
|
||||
params["style"] = json!(s.crop_mark_style().id());
|
||||
}
|
||||
// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those `params`
|
||||
// give aside. They join the journal entry, so replaying it gives the same effect.
|
||||
if effects::takes_pathfinder_options(id) {
|
||||
if let Value::Object(filled) = pathfinder_effect_options(s).to_params() {
|
||||
for (key, v) in filled {
|
||||
if params.get(&key).is_none() {
|
||||
params[key.as_str()] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
s.note_journal("params", params.clone());
|
||||
}
|
||||
if texture_load_effect(id) {
|
||||
load_texture(&mut params, C)?;
|
||||
}
|
||||
// A custom bevel by name takes a copy of its points from the bevels file.
|
||||
if bevel_effect(id) {
|
||||
super::bevels::resolve_custom(s, p, &mut params, C)?;
|
||||
}
|
||||
// An SVG filter needs its <filter> element, and is named by its id.
|
||||
if id == effects::SVG_FILTER {
|
||||
let xml = params.get("xml").and_then(Value::as_str).ok_or_else(|| bad(C, "give `xml`, one SVG <filter> element"))?;
|
||||
@@ -789,10 +817,14 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::params::check_effect_color(C, effect, ¶ms)?;
|
||||
super::params::check_effect_channel(C, effect, ¶ms)?;
|
||||
super::params::check_effect_center(C, effect, ¶ms)?;
|
||||
super::params::check_effect_pathfinder(C, effect, ¶ms)?;
|
||||
}
|
||||
if edited.iter().any(|e| texture_load_effect(e)) {
|
||||
load_texture(&mut params, C)?;
|
||||
}
|
||||
if edited.iter().any(|e| bevel_effect(e)) || kind == Some(effects::EXTRUDE) {
|
||||
super::bevels::resolve_custom(s, p, &mut params, C)?;
|
||||
}
|
||||
let targets = effect_targets(s, p, item, index, C)?;
|
||||
// The type each 3D effect already has, with nothing else to change, is no edit (and is not
|
||||
// checked again).
|
||||
@@ -808,6 +840,15 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// Pathfinder effects given the values they already evaluate with, and nothing else to change,
|
||||
// are no edit and record no undo step.
|
||||
if kind.is_none() && warp_id.is_none() && visible.is_none() {
|
||||
let d = &s.doc()?.doc;
|
||||
let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect();
|
||||
if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, ¶ms)) {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// An SVG filter is named by its id: another filter renames the effect.
|
||||
if edited.iter().any(|e| e == effects::SVG_FILTER)
|
||||
&& let Some(xml) = params.get("xml").and_then(Value::as_str)
|
||||
@@ -876,6 +917,36 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// Does effect `id` take a `bevel` (Extrude & Bevel, Extrude & Bevel (Classic)), which may be a
|
||||
/// custom bevel given by name?
|
||||
fn bevel_effect(id: &str) -> bool {
|
||||
id == effects::EXTRUDE || id == effects::CLASSIC_EXTRUDE
|
||||
}
|
||||
|
||||
/// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder
|
||||
/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
|
||||
/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale
|
||||
/// Strokes & Effects took past its range evaluates at the bound but is still edited), and every
|
||||
/// other value given equal to the one it has?
|
||||
fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
|
||||
if !effects::takes_pathfinder_options(&e.id) {
|
||||
return false;
|
||||
}
|
||||
let Some(given) = params.as_object().filter(|m| !m.is_empty()) else { return true };
|
||||
let current = effects::merged_params(&e.id, &e.params);
|
||||
let mut after = current.clone();
|
||||
if let Value::Object(m) = &mut after {
|
||||
m.extend(given.clone());
|
||||
}
|
||||
let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v));
|
||||
let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x));
|
||||
let stored_same = given
|
||||
.iter()
|
||||
.filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str()))
|
||||
.all(|(k, v)| e.params.get(k).is_none_or(|stored| same_value(stored, v)));
|
||||
others_same && stored_same && effects::PathfinderEffectOptions::from_params(¤t) == effects::PathfinderEffectOptions::from_params(&after)
|
||||
}
|
||||
|
||||
// ---------- Load Texture ----------
|
||||
|
||||
/// Effect › Distort › Glass.
|
||||
|
||||
@@ -1193,7 +1193,8 @@ impl SaveJob {
|
||||
}
|
||||
// The other open documents that place this one show the new version.
|
||||
let written = self.plan.path.clone().filter(|_| matches!(self.plan.format.id, "vectorcraft" | "template"));
|
||||
// A save of the arrowheads file lists its heads in the arrowhead menus.
|
||||
// A save of the arrowheads file lists its heads in the arrowhead menus, and one of the
|
||||
// bevels file its bevels in the Bevel Shape menus.
|
||||
let native = self.plan.format.id == "vectorcraft";
|
||||
if let Some(st) = s.document_mut(uid) {
|
||||
self.finish(st);
|
||||
@@ -1204,6 +1205,7 @@ impl SaveJob {
|
||||
if let Some(path) = written {
|
||||
if native {
|
||||
s.arrowheads_saved(&path);
|
||||
s.bevels_saved(&path);
|
||||
}
|
||||
crate::cmd::links::refresh_placed(s, uid, &path);
|
||||
}
|
||||
|
||||
@@ -141,7 +141,11 @@ impl Builder {
|
||||
if fills.is_empty() { Body::Complex } else { Body::Fills { shape: self.shape(path, rule, Kind::Vector)?, fills } }
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
|
||||
// A distorted image's frame joins its corners.
|
||||
let frame = match n.image_frame().filter(|_| n.is_distorted_image()) {
|
||||
Some(bp) => PathData::from_bezpath(&bp),
|
||||
None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf),
|
||||
};
|
||||
self.shape(frame, FillRule::NonZero, Kind::Other)?;
|
||||
Body::Complex
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`.
|
||||
// While the Live Paint Bucket is active the proxies show the default paint, whose stops can be
|
||||
// selected with a part picked.
|
||||
if s.tool_id() != super::paint::LIVE_PAINT_BUCKET && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
if !s.bucket_paints() && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
let index = match p.get("index") {
|
||||
@@ -111,7 +111,7 @@ impl StopOwner {
|
||||
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
|
||||
fill: s.fill_active,
|
||||
item: s.appearance_item(),
|
||||
bucket: s.tool_id() == super::paint::LIVE_PAINT_BUCKET,
|
||||
bucket: s.bucket_paints(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1211,6 +1211,16 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its
|
||||
/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader
|
||||
/// that places it by the transform still gives it its old size.
|
||||
fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
}
|
||||
|
||||
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
|
||||
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
|
||||
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
|
||||
@@ -1235,7 +1245,12 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
let distorted = n.is_distorted_image();
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if distorted {
|
||||
refill_distorted(im, &link, &img);
|
||||
return (n, clip);
|
||||
}
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
let (old_pt, old_clip) = match old.get(&im.key) {
|
||||
@@ -1251,6 +1266,14 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
|
||||
}
|
||||
for id in ids {
|
||||
if d.node(*id).is_some_and(Node::is_distorted_image) {
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
{
|
||||
refill_distorted(im, &link, &img);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue };
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
@@ -2068,6 +2091,9 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
// Whether the images were found as the missing links (nothing selected, a folder given) rather
|
||||
// than named or selected.
|
||||
let mut found_missing = false;
|
||||
let mut ids: Vec<NodeId> = match (&each, ids_param(p, "ids", C)?) {
|
||||
(Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(),
|
||||
(None, Some(ids)) => ids,
|
||||
@@ -2075,6 +2101,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selected: Vec<NodeId> = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect();
|
||||
match folder_param {
|
||||
Some(_) if selected.is_empty() => {
|
||||
found_missing = true;
|
||||
groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect()
|
||||
}
|
||||
_ => selected,
|
||||
@@ -2087,6 +2114,11 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the images to relink, or pass ids"));
|
||||
}
|
||||
// A named or selected distorted image is refused before a folder is searched, whether or not
|
||||
// its file is found there.
|
||||
if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// All Instances: the other stored objects linked to the same files, each once.
|
||||
if scope == Scope::All {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
@@ -2131,6 +2163,11 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
(None, None, None) => return Err(bad(C, "give path (a file) or folder")),
|
||||
}
|
||||
// A new file's placement options place a plain image: a distorted one is left as it is.
|
||||
let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image));
|
||||
if let Some(id) = distorted {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// Every file is read and checked before any is copied.
|
||||
let mut checked = vec![];
|
||||
for (ids, path) in files {
|
||||
@@ -2593,6 +2630,9 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the linked images or placed documents, or pass ids"));
|
||||
}
|
||||
if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// A DCS file's plates print from its file.
|
||||
let separated = |id: &NodeId| match kind(id) {
|
||||
Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated),
|
||||
@@ -2721,6 +2761,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if im.link.is_some() {
|
||||
return Err(bad(C, format!("image {} is linked already", id.0)));
|
||||
}
|
||||
if n.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
|
||||
let stored = stored_extension(blob);
|
||||
@@ -2772,6 +2815,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
if n.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
embedded.push((id, n.display_name(), blob));
|
||||
}
|
||||
@@ -2984,7 +3030,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (px, py) = file_pt(&st.doc, &im.key);
|
||||
out["effectivePpi"] = out["ppi"].take();
|
||||
out["ppi"] = json!([72.0 / px, 72.0 / py]);
|
||||
(out["scale"], out["rotation"]) = scale_rotation(im.xf, (px, py));
|
||||
// A distorted image is measured at its middle, as its effective resolution is.
|
||||
let xf = stored(&doc, id).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf);
|
||||
(out["scale"], out["rotation"]) = scale_rotation(xf, (px, py));
|
||||
out["format"] = json!(format_label(&st.doc, im));
|
||||
out["placement"] = placement_json(im.placement);
|
||||
out["status"] = json!("embedded");
|
||||
|
||||
@@ -244,12 +244,22 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) => return Err(bad(C, "handle must be in or out")),
|
||||
};
|
||||
let independent = switch_or(p, "independent", false, C)?;
|
||||
let symmetric = switch_or(p, "symmetric", false, C)?;
|
||||
let link = switch_or(p, "link", false, C)?;
|
||||
let with = spine_points_param(p, C)?;
|
||||
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
|
||||
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "`with` moves points, not a handle"));
|
||||
}
|
||||
if symmetric && independent {
|
||||
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
|
||||
}
|
||||
if symmetric && handle.is_none() {
|
||||
return Err(bad(C, "`symmetric` places a handle: give `handle`"));
|
||||
}
|
||||
if link && symmetric {
|
||||
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
|
||||
}
|
||||
if link && independent {
|
||||
return Err(bad(C, "`link` and `independent` cannot both be true"));
|
||||
}
|
||||
@@ -264,6 +274,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
|
||||
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
|
||||
// At an open end of the spine the handle moves as it would without `symmetric`.
|
||||
let symmetric = symmetric && pull_out;
|
||||
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
|
||||
if let Some(out) = handle {
|
||||
if link {
|
||||
@@ -271,6 +283,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
a.set_handle(out, q, independent);
|
||||
}
|
||||
if symmetric {
|
||||
let opposite = a.p - (q - a.p);
|
||||
if out { a.h_in = opposite } else { a.h_out = opposite }
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let delta = q - a.p;
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Spine Point",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `symmetric` and `link` need `handle`, `symmetric` cannot go with `independent`, and `link` cannot go with `independent` or `symmetric`; all default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
has_doc,
|
||||
spine_move_anchor
|
||||
),
|
||||
|
||||
@@ -25,14 +25,23 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let (rows, cols) = if at.is_some() { (1, 1) } else { (rows, cols) };
|
||||
let roots = roots_param(s, p)?;
|
||||
// The distorted images left as they are, each with why.
|
||||
let mut distorted = vec![];
|
||||
let (ids, index) = s.edit("Create Gradient Mesh", |d, sel| {
|
||||
let mut out = vec![];
|
||||
let mut index = None;
|
||||
let mut refused = None;
|
||||
let model = d.color_mode.model();
|
||||
distorted.clear();
|
||||
for id in &roots {
|
||||
let Some(n) = d.node(*id).cloned() else { continue };
|
||||
let m = if let NodeKind::Image(im) = &n.kind {
|
||||
if n.is_distorted_image() {
|
||||
let e = super::super::xform::distorted_image_error(C, *id);
|
||||
distorted.push(json!({"id": id.0, "reason": e.to_string()}));
|
||||
refused.get_or_insert(e);
|
||||
continue;
|
||||
}
|
||||
// An embedded image: the points take the picture's colours there.
|
||||
match image_mesh(d, im, rows, cols) {
|
||||
Ok(mut m) => {
|
||||
@@ -40,7 +49,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(m)
|
||||
}
|
||||
Err(why) => {
|
||||
refused.get_or_insert(why);
|
||||
refused.get_or_insert_with(|| bad(C, why));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -60,7 +69,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match m.add_lines_at(q, tol) {
|
||||
Some(i) => index = Some(i),
|
||||
None => {
|
||||
refused.get_or_insert("point is outside the object");
|
||||
refused.get_or_insert_with(|| bad(C, "point is outside the object"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -75,7 +84,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
out.push(*id);
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(bad(C, refused.unwrap_or("select a path, a compound path or an embedded image")));
|
||||
return Err(refused.unwrap_or_else(|| bad(C, "select a path, a compound path or an embedded image")));
|
||||
}
|
||||
sel.set(out.iter().copied());
|
||||
Ok((out, index))
|
||||
@@ -84,6 +93,9 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(i) = index {
|
||||
r["index"] = json!(i);
|
||||
}
|
||||
if !distorted.is_empty() {
|
||||
r["skipped"] = json!(distorted);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
|
||||
@@ -998,6 +998,9 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result<MosaicPlan> {
|
||||
.ok_or_else(|| bad(C, "select an image"))?;
|
||||
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if node.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) {
|
||||
return Err(bad(C, "the image has no embedded pixels"));
|
||||
}
|
||||
@@ -1285,6 +1288,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.ok_or_else(|| bad(C, "select an image"))?;
|
||||
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if node.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
if switch_or(p, "trim", false, C)? {
|
||||
if p.get("ppi").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
|
||||
@@ -1495,11 +1501,16 @@ fn mask_image(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.find_map(|id| match st.doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Image(im)) => {
|
||||
Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf)))
|
||||
.find_map(|id| {
|
||||
let n = st.doc.node(*id)?;
|
||||
match &n.kind {
|
||||
// A distorted image's outline joins its corners.
|
||||
NodeKind::Image(_) if n.is_distorted_image() => Some((*id, PathData::from_bezpath(&n.image_frame()?))),
|
||||
NodeKind::Image(im) => {
|
||||
Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| bad("object.maskImage", "select an image"))?;
|
||||
let (gid, pid) = s.edit("Mask", |d, sel| {
|
||||
|
||||
@@ -209,7 +209,7 @@ impl Session {
|
||||
/// the first selected object (so the last selection's once nothing is selected). Not while the
|
||||
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with.
|
||||
pub(crate) fn inherit_new_art(&mut self) {
|
||||
if self.prefs.new_art_basic || self.tool_id() == super::paint::LIVE_PAINT_BUCKET {
|
||||
if self.prefs.new_art_basic || self.bucket_paints() {
|
||||
return;
|
||||
}
|
||||
let Some(st) = self.active() else { return };
|
||||
|
||||
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -124,7 +124,7 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live
|
||||
}
|
||||
|
||||
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
|
||||
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
|
||||
let items = match p.get("items").filter(|v| !v.is_null()) {
|
||||
@@ -235,6 +235,13 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When every value given is the current one, the document and its undo history stay as they
|
||||
// are.
|
||||
let st = s.doc()?;
|
||||
// `rectanglesOnly`: the live rectangles among the targets; the other objects stay as they are.
|
||||
let ids: Vec<NodeId> = if p.get("rectanglesOnly").and_then(Value::as_bool) == Some(true) {
|
||||
let rectangle = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Path { live: Some(l), .. }) if matches!(**l, LiveShape::Rectangle { .. }));
|
||||
ids.into_iter().filter(rectangle).collect()
|
||||
} else {
|
||||
ids
|
||||
};
|
||||
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
|
||||
// past the document's coordinate limit is an error before anything changes.
|
||||
let mut lines = std::collections::BTreeMap::new();
|
||||
@@ -278,16 +285,23 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let Some(c) = LiveCorners::new(path, live.as_deref()) else { return true };
|
||||
let picked = corners_of(*id).unwrap_or_else(|| c.picked(st.selection.anchors.get(id)));
|
||||
// Setting corners folds a scale left in a rectangle's transform into its size, which
|
||||
// changes it.
|
||||
live.as_deref().is_none_or(|l| l.folded() == *l)
|
||||
// Setting a radius folds a scale left in a rectangle's transform into its size, which
|
||||
// changes it. A kind the corners already have leaves the rectangle as it is.
|
||||
(radius.is_none() || live.as_deref().is_none_or(|l| l.folded() == *l))
|
||||
&& picked.iter().all(|k| {
|
||||
*k < c.base.anchor_count()
|
||||
&& radius.is_none_or(|r| (c.drawn_radius(*k) - r.max(0.0)).abs() < 1e-9)
|
||||
// A radius stored in document units can be larger than it draws; a relative
|
||||
// one is a fraction, so it is compared as drawn.
|
||||
&& radius.is_none_or(|r| {
|
||||
let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) };
|
||||
(now - r.max(0.0)).abs() < 1e-9
|
||||
})
|
||||
&& kind.is_none_or(|kd| c.kind(*k) == kd)
|
||||
})
|
||||
};
|
||||
if ids.iter().all(has_values) {
|
||||
// The objects every value given already matches stay as they are, beside others that change.
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| !has_values(id)).collect();
|
||||
if ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Live Shape", |d, sel| {
|
||||
|
||||
@@ -203,10 +203,11 @@ impl Session {
|
||||
/// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item
|
||||
/// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With
|
||||
/// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that
|
||||
/// object as the instance draws it. None while the Live Paint Bucket is the active tool: the
|
||||
/// proxies show the colors it paints with.
|
||||
/// object as the instance draws it. None while the Live Paint Bucket is the active tool (or
|
||||
/// another tool works for it, [`Session::bucket_paints`]): the proxies show the colors it
|
||||
/// paints with.
|
||||
pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option<usize>)> {
|
||||
if self.tool_id() == LIVE_PAINT_BUCKET {
|
||||
if self.bucket_paints() {
|
||||
return None;
|
||||
}
|
||||
let st = self.active()?;
|
||||
@@ -378,11 +379,28 @@ impl DocState {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the
|
||||
/// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while
|
||||
/// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a
|
||||
/// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the
|
||||
/// sample its click takes before it switches back to the bucket.
|
||||
pub fn bucket_paints(&self) -> bool {
|
||||
let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET);
|
||||
// A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it.
|
||||
self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket)
|
||||
}
|
||||
|
||||
/// The tool the active tool's armed one-shot pick switches back to after its click
|
||||
/// ([`vectorcraft_tools::Tool::returns_to`]).
|
||||
pub fn tool_returns_to(&self) -> Option<String> {
|
||||
self.tool.returns_to().map(str::to_string)
|
||||
}
|
||||
|
||||
/// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item.
|
||||
/// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors.
|
||||
/// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]).
|
||||
pub fn proxy_mixed(&self) -> (bool, bool) {
|
||||
if self.tool_id() == LIVE_PAINT_BUCKET {
|
||||
if self.bucket_paints() {
|
||||
return (false, false);
|
||||
}
|
||||
self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points()))
|
||||
@@ -737,12 +755,13 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
|
||||
}
|
||||
|
||||
/// Is the Live Paint Bucket the active tool while `p` names no `ids`, `id` or `item`? A fill,
|
||||
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`,
|
||||
/// `id` or `item`? A fill,
|
||||
/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults
|
||||
/// and the selection keeps its paint.
|
||||
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
|
||||
// A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row.
|
||||
s.tool_id() == LIVE_PAINT_BUCKET && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
|
||||
s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
|
||||
}
|
||||
|
||||
/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise.
|
||||
|
||||
@@ -516,7 +516,30 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
|
||||
}
|
||||
check_effect_color(id, effect, params)?;
|
||||
check_effect_channel(id, effect, params)?;
|
||||
check_effect_center(id, effect, params)
|
||||
check_effect_center(id, effect, params)?;
|
||||
check_effect_pathfinder(id, effect, params)
|
||||
}
|
||||
|
||||
/// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given
|
||||
/// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and
|
||||
/// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves
|
||||
/// before they edit, as they run [`check_effect_color`].
|
||||
pub(crate) fn check_effect_pathfinder(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
use vectorcraft_render::effects;
|
||||
if !effects::takes_pathfinder_options(effect) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(v) = params.get("precision")
|
||||
&& !v.as_f64().is_some_and(|p| effects::PATHFINDER_EFFECT_PRECISION.contains(&p))
|
||||
{
|
||||
return Err(bad(id, "precision must be from 0.001 to 10 pt"));
|
||||
}
|
||||
for key in ["removeRedundantPoints", "removeUnpainted"] {
|
||||
if params.get(key).is_some_and(|v| !v.is_boolean()) {
|
||||
return Err(bad(id, format!("`{key}` must be true or false")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key
|
||||
@@ -557,9 +580,11 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
/// A value of the type effect `effect` reads for `key`, a parameter its params description names
|
||||
/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`,
|
||||
/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number
|
||||
/// and a Gaussian Blur's `linear` is true or false. A Glass, Texturizer or Rough Pastels
|
||||
/// `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of Crop
|
||||
/// Marks have checks of their own; they aren't listed.
|
||||
/// and a Gaussian Blur's `linear` is true or false. A Pathfinder effect's `precision` is a number and
|
||||
/// its `removeRedundantPoints` and `removeUnpainted` are true or false. A Glass, Texturizer or Rough
|
||||
/// Pastels `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version`, the `style` of Crop
|
||||
/// Marks and an Extrude & Bevel's custom `bevelName` and `bevelProfile` have checks of their own;
|
||||
/// they aren't listed.
|
||||
pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
|
||||
use vectorcraft_render::effects;
|
||||
let number = || Some(Value::from(0.0));
|
||||
@@ -568,6 +593,8 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
|
||||
"variation" if effect == "stylize.scribble" => number(),
|
||||
"width" if effect == "path.outlineStroke" => number(),
|
||||
"linear" if effect == "blur.gaussian" => Some(Value::Bool(false)),
|
||||
"precision" if effects::takes_pathfinder_options(effect) => number(),
|
||||
"removeRedundantPoints" | "removeUnpainted" if effects::takes_pathfinder_options(effect) => Some(Value::Bool(false)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
has_doc,
|
||||
set_handle
|
||||
),
|
||||
@@ -461,6 +461,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return link_handle(s, p, id, si, ai, out, pos);
|
||||
}
|
||||
let independent = switch_or(p, "independent", false, "path.setHandle")?;
|
||||
let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?;
|
||||
if symmetric && independent {
|
||||
return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true"));
|
||||
}
|
||||
// The other handle is mirrored only where a segment leaves the anchor on its side: at an open
|
||||
// end the handle moves as it would without `symmetric`.
|
||||
let symmetric = symmetric && has_segment(s, id, si, ai, !out)?;
|
||||
let at = match p.get("at").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?),
|
||||
@@ -472,6 +479,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& at.is_none_or(|to| to == a.p)
|
||||
&& (if out { a.h_out } else { a.h_in }) == pos
|
||||
&& !(independent && a.kind != AnchorKind::Corner)
|
||||
&& (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p))
|
||||
{
|
||||
return ok();
|
||||
}
|
||||
@@ -504,6 +512,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
a.set_handle(out, pos, independent);
|
||||
}
|
||||
if symmetric {
|
||||
let opposite = a.p - (pos - a.p);
|
||||
if out { a.h_in = opposite } else { a.h_out = opposite }
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
@@ -519,6 +531,9 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
|
||||
if switch_or(p, "independent", false, C)? {
|
||||
return Err(bad(C, "`link` and `independent` cannot both be true"));
|
||||
}
|
||||
if switch_or(p, "symmetric", false, C)? {
|
||||
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
|
||||
}
|
||||
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
@@ -655,6 +670,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anc
|
||||
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
|
||||
}
|
||||
|
||||
/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or
|
||||
/// incoming side; false when the path, subpath or anchor is not there.
|
||||
fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result<bool> {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
|
||||
}
|
||||
|
||||
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?;
|
||||
let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?;
|
||||
|
||||
@@ -685,14 +685,21 @@ fn pf_label(op: PathfinderOp) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
|
||||
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
|
||||
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
|
||||
/// The Pathfinder Options in the preferences, as the panel's operations and a new Pathfinder effect
|
||||
/// take them.
|
||||
pub(crate) fn current_pf_options(s: &Session) -> PathfinderOptions {
|
||||
let mut stored = s.prefs.pathfinder;
|
||||
if !PATHFINDER_PRECISION_RANGE.contains(&stored.precision) {
|
||||
// A preferences file edited by hand: the default, rather than refitting everything away.
|
||||
stored.precision = po::DEFAULT_PRECISION;
|
||||
}
|
||||
stored
|
||||
}
|
||||
|
||||
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
|
||||
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
|
||||
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
|
||||
let stored = current_pf_options(s);
|
||||
let keys = ["precision", "removeRedundantPoints", "removeUnpainted"];
|
||||
let given: serde_json::Map<String, Value> =
|
||||
p.as_object().into_iter().flatten().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
|
||||
@@ -630,19 +630,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
|
||||
/// its file's clipping path or not (`new_image`); other objects keep their centre.
|
||||
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
|
||||
// An image alone in a clip group (as a PSD or PSB file's clipping path places it,
|
||||
// [`fileio::file_clipped`]) is measured as the image when the new art is an image; a DCS
|
||||
// file's plates are not.
|
||||
let image = match &old.kind {
|
||||
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
|
||||
[path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
|
||||
NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
};
|
||||
let image = replace_measured(d, old, new_image);
|
||||
if image_xf && let NodeKind::Image(im) = &image.kind {
|
||||
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
|
||||
let full = Affine::scale_non_uniform(sx, sy);
|
||||
@@ -655,6 +643,22 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
|
||||
Affine::translate(c - natural.center())
|
||||
}
|
||||
|
||||
/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
|
||||
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
|
||||
/// image (`new_image`), except a DCS file's plates; else `old` itself.
|
||||
fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
|
||||
match &old.kind {
|
||||
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
|
||||
[path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
|
||||
NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
}
|
||||
}
|
||||
|
||||
/// `rect` fitted with `natural`'s aspect, centred.
|
||||
fn fit(natural: Rect, r: Rect) -> Affine {
|
||||
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
|
||||
@@ -814,6 +818,17 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
|
||||
}
|
||||
let natural = loaded.natural;
|
||||
// Replace keeps the transform of the image it measures (`replace_measured`), which a
|
||||
// distortion's corners do not follow. Type, and any other object it measures, is placed by the
|
||||
// bounds of what it replaces, so a distorted image there is not refused.
|
||||
if let Some(o) = old_node
|
||||
&& !is_text
|
||||
{
|
||||
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
|
||||
if image.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(PLACE, image.id));
|
||||
}
|
||||
}
|
||||
let m = match (old_node, rect) {
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
|
||||
(None, Some(r)) => fit(natural, r),
|
||||
@@ -1173,6 +1188,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = super::links::with_brush_art(&st.doc);
|
||||
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution, taken at the middle of a distorted image.
|
||||
let ppi = effective_ppi(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf));
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
|
||||
let doc_path = super::links::LinkBase::of(st).doc;
|
||||
@@ -1184,7 +1201,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
|
||||
"pixelWidth": im.width,
|
||||
"pixelHeight": im.height,
|
||||
"ppi": effective_ppi(im.xf),
|
||||
"ppi": ppi,
|
||||
"width": size.width(),
|
||||
"height": size.height(),
|
||||
}))
|
||||
|
||||
@@ -746,5 +746,7 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"stroke.arrowheads.edit",
|
||||
"stroke.arrowheads.list",
|
||||
"text.similarFonts",
|
||||
"threeD.bevels.edit",
|
||||
"threeD.bevels.list",
|
||||
"type.compositeFonts.set",
|
||||
];
|
||||
|
||||
@@ -404,6 +404,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
"Update Links",
|
||||
choice(&[("automatically", "Automatically"), ("manually", "Manually"), ("askWhenModified", "Ask When Modified")])
|
||||
),
|
||||
p!("pdfTextAs", "File Handling", "Files", "PDF Text", choice(&[("text", "Editable"), ("outlines", "Outlines")])),
|
||||
// Clipboard Handling
|
||||
p!("copyAsSvg", "Clipboard Handling", "On Copy", "Include SVG Code", bool),
|
||||
p!("copyAsPdf", "Clipboard Handling", "On Copy", "PDF", bool),
|
||||
@@ -752,6 +753,13 @@ impl Session {
|
||||
t.set_option("cornerRadius", &r);
|
||||
}
|
||||
}
|
||||
// A press of the tool that is dropped keeps the new radius, also when the tool lent a
|
||||
// selection tool for the press.
|
||||
if self.press_taken_by("roundedRectangle")
|
||||
&& let Some((_, saved)) = self.press_options.as_mut()
|
||||
{
|
||||
saved.insert("cornerRadius".into(), r);
|
||||
}
|
||||
}
|
||||
if fonts_folder_changed {
|
||||
let folder = self.prefs.fonts_folder.trim();
|
||||
|
||||
@@ -455,6 +455,10 @@ fn places(map: Affine) -> bool {
|
||||
/// member).
|
||||
pub(crate) fn replace_with_image(mut v: Node, image: Node) -> Node {
|
||||
if !v.is_layer() {
|
||||
// The new pixels already show a distorted image's distortion.
|
||||
if let Some(e) = v.extras_if_any() {
|
||||
e.image_quad = None;
|
||||
}
|
||||
return Node { kind: image.kind, appearance: Default::default(), ..v };
|
||||
}
|
||||
v.appearance = Default::default();
|
||||
|
||||
@@ -130,7 +130,8 @@ type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule);
|
||||
#[derive(Clone)]
|
||||
struct ImageRead<'a> {
|
||||
blob: &'a vectorcraft_doc::ImageBlob,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
/// Pixel space to the page: the image's transform, or a distorted image's projective map.
|
||||
map: vectorcraft_geom::Homography,
|
||||
size: (f64, f64),
|
||||
area: Option<Rect>,
|
||||
clip: Option<Vec<Region>>,
|
||||
@@ -261,9 +262,9 @@ impl<'a> Theme<'a> {
|
||||
let keeps: Vec<Box<dyn Fn(f64, f64) -> bool + '_>> = group
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let (xf, (w, h), area, clip, cost, tested) = (r.xf, r.size, r.area, &r.clip, elements(r), &tested);
|
||||
let (map, (w, h), area, clip, cost, tested) = (r.map, r.size, r.area, &r.clip, elements(r), &tested);
|
||||
Box::new(move |u: f64, v: f64| {
|
||||
let p = xf * Point::new(u * w, v * h);
|
||||
let Some(p) = map.apply(Point::new(u * w, v * h)) else { return false };
|
||||
area.is_none_or(|a| a.contains(p))
|
||||
&& clip.as_ref().is_none_or(|rs| {
|
||||
tested.set(tested.get().saturating_add(cost));
|
||||
@@ -278,7 +279,7 @@ impl<'a> Theme<'a> {
|
||||
.map(|(r, keep)| {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let (w, h) = r.size;
|
||||
let inv = r.xf.inverse();
|
||||
let inv = r.map.inverse();
|
||||
// The box sampled: the marquee, cut to the clipping paths' bounds, so a small
|
||||
// region a clip shows of a large image is still sampled densely.
|
||||
let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default());
|
||||
@@ -286,12 +287,16 @@ impl<'a> Theme<'a> {
|
||||
(Some(a), Some(c)) => Some(a.intersect(c)),
|
||||
(a, c) => a.or(c),
|
||||
};
|
||||
let box_uv = region.map(|a| {
|
||||
let uv: Vec<Point> =
|
||||
[(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect();
|
||||
// A region that crosses a distorted image's horizon has no box: the whole
|
||||
// image is sampled, and `keep` tests each pixel.
|
||||
let box_uv = region.zip(inv).and_then(|(a, inv)| {
|
||||
let uv: Vec<Point> = [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)]
|
||||
.into_iter()
|
||||
.map(|(x, y)| inv.apply(Point::new(x, y)))
|
||||
.collect::<Option<_>>()?;
|
||||
let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min);
|
||||
let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max);
|
||||
[low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h]
|
||||
Some([low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h])
|
||||
});
|
||||
(box_uv, if r.clip.is_some() { clipped } else { budget }, keep.as_ref())
|
||||
})
|
||||
@@ -401,7 +406,9 @@ impl<'a> Theme<'a> {
|
||||
None
|
||||
};
|
||||
let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
|
||||
self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize });
|
||||
// A distorted image's pixels are where its projective map puts them.
|
||||
let map = n.image_map().unwrap_or_else(|| vectorcraft_geom::Homography::from_affine(im.xf));
|
||||
self.queue_image(ImageRead { blob, map, size, area, clip: self.clip.clone(), colorize });
|
||||
return;
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
@@ -2051,7 +2058,14 @@ mod tests {
|
||||
bp.line_to((size, size));
|
||||
bp.line_to((0.0, size));
|
||||
bp.close_path();
|
||||
ImageRead { blob, xf: Affine::IDENTITY, size: (size, size), area: None, clip: Some(vec![(bp, FillRule::NonZero)]), colorize: None }
|
||||
ImageRead {
|
||||
blob,
|
||||
map: vectorcraft_geom::Homography::from_affine(Affine::IDENTITY),
|
||||
size: (size, size),
|
||||
area: None,
|
||||
clip: Some(vec![(bp, FillRule::NonZero)]),
|
||||
colorize: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The reads of one image inside clip groups share the work limit: three reads of a 64 px
|
||||
|
||||
+740
-37
@@ -10,9 +10,11 @@
|
||||
//! path, inside groups too) is compared with the glyphs of the candidate fonts
|
||||
//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched
|
||||
//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object
|
||||
//! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as
|
||||
//! they are and are reported. Near matches (another version of the font, simplified outlines,
|
||||
//! merged glyphs) and images are phase 2.
|
||||
//! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced
|
||||
//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading
|
||||
//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). Shapes
|
||||
//! that match no font stay as they are and are reported. Near matches (another version of the
|
||||
//! font, simplified outlines, merged glyphs) and images are phase 2.
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
use std::sync::Arc;
|
||||
@@ -39,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Retype",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
has_selected_path,
|
||||
retype
|
||||
)]
|
||||
@@ -163,8 +165,11 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vecto
|
||||
}
|
||||
|
||||
/// One line of retyped glyphs.
|
||||
#[derive(Clone)]
|
||||
struct Line {
|
||||
pieces: Vec<NodeId>,
|
||||
/// Tracking in 1/1000 em, added after each character, spaces included.
|
||||
tracking: f64,
|
||||
/// What each piece matched, as `pieces`.
|
||||
matches: Vec<GlyphMatch>,
|
||||
/// Every glyph the first piece fits, while the line holds only it: the next glyph may tell
|
||||
@@ -204,16 +209,53 @@ impl Line {
|
||||
// Wrapped: type turned 180° has angles near +π and −π.
|
||||
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
&& across < size * 0.05
|
||||
&& (m.origin - self.end).dot(dir) > -size * 0.25
|
||||
// After the line's end, or, for type tracked tighter than that, still ahead of the
|
||||
// last glyph's start (by more than rounding); the layout check decides whether it fits.
|
||||
&& ((m.origin - self.end).dot(dir) > -size * 0.25
|
||||
|| self.matches.last().is_some_and(|last| (m.origin - last.origin).dot(dir) > size * 1e-3))
|
||||
}
|
||||
|
||||
fn size(&self) -> f64 {
|
||||
self.scale * self.face.units_per_em()
|
||||
}
|
||||
|
||||
/// The shapes of the one-contour glyphs that stand alone on this line: neither the glyph before
|
||||
/// nor the one after continues it by starting after the end of the glyph before it. A glyph
|
||||
/// that joined the line only through the tight-tracking test counts as alone. A line of three
|
||||
/// glyphs or more is type (its tracking can be read), so none of its glyphs is alone.
|
||||
fn lone_one_contour(&self) -> Vec<NodeId> {
|
||||
if self.matches.len() >= 3 {
|
||||
return vec![];
|
||||
}
|
||||
let dir = self.dir();
|
||||
let size = self.size();
|
||||
// Does glyph `k` start after the end of the glyph before it, less a quarter em?
|
||||
let after_previous = |k: usize| match (k.checked_sub(1).and_then(|j| self.matches.get(j)), self.matches.get(k)) {
|
||||
(Some(a), Some(b)) => (b.origin - (a.origin + dir * (a.face.advance(a.gid) * a.scale))).dot(dir) > -size * 0.25,
|
||||
_ => false,
|
||||
};
|
||||
let n = self.matches.len();
|
||||
(0..n)
|
||||
.filter(|&k| !after_previous(k) && !after_previous(k + 1))
|
||||
.filter_map(|k| self.matches.get(k).filter(|m| m.contours == 1).and_then(|_| self.pieces.get(k).copied()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The line's tracking in points.
|
||||
fn tracking_pt(&self) -> f64 {
|
||||
self.tracking * self.size() / 1000.0
|
||||
}
|
||||
|
||||
fn push(&mut self, id: NodeId, m: &GlyphMatch) {
|
||||
// A gap wider than half a space before the glyph is spaces the outlines left no shape for.
|
||||
// A gap, past the tracking, wider than half a space before the glyph is spaces the
|
||||
// outlines left no shape for. Each space takes the tracking too.
|
||||
let dir = self.dir();
|
||||
let gap = (m.origin - self.end).dot(dir);
|
||||
let space = space_advance(&self.face) * self.scale;
|
||||
if space > 0.0 && gap > space * 0.5 {
|
||||
let n = ((gap / space).round() as usize).clamp(1, 64);
|
||||
let gap = (m.origin - self.end).dot(dir) - self.tracking_pt();
|
||||
// Tracking tighter than a space's width gives each space a negative advance.
|
||||
let space = space_advance(&self.face) * self.scale + self.tracking_pt();
|
||||
let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 };
|
||||
if spaces.is_finite() && spaces > 0.5 {
|
||||
let n = (spaces.round() as usize).clamp(1, 64);
|
||||
self.text.extend(std::iter::repeat_n(' ', n));
|
||||
}
|
||||
self.text.push(m.ch);
|
||||
@@ -222,13 +264,49 @@ impl Line {
|
||||
self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale);
|
||||
}
|
||||
|
||||
/// The line of this one's glyphs `from..to`, with its group, paint and transparency.
|
||||
/// The line of this one's glyphs `from..to`, with its group, paint, transparency, tracking and
|
||||
/// the spaces between those glyphs.
|
||||
fn part(&self, from: usize, to: usize) -> Option<Line> {
|
||||
let mut text = String::new();
|
||||
let mut glyph = 0usize;
|
||||
for c in self.text.chars() {
|
||||
// The text after glyph `to - 1` is not read.
|
||||
if glyph >= to {
|
||||
break;
|
||||
}
|
||||
if c == ' ' {
|
||||
// Spaces before glyph `glyph`, after glyph `glyph - 1`.
|
||||
if glyph > from {
|
||||
text.push(c);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if glyph >= from {
|
||||
text.push(c);
|
||||
}
|
||||
glyph += 1;
|
||||
}
|
||||
if glyph != to || to > self.matches.len() {
|
||||
return self.respaced(from, to, self.tracking);
|
||||
}
|
||||
let mut l = self.respaced(from, to.min(from.saturating_add(1)), self.tracking)?;
|
||||
l.pieces = self.pieces.get(from..to)?.to_vec();
|
||||
l.matches = self.matches.get(from..to)?.to_vec();
|
||||
let last = l.matches.last()?;
|
||||
l.end = last.origin + l.dir() * (last.face.advance(last.gid) * last.scale);
|
||||
l.text = text;
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// The line of this one's glyphs `from..to` at `tracking`, with its group, paint and
|
||||
/// transparency, its spaces read again from the gaps at that tracking.
|
||||
fn respaced(&self, from: usize, to: usize, tracking: f64) -> Option<Line> {
|
||||
let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?);
|
||||
let (first, m) = (ids.first()?, ms.first()?);
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
let mut l = Line {
|
||||
pieces: vec![*first],
|
||||
tracking,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: vec![],
|
||||
text: m.ch.to_string(),
|
||||
@@ -248,8 +326,8 @@ impl Line {
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// The point type that sets this line.
|
||||
fn text_object(&self, system_layout: bool) -> TextObject {
|
||||
/// The point type that sets this line, not yet laid out (for a layout check).
|
||||
fn probe(&self, system_layout: bool) -> TextObject {
|
||||
let style = CharStyle {
|
||||
font_family: self.face.family.clone(),
|
||||
font_style: self.face.style.clone(),
|
||||
@@ -258,6 +336,7 @@ impl Line {
|
||||
// Each outlined glyph was drawn on its own; a ligature would draw another shape.
|
||||
features: vec!["-liga".into()],
|
||||
size: self.scale * self.face.units_per_em(),
|
||||
tracking: self.tracking,
|
||||
fill: self.appearance.fill_paint(),
|
||||
stroke: self.appearance.stroke_paint(),
|
||||
stroke_width: self.appearance.stroke_width(),
|
||||
@@ -277,6 +356,12 @@ impl Line {
|
||||
}
|
||||
t.para = super::create::new_type_para();
|
||||
t.system_layout = system_layout;
|
||||
t
|
||||
}
|
||||
|
||||
/// The point type that sets this line, laid out and measured.
|
||||
fn text_object(&self, system_layout: bool) -> TextObject {
|
||||
let mut t = self.probe(system_layout);
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
t
|
||||
}
|
||||
@@ -285,27 +370,262 @@ impl Line {
|
||||
/// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(&self, t: &TextObject) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01);
|
||||
for (k, m) in self.matches.iter().enumerate() {
|
||||
let Some(g) = drawn.next() else { return Some(k) };
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
|
||||
return Some(k);
|
||||
first_mismatch(t, &self.matches, self.size())
|
||||
}
|
||||
|
||||
/// Along the line, where its first glyph starts and its last glyph's advance ends, from
|
||||
/// `from` (the tracking after the last glyph left out).
|
||||
fn span_from(&self, from: Point) -> (f64, f64) {
|
||||
let dir = self.dir();
|
||||
let last = self.matches.last().map_or(self.end, |m| m.origin + dir * (m.face.advance(m.gid) * m.scale));
|
||||
((self.origin - from).dot(dir), (last - from).dot(dir))
|
||||
}
|
||||
|
||||
/// This line with the tracking its glyphs are spaced by, when it has at least three glyphs.
|
||||
/// The glyphs are laid out untracked and without spaces, so each gap's extra is how much
|
||||
/// further apart the outlines are than the font's advances and pair kerning set them; a gap
|
||||
/// read as word spaces is measured from the glyph's own advance instead, as no pair kerning
|
||||
/// crosses a space. The extra most gaps share (the lower median, so that the word spaces of a
|
||||
/// few gaps do not count) places the word spaces; the tracking is then the lower median, over
|
||||
/// the gaps, of each gap's extra less its spaces, per character. The upper median of the
|
||||
/// extras is tried next, for a line whose word spaces are its tighter gaps, and last the lower
|
||||
/// median less one space, halved, for a line most of whose gaps hold a word space. A tracking within
|
||||
/// 0.05 of a whole number is tried rounded to it first, then as measured. A tracked line is
|
||||
/// kept when its type draws the whole line in place, or more of it from its start than
|
||||
/// untracked type does. When untracked type with the spaces also draws the whole line, the line stays
|
||||
/// untracked if the tracking is under one unit or the tracked reading drops a gap untracked
|
||||
/// type reads as one space. The line also stays as it is when its tracking is 0 or outside
|
||||
/// -1000..10000, and when its tracking is negative and the line does not paint the same as one
|
||||
/// object ([`paints_as_one`]: its glyphs may overlap). Each of the nine layouts at most takes
|
||||
/// its characters, spaces included, from `budget` before it runs; without enough left, the
|
||||
/// line stays as it is, or becomes the best tracked reading laid out before the budget ran out.
|
||||
fn tracked(self, system_layout: bool, budget: &mut usize) -> Line {
|
||||
let size = self.size();
|
||||
let n = self.pieces.len();
|
||||
if n < 3 || size <= 0.0 {
|
||||
return self;
|
||||
}
|
||||
// Each layout takes its characters, spaces included, from `budget` before it runs.
|
||||
let mut take = |text: &str| match budget.checked_sub(text.chars().count()) {
|
||||
Some(left) => {
|
||||
*budget = left;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if !take(&self.text) {
|
||||
return self;
|
||||
}
|
||||
let plain_miss = self.first_mismatch(&self.probe(system_layout));
|
||||
let dir = self.dir();
|
||||
// Where untracked type draws the glyphs of `text` (each layout dropped once read).
|
||||
let mut bare = self.clone();
|
||||
bare.tracking = 0.0;
|
||||
let mut origins = |text: String| -> Vec<Point> {
|
||||
bare.text = text;
|
||||
let t = bare.probe(system_layout);
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect()
|
||||
};
|
||||
// With no spaces.
|
||||
let joined: String = self.matches.iter().map(|m| m.ch).collect();
|
||||
if !take(&joined) {
|
||||
return self;
|
||||
}
|
||||
let drawn = origins(joined);
|
||||
if drawn.len() != n {
|
||||
return self;
|
||||
}
|
||||
// And with one space between each two glyphs (kerning against the space included).
|
||||
let spaced = self.matches.iter().map(|m| m.ch.to_string()).collect::<Vec<_>>().join(" ");
|
||||
if !take(&spaced) {
|
||||
return self;
|
||||
}
|
||||
let drawn_spaced = origins(spaced);
|
||||
// A font whose space has ink draws more glyphs: then the glyph's own advance stands in.
|
||||
let spaced_ok = drawn_spaced.len() == n;
|
||||
let space = space_advance(&self.face) * self.scale;
|
||||
// Each gap's extra over the joined pair, and over the pair with one space between them
|
||||
// plus a space (so the extra counts the spaces as the joined pair's extra counts none).
|
||||
let gaps: Vec<(f64, f64)> = self
|
||||
.matches
|
||||
.windows(2)
|
||||
.enumerate()
|
||||
.zip(drawn.windows(2))
|
||||
.filter_map(|((i, m), p)| match (m, p) {
|
||||
([a, b], [pa, pb]) => {
|
||||
let d = (b.origin - a.origin).dot(dir);
|
||||
let apart = match (spaced_ok, drawn_spaced.get(i), drawn_spaced.get(i + 1)) {
|
||||
(true, Some(qa), Some(qb)) => d - (*qb - *qa).dot(dir) + space,
|
||||
_ => d - a.face.advance(a.gid) * a.scale,
|
||||
};
|
||||
Some((d - (*pb - *pa).dot(dir), apart))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let extra: Vec<f64> = gaps.iter().map(|g| g.0).collect();
|
||||
// The spaces in each gap at a tracking of `tr` points: each space takes the tracking too,
|
||||
// and tracking tighter than a space's width gives it a negative advance. A gap reads as
|
||||
// spaces when they fit it better than the joined pair does.
|
||||
let spaces = |tr: f64| -> Vec<usize> {
|
||||
gaps.iter()
|
||||
.map(|(joined, apart)| {
|
||||
let step = space + tr;
|
||||
// Spaces with no advance: one space, which still breaks the pair's kerning.
|
||||
let s = if step.abs() > 1e-9 { (apart - tr) / step } else { 1.0 };
|
||||
if !s.is_finite() {
|
||||
return 0;
|
||||
}
|
||||
// At least one space: the space's own kerning can make it fit a narrower gap.
|
||||
let k = (s.round().max(1.0) as usize).clamp(1, 64);
|
||||
// Spaces only where they fit better by more than rounding (1/100,000 em).
|
||||
if (apart - tr - k as f64 * step).abs() + size * 1e-5 < (joined - tr).abs() { k } else { 0 }
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The tracking the gaps give when the word spaces are placed by `seed`.
|
||||
let measure = |seed: f64| -> Option<f64> {
|
||||
let per: Vec<f64> = gaps
|
||||
.iter()
|
||||
.zip(spaces(seed))
|
||||
.map(|((joined, apart), s)| if s == 0 { *joined } else { (apart - s as f64 * space) / (s + 1) as f64 })
|
||||
.collect();
|
||||
median(per, false).map(|g| g / size * 1000.0)
|
||||
};
|
||||
// The lower median of the extras places the word spaces first; the upper one second, for a
|
||||
// line whose word spaces are its tighter gaps (tracking tighter than a space).
|
||||
let lower = median(extra.clone(), false);
|
||||
// A line whose word gaps are most of its gaps has a space and two trackings in each extra
|
||||
// (tracking is added after the glyph and after the space): the seed then places the spaces
|
||||
// from the extra less one space, shared by the two. It goes last, so a reading that fits
|
||||
// without it is kept (an untracked "a b c" has no such tracking).
|
||||
// Where untracked type already draws the whole line, a space and a tracking of half its
|
||||
// advance less draw it too: that reading is not tried.
|
||||
let spaced_seed = lower.filter(|_| plain_miss.is_some()).map(|e| (e - space) / 2.0);
|
||||
let mut tries = vec![];
|
||||
for seed in [lower, median(extra, true), spaced_seed].into_iter().flatten() {
|
||||
let Some(measured) = measure(seed) else { continue };
|
||||
for t in [round_tracking(measured), measured] {
|
||||
if !tries.contains(&t) {
|
||||
tries.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| self.matches.len().saturating_sub(1))
|
||||
// The spaces in each gap of the line as it is (the reading `plain_miss` checked).
|
||||
let mut plain_gaps = vec![];
|
||||
let mut run = 0usize;
|
||||
for (i, c) in self.text.chars().enumerate() {
|
||||
if c == ' ' {
|
||||
run += 1;
|
||||
} else {
|
||||
if i > 0 {
|
||||
plain_gaps.push(run);
|
||||
}
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
let mut best: Option<(usize, Line)> = None;
|
||||
for t in tries {
|
||||
if t == 0.0 || !TRACKING.contains(&t) {
|
||||
continue;
|
||||
}
|
||||
if t < 0.0 && !paints_as_one(&self) {
|
||||
return self;
|
||||
}
|
||||
let mut tracked = self.clone();
|
||||
tracked.tracking = t;
|
||||
tracked.text = String::new();
|
||||
let gaps = spaces(t * size / 1000.0);
|
||||
for (k, (m, s)) in self.matches.iter().zip(std::iter::once(0).chain(gaps.iter().copied())).enumerate() {
|
||||
if k > 0 {
|
||||
tracked.text.extend(std::iter::repeat_n(' ', s));
|
||||
}
|
||||
tracked.text.push(m.ch);
|
||||
}
|
||||
// A reading the budget cannot lay out is skipped; the next may be shorter.
|
||||
if !take(&tracked.text) {
|
||||
continue;
|
||||
}
|
||||
// When both draw the whole line (gaps as wide as whole spaces), the tracked reading is
|
||||
// kept unless it drops a gap that untracked type reads as one space: such a gap is a
|
||||
// word space ("a b c"), and the line keeps its spaces.
|
||||
let drops_a_word_space = plain_gaps.iter().zip(&gaps).any(|(plain, tracked)| *plain == 1 && *tracked == 0);
|
||||
match (tracked.first_mismatch(&tracked.probe(system_layout)), plain_miss) {
|
||||
// Under a unit of tracking, or a word space the tracked reading drops, where
|
||||
// untracked type draws the line: no tracking.
|
||||
(None, None) if t.abs() < 1.0 || drops_a_word_space => return self,
|
||||
(None, _) => return tracked,
|
||||
(Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
best.map_or(self, |(_, l)| l)
|
||||
}
|
||||
}
|
||||
|
||||
/// Does line `l` paint the same as one object as glyph by glyph where its glyphs overlap: opaque,
|
||||
/// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and
|
||||
/// blend once, spans a gradient over all of it, and strokes after filling every glyph.
|
||||
fn paints_as_one(l: &Line) -> bool {
|
||||
l.opacity == 1.0
|
||||
&& l.blend == vectorcraft_color::BlendMode::Normal
|
||||
&& matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
|
||||
&& matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None)
|
||||
}
|
||||
|
||||
/// The tracking Retype sets, in 1/1000 em.
|
||||
const TRACKING: std::ops::RangeInclusive<f64> = -1000.0..=10000.0;
|
||||
|
||||
/// The lower median of the finite values of `v`, or the upper one when `upper`; None for fewer
|
||||
/// than two.
|
||||
fn median(mut v: Vec<f64>, upper: bool) -> Option<f64> {
|
||||
v.retain(|x| x.is_finite());
|
||||
if v.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.get(if upper { v.len() / 2 } else { (v.len() - 1) / 2 }).copied()
|
||||
}
|
||||
|
||||
/// Tracking `t` rounded to a whole number when it is within 0.05 of one.
|
||||
fn round_tracking(t: f64) -> f64 {
|
||||
if (t - t.round()).abs() < 0.05 { t.round() } else { t }
|
||||
}
|
||||
|
||||
/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another
|
||||
/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
let tol = (size * 0.01).max(0.01);
|
||||
for (k, m) in matches.iter().enumerate() {
|
||||
let Some(g) = drawn.next() else { return Some(k) };
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
|
||||
return Some(k);
|
||||
}
|
||||
}
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| matches.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
/// `lines` checked against their own layout: a line splits where its type stops drawing the
|
||||
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
|
||||
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
|
||||
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
|
||||
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
|
||||
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
|
||||
// Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot
|
||||
// leave glyphs unchecked; past it they keep no tracking. Each measure takes the glyphs to
|
||||
// rebuild the rest and the characters it lays out (see [`Line::tracked`]); the budget covers
|
||||
// one measure of each whole line, as `retype` gives the first, and the glyph checks' budget.
|
||||
// The glyphs measured again after splits are limited apart from it, at six times each rest's
|
||||
// glyphs from half as much again as the glyph checks' budget.
|
||||
let mut remeasured = budget.saturating_add(budget / 2);
|
||||
let mut track_budget =
|
||||
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(394))).fold(budget, usize::saturating_add);
|
||||
let mut todo: std::collections::VecDeque<Line> = lines.into();
|
||||
let mut out = vec![];
|
||||
while let Some(l) = todo.pop_front() {
|
||||
@@ -323,28 +643,58 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
|
||||
break;
|
||||
};
|
||||
budget = left;
|
||||
match part.first_mismatch(&part.text_object(system_layout)) {
|
||||
match part.first_mismatch(&part.probe(system_layout)) {
|
||||
// The whole line is drawn as it was: one object.
|
||||
None if e == n => {
|
||||
out.push(part);
|
||||
break;
|
||||
}
|
||||
None => w = w.saturating_mul(2),
|
||||
// The first glyph on its own may still be drawn as it was (a contextual form
|
||||
// changed it in the line); else it stays an outline. Checked again either way.
|
||||
Some(0) if n > 1 => {
|
||||
todo.extend_front_parts(&l, [(0, 1), (1, n)]);
|
||||
// Tracking that type does not set as the outlines are spaced: the line is
|
||||
// checked again without it.
|
||||
Some(k) if l.tracking != 0.0 && k < 2 => {
|
||||
match l.respaced(0, n, 0.0) {
|
||||
Some(p) => todo.push_front(p),
|
||||
None => unmatched.extend(l.pieces.iter().copied()),
|
||||
}
|
||||
break;
|
||||
}
|
||||
Some(0) => {
|
||||
// A single glyph its type cannot draw as it was stays an outline.
|
||||
Some(0) if n == 1 => {
|
||||
unmatched.extend(l.pieces.first().copied());
|
||||
break;
|
||||
}
|
||||
// The glyphs before the mismatch, then the rest, each checked as a line of its
|
||||
// own: the type before the mismatch may draw otherwise without what follows it (a
|
||||
// font can place a glyph by the glyph after it).
|
||||
// font can place a glyph by the glyph after it), and the first glyph on its own
|
||||
// may still be drawn as it was (a contextual form changed it in the line). The
|
||||
// rest takes the tracking its own glyphs are spaced by, while the budget for
|
||||
// measuring it lasts and when type draws its first glyph as it was, followed by the
|
||||
// next two (else that glyph splits off first, and the tracking is measured from the
|
||||
// next one); past it, an untracked line's rest keeps its text as it is.
|
||||
Some(k) => {
|
||||
todo.extend_front_parts(&l, [(0, k), (k, n)]);
|
||||
let k = k.max(1);
|
||||
// A measure takes at least six times the rest's glyphs from each budget.
|
||||
let measurable = n - k >= 3 && remeasured >= (n - k).saturating_mul(6) && track_budget >= (n - k).saturating_mul(6);
|
||||
let first_drawn = measurable && {
|
||||
budget = budget.saturating_sub(3);
|
||||
l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0))
|
||||
};
|
||||
let rest = if first_drawn {
|
||||
// Rebuilding the rest for the measure takes its glyphs from the budget.
|
||||
remeasured = remeasured.saturating_sub((n - k).saturating_mul(6));
|
||||
track_budget = track_budget.saturating_sub(n - k);
|
||||
l.respaced(k, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget))
|
||||
} else if l.tracking == 0.0 {
|
||||
l.part(k, n)
|
||||
} else {
|
||||
l.respaced(k, n, 0.0)
|
||||
};
|
||||
match rest {
|
||||
Some(r) => todo.push_front(r),
|
||||
None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()),
|
||||
}
|
||||
todo.extend_front_parts(&l, [(0, k)]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -353,6 +703,290 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
|
||||
out
|
||||
}
|
||||
|
||||
/// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes
|
||||
/// of the area type on the layers Retype changes
|
||||
/// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type.
|
||||
const MAX_WRAP_WORK: usize = 2_000_000;
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn max_wrap_work() -> usize {
|
||||
MAX_WRAP_WORK
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// [`MAX_WRAP_WORK`], lowered by tests on their own thread.
|
||||
static WRAP_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_WRAP_WORK) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn max_wrap_work() -> usize {
|
||||
WRAP_LIMIT.with(|c| c.get())
|
||||
}
|
||||
|
||||
/// Lines farther apart than this many times their size do not join into one object.
|
||||
const MAX_LEADING: f64 = 3.0;
|
||||
|
||||
/// What Retype makes: one type object and the shapes it replaces.
|
||||
struct Made {
|
||||
t: TextObject,
|
||||
/// For area type, the point type that also draws the glyphs in place: the type kept when
|
||||
/// Text Wrap objects above it change the area type's layout.
|
||||
point: Option<TextObject>,
|
||||
/// The glyphs the type must draw, in order.
|
||||
matches: Vec<GlyphMatch>,
|
||||
pieces: Vec<NodeId>,
|
||||
text: String,
|
||||
face: Arc<vectorcraft_text::FontFace>,
|
||||
size: f64,
|
||||
tracking: f64,
|
||||
/// The leading set on the type: None for Auto or a single line.
|
||||
leading: Option<f64>,
|
||||
opacity: f32,
|
||||
blend: vectorcraft_color::BlendMode,
|
||||
}
|
||||
|
||||
impl Made {
|
||||
fn line(l: &Line, system_layout: bool) -> Made {
|
||||
Made {
|
||||
t: l.text_object(system_layout),
|
||||
point: None,
|
||||
matches: l.matches.clone(),
|
||||
pieces: l.pieces.clone(),
|
||||
text: l.text.clone(),
|
||||
face: l.face.clone(),
|
||||
size: l.size(),
|
||||
tracking: l.tracking,
|
||||
leading: None,
|
||||
opacity: l.opacity,
|
||||
blend: l.blend,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The alignments lines can share, in the order one is chosen: their starts, their ends, their
|
||||
/// centers.
|
||||
const ALIGNS: [vectorcraft_doc::Justify; 3] = [vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Right, vectorcraft_doc::Justify::Center];
|
||||
|
||||
/// A run of lines that may become one object: lines after the first, each one leading further
|
||||
/// across, in the same group, paint, transparency, font, size, turn and tracking, lined up alike.
|
||||
struct Block {
|
||||
lines: Vec<Line>,
|
||||
/// The mean distance between baselines, from the first line's to the last line's.
|
||||
leading: f64,
|
||||
/// Which of [`ALIGNS`] every line so far shares.
|
||||
aligns: [bool; 3],
|
||||
/// The tracking of the first line that has one ([`Block::spaced`]).
|
||||
tracking: Option<f64>,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn new(l: Line) -> Block {
|
||||
let tracking = Block::spaced(&l).then_some(l.tracking);
|
||||
Block { lines: vec![l], leading: 0.0, aligns: [true; 3], tracking }
|
||||
}
|
||||
|
||||
/// Does line `l` have a tracking of its own? A line of fewer than three glyphs that kept no
|
||||
/// tracking has no gaps to measure it by ([`Line::tracked`]): it takes the block's.
|
||||
fn spaced(l: &Line) -> bool {
|
||||
l.pieces.len() >= 3 || l.tracking != 0.0
|
||||
}
|
||||
|
||||
/// Add `l` when it continues the block; `l` back when it does not. `follows` tells whether the
|
||||
/// shape `l` starts with comes right after the block's last shape, with nothing between them
|
||||
/// in paint order.
|
||||
fn take(&mut self, l: Line, follows: impl Fn(NodeId, NodeId) -> bool) -> Option<Line> {
|
||||
let (Some(first), Some(prev)) = (self.lines.first(), self.lines.last()) else { return Some(l) };
|
||||
let (Some(a), Some(b)) = (prev.pieces.last(), l.pieces.first()) else { return Some(l) };
|
||||
let size = first.size();
|
||||
let tol = (size * 0.01).max(0.01);
|
||||
let same = follows(*a, *b)
|
||||
&& l.parent == first.parent
|
||||
&& l.appearance == first.appearance
|
||||
&& l.opacity == first.opacity
|
||||
&& l.blend == first.blend
|
||||
&& l.face.id() == first.face.id()
|
||||
&& (l.scale - first.scale).abs() <= first.scale * 1e-4
|
||||
&& ((l.angle - first.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
// The lines' estimates may differ a little; the layout check decides.
|
||||
&& (!Block::spaced(&l) || self.tracking.is_none_or(|t| (l.tracking - t).abs() < 1.0))
|
||||
// Lines whose ink overlaps, or a gradient spanning them, would paint otherwise as one.
|
||||
&& paints_as_one(first);
|
||||
if !same {
|
||||
return Some(l);
|
||||
}
|
||||
// Across the lines, down from the first line's baseline.
|
||||
let across = Vec2::new(-first.angle.sin(), first.angle.cos());
|
||||
let down = (l.origin - first.origin).dot(across);
|
||||
let n = self.lines.len() as f64;
|
||||
// The mean distance between the baselines so far, which this line's must continue.
|
||||
let leading = if self.lines.len() == 1 { down } else { self.leading };
|
||||
// A quarter of the size is the least leading; the outlines' positions are rounded.
|
||||
if !(leading >= size * 0.25 * (1.0 - 1e-6) && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol {
|
||||
return Some(l);
|
||||
}
|
||||
let leading = down / n;
|
||||
let (s0, e0) = first.span_from(first.origin);
|
||||
let (s, e) = l.span_from(first.origin);
|
||||
let fits = [(s - s0).abs() <= tol, (e - e0).abs() <= tol, ((s + e) - (s0 + e0)).abs() * 0.5 <= tol];
|
||||
let aligns = [self.aligns[0] && fits[0], self.aligns[1] && fits[1], self.aligns[2] && fits[2]];
|
||||
if !aligns.contains(&true) {
|
||||
return Some(l);
|
||||
}
|
||||
self.leading = leading;
|
||||
self.aligns = aligns;
|
||||
if self.tracking.is_none() && Block::spaced(&l) {
|
||||
self.tracking = Some(l.tracking);
|
||||
}
|
||||
self.lines.push(l);
|
||||
None
|
||||
}
|
||||
|
||||
/// The block as one area type object when type draws every glyph in its place as area type,
|
||||
/// else as one point type object when that does. When neither does, the lines before the line
|
||||
/// of the first glyph the type moves are made again as a block, and the lines from that one on
|
||||
/// are joined again ([`blocks`]); the first line on its own stays one object. Area type whose
|
||||
/// frame would reach past [`crate::MAX_COORD`] stays point type, and point type whose bounds
|
||||
/// would stays one object per line. Each try takes six times the
|
||||
/// block's glyphs from `budget` (point and area type are each laid out, measured and checked);
|
||||
/// without enough left, each line is one object.
|
||||
fn made(self, system_layout: bool, budget: &mut usize) -> Vec<Made> {
|
||||
let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::<Vec<_>>();
|
||||
let (Some(first), true) = (self.lines.first(), self.lines.len() > 1) else { return single(&self.lines) };
|
||||
let Some(justify) = ALIGNS.iter().zip(self.aligns).find(|(_, ok)| *ok).map(|(j, _)| *j) else { return single(&self.lines) };
|
||||
let glyphs = self.lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add);
|
||||
let Some(left) = budget.checked_sub(glyphs.saturating_mul(6)) else { return single(&self.lines) };
|
||||
*budget = left;
|
||||
let mut all = first.clone();
|
||||
all.tracking = self.tracking.unwrap_or(first.tracking);
|
||||
all.text = self.lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>().join("\n");
|
||||
let mut t = all.probe(system_layout);
|
||||
t.para.justify = justify;
|
||||
let size = first.size();
|
||||
let mut set_leading = None;
|
||||
if let Some(r) = t.runs.first_mut() {
|
||||
// The leading that puts the last baseline where the last line's is: Auto when Auto
|
||||
// does, else the mean distance between baselines, to a thousandth of a point (as
|
||||
// typed leading is) when that still puts the last baseline in place.
|
||||
let gaps = self.lines.len().saturating_sub(1) as f64;
|
||||
let across = Vec2::new(-first.angle.sin(), first.angle.cos());
|
||||
let span = self.lines.last().map_or(0.0, |l| (l.origin - first.origin).dot(across));
|
||||
if (t.para.effective_leading(&r.style) * gaps - span).abs() > size * 1e-4 {
|
||||
let exact = span / gaps;
|
||||
let rounded = (exact * 1000.0).round() / 1000.0;
|
||||
let leading = if ((rounded - exact) * gaps).abs() <= size * 1e-4 { rounded } else { exact };
|
||||
r.style.leading = Some(leading);
|
||||
set_leading = Some(leading);
|
||||
}
|
||||
}
|
||||
let matches: Vec<GlyphMatch> = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect();
|
||||
// Aligned at its end or center, point type starts its first line elsewhere: the type moves
|
||||
// so its first glyph is where the first outline is.
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) {
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
t.xf = kurbo::Affine::translate(m.origin - at) * t.xf;
|
||||
}
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
if let Some(k) = first_mismatch(&t, &matches, size) {
|
||||
// The line that holds glyph `k`.
|
||||
let mut seen = 0usize;
|
||||
let at = self.lines.iter().position(|l| {
|
||||
seen = seen.saturating_add(l.pieces.len());
|
||||
k < seen
|
||||
});
|
||||
let Block { mut lines, leading, aligns, .. } = self;
|
||||
let rest = lines.split_off(at.unwrap_or(0).clamp(1, lines.len()));
|
||||
let mut out = if lines.len() > 1 {
|
||||
let tracking = lines.iter().find(|l| Block::spaced(l)).map(|l| l.tracking);
|
||||
Block { lines, leading, aligns, tracking }.made(system_layout, budget)
|
||||
} else {
|
||||
single(&lines)
|
||||
};
|
||||
// The lines of the rest followed each other in the block.
|
||||
out.extend(blocks(rest, |_, _| true, system_layout, budget));
|
||||
return out;
|
||||
}
|
||||
// The edit is refused when an object's bounds reach past the coordinate limit. A turned
|
||||
// block's box can reach a corner that none of its lines does: the lines then stay apart.
|
||||
let in_range =
|
||||
|t: &TextObject| Node::new(NodeId(0), NodeKind::Text(Box::new(t.clone()))).geometric_bounds().is_none_or(crate::sanity::rect_in_range);
|
||||
if !in_range(&t) {
|
||||
return single(&self.lines);
|
||||
}
|
||||
let mut area = t.clone();
|
||||
super::typemenu::point_to_area(&mut area);
|
||||
let mut point = None;
|
||||
if in_range(&area) && first_mismatch(&area, &matches, size).is_none() {
|
||||
point = Some(std::mem::replace(&mut t, area));
|
||||
}
|
||||
vec![Made {
|
||||
t,
|
||||
point,
|
||||
matches,
|
||||
pieces: self.lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(),
|
||||
text: all.text,
|
||||
face: first.face.clone(),
|
||||
size,
|
||||
tracking: all.tracking,
|
||||
leading: set_leading,
|
||||
opacity: first.opacity,
|
||||
blend: first.blend,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// A line of two untracked glyphs has one gap, too few to measure a tracking by
|
||||
/// ([`Line::tracked`]). It is set at the tracking of the nearest tracked line of the same font,
|
||||
/// size and turn, so the layout check ([`verified`]) tries it as that line is set: the check falls
|
||||
/// back to the line untracked, and then splits it, when the pair is not spaced so. A pair that
|
||||
/// untracked type already draws in place keeps its text, and negative tracking goes only to a pair
|
||||
/// that paints the same as one object ([`paints_as_one`]).
|
||||
fn share_tracking(lines: &mut [Line], system_layout: bool) {
|
||||
for i in 0..lines.len() {
|
||||
let Some(l) = lines.get(i).filter(|l| l.pieces.len() == 2 && l.tracking == 0.0) else { continue };
|
||||
if l.first_mismatch(&l.probe(system_layout)).is_none() {
|
||||
continue;
|
||||
}
|
||||
let like = |o: &Line| {
|
||||
o.tracking != 0.0
|
||||
&& o.parent == l.parent
|
||||
&& o.face.id() == l.face.id()
|
||||
&& (o.scale - l.scale).abs() <= l.scale * 1e-4
|
||||
&& ((o.angle - l.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
};
|
||||
let nearest = lines.iter().enumerate().filter(|(_, o)| like(o)).min_by_key(|(j, _)| j.abs_diff(i)).map(|(_, o)| o.tracking);
|
||||
if let Some(p) = nearest.filter(|t| *t > 0.0 || paints_as_one(l)).and_then(|t| l.respaced(0, 2, t)) {
|
||||
lines[i] = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of
|
||||
/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after
|
||||
/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
|
||||
fn blocks(lines: Vec<Line>, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec<Made> {
|
||||
let mut out = vec![];
|
||||
let mut block: Option<Block> = None;
|
||||
for l in lines {
|
||||
let l = match block.as_mut() {
|
||||
Some(b) => match b.take(l, &follows) {
|
||||
None => continue,
|
||||
Some(l) => l,
|
||||
},
|
||||
None => l,
|
||||
};
|
||||
if let Some(b) = block.take() {
|
||||
out.extend(b.made(system_layout, budget));
|
||||
}
|
||||
block = Some(Block::new(l));
|
||||
}
|
||||
if let Some(b) = block {
|
||||
out.extend(b.made(system_layout, budget));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Puts parts of a line at the front of the work list, in order.
|
||||
trait FrontParts {
|
||||
fn extend_front_parts<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]);
|
||||
@@ -407,6 +1041,7 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Line {
|
||||
pieces: vec![id],
|
||||
tracking: 0.0,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: l.first_cands.clone(),
|
||||
text: m.ch.to_string(),
|
||||
@@ -428,6 +1063,7 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Some(Line {
|
||||
pieces: vec![pc.id],
|
||||
tracking: 0.0,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: cands.to_vec(),
|
||||
text: m.ch.to_string(),
|
||||
@@ -531,8 +1167,15 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is
|
||||
// what was asked for. Lone means alone on its baseline as the outlines lie, before the
|
||||
// layout check splits lines (tracking and manual kerning split them glyph by glyph).
|
||||
let lone_pieces: std::collections::HashSet<NodeId> =
|
||||
lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect();
|
||||
let lone_pieces: std::collections::HashSet<NodeId> = lines.iter().flat_map(Line::lone_one_contour).collect();
|
||||
// Each line's tracking is measured with nine layouts at most: the line as read (its
|
||||
// characters), its glyphs without and with one space between them (three times its
|
||||
// glyphs) and six tracked readings of at most 64 spaces in each gap (390 times its
|
||||
// glyphs), so every line has what its measure can take.
|
||||
let mut budget =
|
||||
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add);
|
||||
let mut lines: Vec<Line> = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
|
||||
share_tracking(&mut lines, system_layout);
|
||||
let mut lines = verified(lines, system_layout, &mut unmatched);
|
||||
if pieces.len() > 1 {
|
||||
lines.retain(|l| {
|
||||
@@ -543,20 +1186,29 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
!lone
|
||||
});
|
||||
}
|
||||
(lines, unmatched, truncated)
|
||||
let at: std::collections::HashMap<NodeId, usize> = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect();
|
||||
let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) {
|
||||
(Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier),
|
||||
_ => false,
|
||||
};
|
||||
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
|
||||
// for small blocks.
|
||||
let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256);
|
||||
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated)
|
||||
};
|
||||
if lines.is_empty() {
|
||||
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
|
||||
}
|
||||
let made = s.edit("Retype", |d, sel| {
|
||||
// The layers as they were, for the Text Wrap check below.
|
||||
let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone());
|
||||
let mut ids = vec![];
|
||||
let mut emptied = vec![];
|
||||
for l in &lines {
|
||||
let Some(first) = l.pieces.first() else { continue };
|
||||
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
|
||||
let t = l.text_object(system_layout);
|
||||
let id = d.alloc_id();
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(t)));
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(l.t.clone())));
|
||||
// The glyphs' own transparency (the group's, kept, still applies over it).
|
||||
node.opacity = l.opacity;
|
||||
node.blend = l.blend;
|
||||
@@ -603,15 +1255,66 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Text Wrap objects above new area type flow it once the edit is done: area type they
|
||||
// would move a glyph of becomes the point type that draws it in place.
|
||||
if let Some(before) = &before {
|
||||
// Worked out on a copy, so the edit's own Text Wrap refresh still sees every other
|
||||
// area type whose wrap changes, and only on the layers this edit changed, as that
|
||||
// refresh is. The copy holds only the changed layers while the work is counted; past
|
||||
// the limit, the new area type is not flowed and all of it becomes its point type.
|
||||
let mut probe = d.clone();
|
||||
let all = std::mem::take(&mut probe.layers);
|
||||
probe.layers = all
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, layer)| {
|
||||
// As resolve_wrap tells an unchanged layer: the same layer at its index first.
|
||||
!(before.layers.get(*i).is_some_and(|b| Arc::ptr_eq(b, layer))
|
||||
|| before.layers.iter().any(|b| b.id == layer.id && Arc::ptr_eq(b, layer)))
|
||||
})
|
||||
.map(|(_, layer)| layer.clone())
|
||||
.collect();
|
||||
let units = vectorcraft_doc::text::wrap_copy_units(&probe);
|
||||
let flowed = units <= max_wrap_work();
|
||||
probe.layers = all;
|
||||
if flowed && units > 0 {
|
||||
vectorcraft_doc::text::resolve_wrap(Some(before), &mut probe);
|
||||
}
|
||||
// With nothing to copy, no area type on those layers has a wrap shape.
|
||||
for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) {
|
||||
let Some(point) = &l.point else { continue };
|
||||
let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue };
|
||||
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
**t = point.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keep: Vec<NodeId> = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect();
|
||||
keep.extend(&ids);
|
||||
sel.set(keep);
|
||||
Ok(ids)
|
||||
})?;
|
||||
let d = &s.doc()?.doc;
|
||||
let area =
|
||||
|id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }));
|
||||
Ok(json!({
|
||||
"ids": made.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
|
||||
"fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::<Vec<_>>(),
|
||||
"fonts": lines
|
||||
.iter()
|
||||
.zip(&made)
|
||||
.map(|(l, id)| json!({
|
||||
"family": l.face.family,
|
||||
"style": l.face.style,
|
||||
"size": l.size,
|
||||
"tracking": l.tracking,
|
||||
"leading": l.leading,
|
||||
"area": area(id),
|
||||
}))
|
||||
.collect::<Vec<_>>(),
|
||||
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"truncated": truncated,
|
||||
}))
|
||||
|
||||
@@ -477,10 +477,10 @@ fn tracked_one_contour_letters_still_become_type() {
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}");
|
||||
assert!(texts.len() > 1, "the tracking splits the line: {r}");
|
||||
assert_eq!(r["texts"], json!([text]), "evenly tracked, the line is one object: {r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
assert_eq!(text_of(&s, r["ids"][0].as_u64().unwrap()).first_style().tracking, 50.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,8 +521,8 @@ fn timing_with_hundreds_of_cjk_outlines() {
|
||||
|
||||
#[test]
|
||||
fn a_long_tracked_line_is_checked_in_time() {
|
||||
// Tracking splits the line at every glyph: the layout check must not lay out the rest of the
|
||||
// line again after each split.
|
||||
// Even tracking is kept on the line; the layout check of a long line must not lay out the rest
|
||||
// of the line again after each window.
|
||||
let text = "abe".repeat(150);
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap();
|
||||
@@ -533,7 +533,706 @@ fn a_long_tracked_line_is_checked_in_time() {
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text);
|
||||
assert_eq!(texts, vec![text], "the whole line is one object: {r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
|
||||
// Two M outlines start 0.3 em apart, closer than the first one's advance: a tight-tracking
|
||||
// line of two, which the layout check splits again. Each is still a lone one-contour glyph.
|
||||
let mut s = session();
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "M", "size": 30}));
|
||||
let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30}));
|
||||
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap();
|
||||
// Nothing is left to retype: both stay outlines, as the lone bar beside art does.
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err();
|
||||
assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}");
|
||||
}
|
||||
|
||||
/// Where type `t` draws each glyph that has ink, in document space.
|
||||
fn glyph_places(t: &TextObject) -> Vec<kurbo::Point> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * kurbo::Point::ORIGIN)).collect()
|
||||
}
|
||||
|
||||
/// Type made with `p` (and `setup` run on its id), outlined and retyped: the original type, and
|
||||
/// Retype's result.
|
||||
fn retyped(s: &mut Session, p: serde_json::Value, setup: &[serde_json::Value]) -> (TextObject, serde_json::Value) {
|
||||
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
|
||||
for q in setup {
|
||||
let mut q = q.clone();
|
||||
q["id"] = json!(id);
|
||||
s.execute("text.setRangeStyle", &q).unwrap();
|
||||
}
|
||||
let before = text_of(s, id);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
(before, s.execute("type.retype", &json!({})).unwrap())
|
||||
}
|
||||
|
||||
fn assert_same_places(a: &TextObject, b: &TextObject) {
|
||||
let (pa, pb) = (glyph_places(a), glyph_places(b));
|
||||
assert_eq!(pa.len(), pb.len());
|
||||
for (x, y) in pa.iter().zip(&pb) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_lines_become_one_area_type_object() {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one\nThird";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(true), "{r}");
|
||||
assert_eq!(r["fonts"][0]["leading"], json!(null), "Auto leading gives the lines' spacing: {r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }));
|
||||
assert_eq!(t.plain_text(), text);
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_a_quarter_of_the_size_apart_join_and_closer_ones_do_not() {
|
||||
// At 20 pt, 5 pt is the least leading that joins lines.
|
||||
// 4.9999999 pt is 5 pt to the rounding of the outlines' positions.
|
||||
for (leading, objects) in [(5.0, 1), (4.9999999, 1), (4.9, 2)] {
|
||||
let mut s = session();
|
||||
let text = "One\nTwo";
|
||||
let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 20}), &[json!({"leading": leading})]);
|
||||
assert_eq!(r["texts"].as_array().unwrap().len(), objects, "{leading}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_glyph_line_takes_the_tracking_of_the_lines_around_it() {
|
||||
let mut s = session();
|
||||
let text = "MMM\nMM\nMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 50})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_keep_their_leading_and_alignment() {
|
||||
for justify in ["left", "center", "right"] {
|
||||
let mut s = session();
|
||||
let text = "Wide first line\nmid\nlast one";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 300, "y": 100, "text": text, "size": 20, "justify": justify}), &[json!({"leading": 31})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{justify}: {r}");
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 31.0, 1e-3), "{justify}: {r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(true), "{justify}: {r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "{justify}");
|
||||
assert_eq!(t.para.justify, before.para.justify, "{justify}");
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_near_auto_leading_keeps_its_own_leading() {
|
||||
// 24.001 pt is Auto's 24 pt within a ten-thousandth of the size per line, but 250 lines
|
||||
// move the last one a quarter of a point.
|
||||
let mut s = session();
|
||||
let text = vec!["ab"; 250].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 24.001})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.001, 1e-4), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_at_auto_leading_of_a_fractional_size_keeps_auto() {
|
||||
// Auto leading of 20.002 pt is 24.0024 pt, finer than the thousandth of a point the leading
|
||||
// between two lines is read to.
|
||||
let mut s = session();
|
||||
// Six hundred lines: read to a thousandth, each gap would be 0.0004 pt short, and the last
|
||||
// line 0.24 pt off.
|
||||
let text = vec!["ab"; 600].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20.002}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert_eq!(r["fonts"][0]["leading"], json!(null), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_at_a_leading_finer_than_a_thousandth_keeps_it() {
|
||||
// 23.9996 pt read to a thousandth is 24 pt, Auto for 20 pt type: over 600 lines the last one
|
||||
// would be 0.24 pt off.
|
||||
let mut s = session();
|
||||
let text = vec!["ab"; 600].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 23.9996})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 23.9996, 1e-6), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_whose_first_gap_is_a_little_off_stays_one_object() {
|
||||
// The second line moved up 0.004 pt: its gap read alone, carried over 100 lines, would put
|
||||
// the last one 0.4 pt off.
|
||||
let mut s = session();
|
||||
let text = ["ab"; 100].join("\n");
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 40, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "leading": 24.004})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let kids = children_of(&s, g);
|
||||
s.execute("select.set", &json!({"ids": kids[2..4]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 0, "dy": -0.004})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.004, 1e-3), "{}", r["fonts"][0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_whose_frame_would_pass_the_coordinate_limit_stay_point_type() {
|
||||
let mut s = session();
|
||||
let text = "Wide line\nWide";
|
||||
let id = s.execute("text.create", &json!({"x": 3_999_000, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
let right = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x1;
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
// The ink ends 2 pt short of the limit; Convert To Area Type's slack would reach past it.
|
||||
s.execute("object.move", &json!({"dx": vectorcraft_doc::MAX_COORD - 2.0 - right, "dy": 0})).unwrap();
|
||||
let before = text_of(&s, id);
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(false), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_type_cannot_join_ends_the_block_there() {
|
||||
// The fourth line keeps a fraction of a unit of tracking that the others do not: joined, it
|
||||
// moves, so the lines before it stay one object and the lines after it join again.
|
||||
let mut s = session();
|
||||
let line = "M".repeat(40);
|
||||
let text = [line.as_str(); 6].join("\n");
|
||||
let start = 3 * 41;
|
||||
let (before, r) =
|
||||
retyped(&mut s, json!({"x": 20, "y": 40, "text": text, "size": 20}), &[json!({"start": start, "end": start + 40, "tracking": 0.6})]);
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.len(), 3, "{texts:?} {}", r["fonts"]);
|
||||
assert_eq!(texts.join("\n"), text);
|
||||
let places: Vec<kurbo::Point> = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect();
|
||||
let want = glyph_places(&before);
|
||||
assert_eq!(places.len(), want.len());
|
||||
for (x, y) in places.iter().zip(&want) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The glyphs of the outline groups `others` moved to the end of group `g`, in order, and the
|
||||
/// emptied groups removed.
|
||||
fn into_one_group(s: &mut Session, g: u64, others: &[u64]) {
|
||||
s.edit("test", |d, _| {
|
||||
for o in others {
|
||||
let kids: Vec<_> = d.node(NodeId(*o)).unwrap().children().unwrap().to_vec();
|
||||
d.remove(NodeId(*o))?;
|
||||
for k in kids {
|
||||
let at = d.node(NodeId(g)).unwrap().children().unwrap().len();
|
||||
d.insert(Some(NodeId(g)), at, (*k).clone())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_that_do_not_stack_as_a_paragraph_stay_apart() {
|
||||
let mut s = session();
|
||||
// Far apart, then lined up at nothing.
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Top", "size": 20}));
|
||||
let b = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Far", "size": 20}));
|
||||
let c = outlined(&mut s, json!({"x": 75, "y": 324, "text": "Askew", "size": 20}));
|
||||
into_one_group(&mut s, a, &[b, c]);
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_between_lines_keeps_them_apart() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB\nCD", "size": 30}));
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
s.edit("test", |d, _| {
|
||||
let n = d.node(NodeId(rect)).unwrap().clone();
|
||||
d.remove(NodeId(rect))?;
|
||||
d.insert(Some(NodeId(g)), 2, n)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["AB", "CD"]), "the rectangle is painted between the lines: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_lines_keep_their_tracking_and_spaces() {
|
||||
let mut s = session();
|
||||
let text = "SPACED OUT\nTITLE";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_line_takes_the_tracking_of_its_block() {
|
||||
// One glyph has no gap to measure tracking by: it joins the tracked lines.
|
||||
for text in ["TITLE\nB", "B\nTITLE", "TITLE\nB\nTITLE"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unevenly_tracked_type_still_becomes_type() {
|
||||
let mut s = session();
|
||||
// Less than half a space more after e: no gap can be read as a word space.
|
||||
let text = "abcdefgh";
|
||||
let (before, r) = retyped(
|
||||
&mut s,
|
||||
json!({"x": 40, "y": 100, "text": text, "size": 30}),
|
||||
&[json!({"start": 0, "end": 4, "tracking": 50}), json!({"start": 4, "end": 8, "tracking": 120})],
|
||||
);
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text, "{r}");
|
||||
assert!(texts.len() > 1, "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
// Each object's glyphs are where the outlines were.
|
||||
let places: Vec<kurbo::Point> = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect();
|
||||
let want = glyph_places(&before);
|
||||
assert_eq!(places.len(), want.len());
|
||||
for (x, y) in places.iter().zip(&want) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
// The second half keeps its own tracking.
|
||||
assert_eq!(r["fonts"].as_array().unwrap().last().unwrap()["tracking"], json!(120.0), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tracked_line_keeps_its_tracking_and_spaces() {
|
||||
let mut s = session();
|
||||
let text = "SPACED OUT";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_line_tracked_two_spaces_wide_keeps_its_tracking() {
|
||||
// Read as it is, the line holds two spaces in each gap, which the tracking measure lays out too.
|
||||
let mut s = session();
|
||||
let text = "M".repeat(400);
|
||||
let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]);
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{}", r["fonts"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_tightly_tracked_line_keeps_its_word_spaces() {
|
||||
// Read as it is, the line holds no spaces; the tracked reading holds eight in each word gap.
|
||||
let mut s = session();
|
||||
let text = vec!["MMM"; 100].join(" ");
|
||||
let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": -180})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]);
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-180.0), "{}", r["fonts"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spaced_letters_keep_their_spaces_when_type_draws_them() {
|
||||
// Most gaps are word spaces: untracked type with the spaces draws every glyph in place.
|
||||
// Every gap one word space: tracking a space wide would draw them too, without the spaces.
|
||||
// L T J: without its spaces the pairs kern, which a measure of the gaps would read as more space.
|
||||
for text in ["a a a aa", "1 2 3", "a b c d", "x = y + 1", "L T J"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slight_tracking_without_spaces_is_kept() {
|
||||
// Tracking 3 moves the last glyph less than the layout check notices: both readings draw it.
|
||||
// A word space both readings keep does not cost the tracking either.
|
||||
for text in ["MMM", "M MM"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": 3})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(3.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines Retype reads from the outlines in group `g` (all in the face of its first glyph's
|
||||
/// first match), before their tracking is measured and their layout checked.
|
||||
fn lines_in(s: &Session, g: u64) -> Vec<super::Line> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]);
|
||||
super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
|
||||
let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted);
|
||||
let face = index.matches(&pieces[0].path)[0].face.id();
|
||||
let mut lines: Vec<super::Line> = vec![];
|
||||
for pc in &pieces {
|
||||
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
|
||||
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
|
||||
lines.extend(super::new_line(pc, &cands));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() {
|
||||
// Glyph `bad` of a tracked line read as another glyph of its font, as when the line's type
|
||||
// would draw another form there: the glyphs after it are still one tracked object.
|
||||
for bad in [0usize, 1] {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
let mut budget = 1000;
|
||||
let mut l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!(l.tracking, 300.0);
|
||||
let other = l.matches[bad].gid + 1;
|
||||
l.matches[bad].gid = other;
|
||||
let bad_id = l.pieces[bad];
|
||||
let mut unmatched = vec![];
|
||||
let out = super::verified(vec![l], false, &mut unmatched);
|
||||
assert_eq!(unmatched, vec![bad_id], "{bad}");
|
||||
let last = out.last().unwrap();
|
||||
assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
assert_eq!(last.tracking, 300.0, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tracking_measure_counts_the_spaces_it_lays_out() {
|
||||
// Three glyphs ten spaces apart: a budget of six times the glyphs, short of the first
|
||||
// layout's 23 characters, lays nothing out.
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "a b c", "size": 30}));
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(lines[0].text.chars().filter(|c| *c == ' ').count() >= 20, "{}", lines[0].text);
|
||||
let mut budget = 3 * 6;
|
||||
let l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!((budget, l.tracking), (3 * 6, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tracking_measure_needs_only_the_layouts_it_runs() {
|
||||
// The line as read, without spaces, with one space per gap, then the tracked reading: a
|
||||
// budget of exactly those characters recovers the tracking.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
let mut budget = lines[0].text.chars().count() + 6 + 11 + 6;
|
||||
let l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!((budget, l.tracking), (0, 300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() {
|
||||
// Tracking 40 spaces wide: read untracked, the rest after the split holds 40 spaces per gap,
|
||||
// and its measure still has the budget to lay them out.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(100), "size": 2})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 8000})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let mut budget = 100_000;
|
||||
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!(l.tracking, 8000.0);
|
||||
l.matches[0].gid += 1;
|
||||
let mut unmatched = vec![];
|
||||
let out = super::verified(vec![l], false, &mut unmatched);
|
||||
assert_eq!(unmatched.len(), 1);
|
||||
let last = out.last().unwrap();
|
||||
assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() {
|
||||
// A long tracked line whose first five glyphs are read as other glyphs: the rest is still one
|
||||
// tracked object.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let mut budget = 1000;
|
||||
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!(l.tracking, 300.0);
|
||||
for m in l.matches.iter_mut().take(5) {
|
||||
m.gid += 1;
|
||||
}
|
||||
let mut unmatched = vec![];
|
||||
let out = super::verified(vec![l], false, &mut unmatched);
|
||||
assert_eq!(unmatched.len(), 5);
|
||||
let last = out.last().unwrap();
|
||||
assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tightly_tracked_type_keeps_its_tracking() {
|
||||
// Tracking tighter than a space: the space moves the next glyph back.
|
||||
// M MM: of its two gaps, the word space is the tighter, and the lower median.
|
||||
// M M MM: most gaps hold a word space, so the tightest extras alone seed a tracking that
|
||||
// splits the last glyph.
|
||||
for text in ["MMMM", "MMMM MM", "M MM", "MM M", "M M MM"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -300})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-300.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kerned_pairs_in_tight_tracking_are_not_read_as_spaces() {
|
||||
// Tracking -250 gives a space a negative advance; the pair kerning of T and a is no space.
|
||||
let mut s = session();
|
||||
let text = "MMMTaMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_space_between_kerned_letters_is_read_as_a_space() {
|
||||
// T and a kern when they touch; with a space between them they do not.
|
||||
let mut s = session();
|
||||
let text = "MMMT aMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// Tracking that cancels the space's advance: the space still stops the pair kerning.
|
||||
let mut s = session();
|
||||
let text = "MMMT aMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -200})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-200.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// Tracking that nearly cancels it: the space still moves the glyphs after it a little.
|
||||
let mut s = session();
|
||||
let text = "MMMM MM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -199.5})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), -199.5, 1e-3), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// A word space a little narrower than its tracking makes it (the word after it moved left by
|
||||
// less than the layout check notices): one space still fits better than the kerned pair.
|
||||
for (tracking, dx) in [(-190, -0.18), (-193, -0.24)] {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMc aMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let kids = children_of(&s, g);
|
||||
assert_eq!(kids.len(), 8);
|
||||
s.execute("select.set", &json!({"ids": kids[4..]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["MMMc aMMM"]), "{tracking}: {r}");
|
||||
}
|
||||
// A space that kerns with the letter after it.
|
||||
let mut s = session();
|
||||
let text = "MMMd TMMM";
|
||||
let p = json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Serif 4", "style": "Regular"});
|
||||
let (before, r) = retyped(&mut s, p, &[json!({"tracking": -217})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-217.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untracked_word_is_not_read_as_spaced_letters_in_tight_tracking() {
|
||||
// Letters, each followed by a space, at tracking of minus half a space, sit where the word's
|
||||
// letters do.
|
||||
let mut s = session();
|
||||
let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "Third", "size": 24}), &[]);
|
||||
assert_eq!(r["texts"], json!(["Third"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_barely_ahead_of_each_other_stay_one_line() {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "MMMM", "size": 30}), &[json!({"tracking": -700})]);
|
||||
assert_eq!(r["texts"], json!(["MMMM"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-700.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracking_near_a_whole_number_is_kept_as_measured_when_rounding_moves_glyphs() {
|
||||
let mut s = session();
|
||||
let text = "i".repeat(400);
|
||||
let (before, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 50.04})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), 50.04, 1e-3), "{}", r["fonts"]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": -300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let kids = children_of(&s, g);
|
||||
s.edit("test", |d, _| {
|
||||
for k in &kids {
|
||||
d.node_mut(NodeId(*k)).unwrap().opacity = 0.5;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
// Each glyph composites on its own over the one it overlaps, as the outlines did.
|
||||
assert_eq!(r["texts"], json!(["M", "M", "M", "M"]), "{r}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["tracking"] == json!(0.0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translucent_gradient_or_stroked_lines_stay_apart() {
|
||||
for case in ["opacity", "blend", "gradient", "stroke"] {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "One\nTwo", "size": 30}));
|
||||
let kids = children_of(&s, g);
|
||||
match case {
|
||||
"gradient" => {
|
||||
let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("paint.setFill", &json!({"gradient": gradient, "ids": kids})).unwrap();
|
||||
}
|
||||
"stroke" => {
|
||||
s.execute("paint.setStroke", &json!({"color": "#ff0000", "ids": kids})).unwrap();
|
||||
}
|
||||
_ => {
|
||||
s.edit("test", |d, _| {
|
||||
for k in &kids {
|
||||
let n = d.node_mut(NodeId(*k)).unwrap();
|
||||
if case == "opacity" {
|
||||
n.opacity = 0.5;
|
||||
} else {
|
||||
n.blend = vectorcraft_color::BlendMode::Multiply;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["One", "Two"]), "{case}: one object would composite or fill the lines as one: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_stay_point_type_past_the_text_wrap_limit_of_their_layer() {
|
||||
// A Text Wrap object above the lines that moves no glyph, on their layer or on another one,
|
||||
// with the limit lowered to nothing: only on their layer does it count.
|
||||
for same_layer in [true, false] {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one";
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = text_of(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
if !same_layer {
|
||||
// Area type below the Text Wrap object on the other layer: work there, none on this one.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let other = s.execute("text.create", &json!({"x": 450, "y": 300, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("type.convertToAreaType", &json!({"ids": [other]})).unwrap();
|
||||
}
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 330, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
super::WRAP_LIMIT.with(|c| c.set(0));
|
||||
let r = s.execute("type.retype", &json!({}));
|
||||
super::WRAP_LIMIT.with(|c| c.set(super::MAX_WRAP_WORK));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(!same_layer), "{same_layer}: {r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_subpaths_of_a_text_wrap_object_count_as_wrap_work() {
|
||||
// Each one is copied into the wrap shapes of the area type below it.
|
||||
let mut s = session();
|
||||
let t = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Area", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("type.convertToAreaType", &json!({"ids": [t]})).unwrap();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
let base = vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc);
|
||||
let file_work = vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc);
|
||||
s.edit("test", |d, _| {
|
||||
if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(rect)).unwrap().kind {
|
||||
for _ in 0..100 {
|
||||
path.subpaths.push(vectorcraft_geom::SubPath::new(vec![], true));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc) >= base + 100);
|
||||
// The count file import and the `.ai` editing copy use stays anchors and shapes only.
|
||||
assert_eq!(vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc), file_work);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_under_a_text_wrap_object_stay_point_type() {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one";
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = text_of(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
// Above the outlines, over the end of both lines: area type would wrap round it.
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 90, "y": 70, "width": 60, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(false), "{r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Point));
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
|
||||
@@ -445,7 +445,7 @@ impl Session {
|
||||
/// selection's stroke.
|
||||
pub fn shown_stroke(&self) -> Option<StrokeLayer> {
|
||||
let st = self.active()?;
|
||||
if self.tool_id() == super::paint::LIVE_PAINT_BUCKET {
|
||||
if self.bucket_paints() {
|
||||
return Some(self.new_art_stroke());
|
||||
}
|
||||
if let Some(part) = st.selected_symbol_part() {
|
||||
|
||||
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Type Path Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
|
||||
has_doc,
|
||||
set_path_handle
|
||||
),
|
||||
@@ -1449,6 +1449,10 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
|
||||
let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
let independent = switch_or(p, "independent", false, C)?;
|
||||
let symmetric = switch_or(p, "symmetric", false, C)?;
|
||||
if symmetric && independent {
|
||||
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
|
||||
}
|
||||
let node = s.doc()?.doc.node(id);
|
||||
let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. }));
|
||||
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
|
||||
@@ -1461,7 +1465,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let within = |t: &TextObject| {
|
||||
t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD))
|
||||
};
|
||||
if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) {
|
||||
if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) {
|
||||
t.kind = before;
|
||||
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Free Distort",
|
||||
[],
|
||||
None,
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
|
||||
has_doc,
|
||||
distort
|
||||
),
|
||||
@@ -86,6 +86,15 @@ impl Projective {
|
||||
Self { m: [a, b, p0.x, d, e, p0.y, g, h], src, pre: bx.to_doc().inverse() }
|
||||
}
|
||||
|
||||
/// Whether `p` maps in front of the warp's horizon, on the side the box's own corners are.
|
||||
fn in_front(&self, p: Point) -> bool {
|
||||
let [.., g, h] = self.m;
|
||||
let p = self.pre * p;
|
||||
let u = if self.src.width().abs() > 1e-12 { (p.x - self.src.x0) / self.src.width() } else { 0.0 };
|
||||
let v = if self.src.height().abs() > 1e-12 { (p.y - self.src.y0) / self.src.height() } else { 0.0 };
|
||||
g * u + h * v + 1.0 > 1e-9
|
||||
}
|
||||
|
||||
pub fn apply(&self, p: Point) -> Point {
|
||||
let [a, b, c, d, e, f, g, h] = self.m;
|
||||
let p = self.pre * p;
|
||||
@@ -138,6 +147,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
// A clip group is bounded by its clip path.
|
||||
NodeKind::Group { children, clip: true } => warp_children(children, pr, |i| i == 0),
|
||||
NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => warp_children(children, pr, |i| i >= skip),
|
||||
// An image's corners follow the warp exactly ([`Node::set_image_corners`]); [`distort`]
|
||||
// has checked that they stay convex.
|
||||
NodeKind::Image(_) => {
|
||||
let b = n.geometric_bounds();
|
||||
if let Some(q) = n.image_corners() {
|
||||
let _ = n.set_image_corners(q.map(|p| pr.apply(p)));
|
||||
}
|
||||
b
|
||||
}
|
||||
_ => {
|
||||
// No editable points: the affine approximation (which maps the gradients too).
|
||||
let b = n.geometric_bounds();
|
||||
@@ -157,6 +175,21 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
before
|
||||
}
|
||||
|
||||
/// Whether the warp from `src` to `q` ([`Projective::from_box`]) takes the corners of `src` to `q`,
|
||||
/// within a millionth of `q`'s shortest side plus the rounding error of coordinates as far from `q`'s
|
||||
/// first corner as the others. The warp is solved and measured with `src` and `q` moved to the
|
||||
/// origin, so coordinates far from it do not widen the allowance.
|
||||
fn reaches_corners(src: OrientedBox, q: [Point; 4]) -> bool {
|
||||
let origin = q[0].to_vec2();
|
||||
let q = q.map(|p| p - origin);
|
||||
let src = OrientedBox { rect: src.rect - src.rect.origin().to_vec2(), ..src };
|
||||
let pr = Projective::from_box(src, q);
|
||||
let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min);
|
||||
let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max);
|
||||
let tol = side * 1e-6 + far * 1e-12;
|
||||
side.is_finite() && side > 0.0 && src.corners().iter().zip(q).all(|(c, want)| pr.apply(*c).distance(want) <= tol)
|
||||
}
|
||||
|
||||
/// Warps each of `children` and returns the union of the pre-warp bounds of those `counts` picks
|
||||
/// by index.
|
||||
fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(usize) -> bool) -> Option<Rect> {
|
||||
@@ -166,6 +199,76 @@ fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(us
|
||||
})
|
||||
}
|
||||
|
||||
/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`]
|
||||
/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with
|
||||
/// why.
|
||||
fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> {
|
||||
if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) {
|
||||
if !q.iter().all(|p| pr.in_front(*p)) {
|
||||
return Some((n.id, Unwarpable::Horizon));
|
||||
}
|
||||
if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) {
|
||||
return Some((
|
||||
n.id,
|
||||
match e {
|
||||
vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex,
|
||||
vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr))
|
||||
}
|
||||
|
||||
/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity
|
||||
/// masks).
|
||||
fn first_image(n: &Node) -> Option<vectorcraft_doc::NodeId> {
|
||||
if matches!(n.kind, NodeKind::Image(_)) {
|
||||
return Some(n.id);
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(first_image)
|
||||
}
|
||||
|
||||
/// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups
|
||||
/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other
|
||||
/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole.
|
||||
fn warped_parts(n: &Node) -> Vec<&Node> {
|
||||
let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. });
|
||||
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_));
|
||||
let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c);
|
||||
let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art);
|
||||
children.chain(mask).collect()
|
||||
}
|
||||
|
||||
/// The error of `command` on image `id`, which is distorted (Perspective Distort or Free Distort)
|
||||
/// in a way the command cannot keep.
|
||||
pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId) -> EngineError {
|
||||
bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0))
|
||||
}
|
||||
|
||||
/// Why an image cannot follow the corners of a distort.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Unwarpable {
|
||||
/// Its corners would fold over, meet or fall on one line.
|
||||
NotConvex,
|
||||
/// A corner would cross the warp's horizon.
|
||||
Horizon,
|
||||
/// Its corners would be too close together for a perspective map to place them.
|
||||
TooNarrow,
|
||||
}
|
||||
|
||||
/// The error of `object.distort` when image `id` cannot follow its corners.
|
||||
fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError {
|
||||
const C: &str = "object.distort";
|
||||
match why {
|
||||
Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
|
||||
Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
|
||||
Unwarpable::TooNarrow => {
|
||||
bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn distort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.distort";
|
||||
// All four corners or nothing, each exactly [x, y]: nothing malformed is left out.
|
||||
@@ -208,6 +311,26 @@ fn distort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(ids_json);
|
||||
}
|
||||
let pr = Projective::from_box(src, [tl, tr, br, bl]);
|
||||
// An image's corners follow the handles exactly, so they must stay a convex shape: nothing
|
||||
// changes when one would not.
|
||||
let doc = &s.doc()?.doc;
|
||||
// Corners that do not make a convex shape give no perspective map (the warp falls back to an
|
||||
// affine one), so an image cannot follow them.
|
||||
if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err()
|
||||
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
|
||||
{
|
||||
return Err(unwarpable_error(id, Unwarpable::NotConvex));
|
||||
}
|
||||
// Corners so close together that the map falls back to an affine one: the box's corners do
|
||||
// not reach the handles, so an image cannot follow them either.
|
||||
if !reaches_corners(src, [tl, tr, br, bl])
|
||||
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
|
||||
{
|
||||
return Err(unwarpable_error(id, Unwarpable::TooNarrow));
|
||||
}
|
||||
if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) {
|
||||
return Err(unwarpable_error(id, why));
|
||||
}
|
||||
s.edit("Free Distort", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
|
||||
@@ -74,6 +74,10 @@ pub struct Session {
|
||||
/// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes
|
||||
/// back as it was at the release ([`Session::pointer`]).
|
||||
pub(crate) lender: Option<Box<dyn Tool>>,
|
||||
/// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the
|
||||
/// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the
|
||||
/// colors the bucket paints with ([`Session::bucket_paints`]).
|
||||
pub(crate) back_to_bucket: bool,
|
||||
/// Pointer and key input that came while the tool computed an edit on another thread, each with
|
||||
/// its number and view, made in order once the edit is applied.
|
||||
held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>,
|
||||
@@ -160,6 +164,8 @@ pub struct Session {
|
||||
pub brush_libraries: cmd::brushlib::Libraries,
|
||||
/// The custom arrowheads of the arrowheads file (`stroke.arrowheads.*`); none without one.
|
||||
pub arrowheads: cmd::arrowheads::Arrowheads,
|
||||
/// The custom bevels of the bevels file (`threeD.bevels.*`); none without one.
|
||||
pub bevels: cmd::bevels::Bevels,
|
||||
/// The id each loaded library outside a request's read roots has been shown under, by its own id
|
||||
/// ([`cmd::swatchlib::concealed_library_ids`]), kept for the session.
|
||||
shown_library_ids: std::sync::Mutex<std::collections::BTreeMap<String, String>>,
|
||||
@@ -329,6 +335,9 @@ pub struct Session {
|
||||
/// The id and persistent options of the tool when the press under way began, which a dropped
|
||||
/// press puts back ([`Session::drop_tool_press`]).
|
||||
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
|
||||
/// An option of the active tool was set during the press under way, which stored all of its
|
||||
/// options, so a dropped press stores the options it puts back.
|
||||
pub(crate) press_options_stored: bool,
|
||||
/// The engine saves the selection and active layer before a Type press and restores them if it drops.
|
||||
pub(crate) press_type_selection: Option<(Selection, Option<NodeId>)>,
|
||||
/// The freeform gradient point selected once the tool took the press under way, which a
|
||||
|
||||
@@ -283,6 +283,11 @@ pub struct Prefs {
|
||||
pub low_res_proxy_eps: bool,
|
||||
pub anti_aliased_bitmaps: bool,
|
||||
pub update_links: String,
|
||||
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
|
||||
/// becomes when the open or place does not say (`text`: editable type in the file's fonts;
|
||||
/// `outlines`: the glyph outlines the file draws). The Import PDF dialog starts from it and
|
||||
/// keeps the choice it confirms.
|
||||
pub pdf_text_as: String,
|
||||
// Clipboard Handling
|
||||
pub copy_as_svg: bool,
|
||||
pub copy_as_pdf: bool,
|
||||
@@ -589,6 +594,7 @@ impl Default for Prefs {
|
||||
low_res_proxy_eps: false,
|
||||
anti_aliased_bitmaps: false,
|
||||
update_links: s("askWhenModified"),
|
||||
pdf_text_as: s("text"),
|
||||
copy_as_svg: true,
|
||||
copy_as_pdf: false,
|
||||
copy_aicb: false,
|
||||
|
||||
@@ -55,6 +55,7 @@ impl Session {
|
||||
histories_seen: None,
|
||||
tool: vectorcraft_tools::create("selection"),
|
||||
lender: None,
|
||||
back_to_bucket: false,
|
||||
held_input: Default::default(),
|
||||
input_count: 0,
|
||||
edit_started_by: None,
|
||||
@@ -89,6 +90,7 @@ impl Session {
|
||||
symbol_libraries: Default::default(),
|
||||
brush_libraries: Default::default(),
|
||||
arrowheads: Default::default(),
|
||||
bevels: Default::default(),
|
||||
shown_library_ids: Default::default(),
|
||||
libraries: Default::default(),
|
||||
pdf_preset_dir: None,
|
||||
@@ -137,6 +139,7 @@ impl Session {
|
||||
plane_widget_press: false,
|
||||
pointer_held: false,
|
||||
press_options: None,
|
||||
press_options_stored: false,
|
||||
press_type_selection: None,
|
||||
press_point: None,
|
||||
ruler_guide: None,
|
||||
|
||||
@@ -323,7 +323,7 @@ impl Session {
|
||||
}
|
||||
// While the Live Paint Bucket is active, paint previews change only the bucket's colors, so
|
||||
// each preview starts from the colors the interaction began with.
|
||||
let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET;
|
||||
let bucket = self.bucket_paints();
|
||||
let (paint, restore_paint) = {
|
||||
let menu = self.menu.clone();
|
||||
let st = self.doc_mut()?;
|
||||
@@ -485,7 +485,7 @@ impl Session {
|
||||
self.pending_paint = None;
|
||||
// While the Live Paint Bucket is active, a previewed color is the bucket's color, which the
|
||||
// cancel puts back as well.
|
||||
let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET;
|
||||
let bucket = self.bucket_paints();
|
||||
if let Some(paint) = self
|
||||
.active()
|
||||
.and_then(|st| st.interaction.as_ref())
|
||||
|
||||
@@ -15,6 +15,7 @@ mod assets;
|
||||
mod assets_3d;
|
||||
mod attributes;
|
||||
mod bboxrotate;
|
||||
mod bevels;
|
||||
mod blendfidelity;
|
||||
mod blendopts;
|
||||
mod blendspine;
|
||||
@@ -202,6 +203,7 @@ mod symbol_nine_slice;
|
||||
mod symbolbounds;
|
||||
mod symboledit;
|
||||
mod symbolism_options;
|
||||
mod symbolism_shift;
|
||||
mod symbollib;
|
||||
mod tangent_line;
|
||||
mod targeting;
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
//! Custom bevels (`cmd/bevels.rs`): bevels read from the bevels file's symbols, listed, set on
|
||||
//! Extrude & Bevel and Extrude & Bevel (Classic) by name, reloaded when the file is saved, and kept
|
||||
//! with the documents that use them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, Symbol};
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use crate::cmd::bevels::{self, bevels_of};
|
||||
use crate::*;
|
||||
|
||||
fn line(pts: &[(f64, f64)], closed: bool) -> Node {
|
||||
let pts: Vec<Point> = pts.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
Node::path(NodeId(0), PathData::single(SubPath::polyline(&pts, closed)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))
|
||||
}
|
||||
|
||||
fn add_symbol(d: &mut Document, name: &str, art: Node) {
|
||||
let art = d.reid(&art);
|
||||
d.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false });
|
||||
}
|
||||
|
||||
/// A folder of its own for test `name`, emptied.
|
||||
fn folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-bevels-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn close(a: (f64, f64), b: (f64, f64)) -> bool {
|
||||
(a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_open_path_symbol_is_a_bevel_from_its_first_anchor_to_its_last() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (20.0, 60.0), (70.0, 40.0), (100.0, 100.0)], false));
|
||||
// The same path mirrored across the page and drawn from the other side gives the same points.
|
||||
add_symbol(&mut d, "Mirrored", line(&[(300.0, 50.0), (280.0, 110.0), (230.0, 90.0), (200.0, 150.0)], false));
|
||||
// In a group of one, at another size.
|
||||
let small = line(&[(0.0, 0.0), (2.0, 6.0), (7.0, 4.0), (10.0, 10.0)], false);
|
||||
add_symbol(&mut d, "Grouped", Node::group(NodeId(0), vec![Arc::new(small)]));
|
||||
// Points past the ends are held to them.
|
||||
add_symbol(&mut d, "Overshoot", line(&[(0.0, 0.0), (-20.0, 50.0), (100.0, 120.0), (100.0, 100.0)], false));
|
||||
add_symbol(&mut d, "Closed", line(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], true));
|
||||
let two = Node::group(NodeId(0), vec![Arc::new(line(&[(0.0, 0.0), (1.0, 1.0)], false)), Arc::new(line(&[(0.0, 0.0), (1.0, 1.0)], false))]);
|
||||
add_symbol(&mut d, "Two paths", two);
|
||||
add_symbol(&mut d, "Upright", line(&[(0.0, 0.0), (5.0, 50.0), (0.0, 100.0)], false));
|
||||
let dense: Vec<(f64, f64)> = (0..=bevels::MAX_ANCHORS).map(|i| (i as f64, i as f64)).collect();
|
||||
add_symbol(&mut d, "Dense", line(&dense, false));
|
||||
add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (1.0, 1.0)], false));
|
||||
let read = bevels_of(&d);
|
||||
let names: Vec<&str> = read.bevels.iter().map(|b| b.name.as_str()).collect();
|
||||
assert_eq!(names, ["Notch", "Mirrored", "Grouped", "Overshoot"]);
|
||||
let notch = [(0.0, 0.0), (0.2, 0.6), (0.7, 0.4), (1.0, 1.0)];
|
||||
for b in &read.bevels[..3] {
|
||||
assert_eq!(b.points.len(), 4, "{}", b.name);
|
||||
assert!(b.points.iter().zip(notch).all(|(&a, b)| close(a, b)), "{}: {:?}", b.name, b.points);
|
||||
}
|
||||
assert!(close(read.bevels[3].points[1], (0.0, 0.5)) && close(read.bevels[3].points[2], (1.0, 1.0)), "{:?}", read.bevels[3].points);
|
||||
let skipped: Vec<(&str, &str)> = read.skipped.iter().map(|(n, r)| (n.as_str(), r.as_str())).collect();
|
||||
assert_eq!(
|
||||
skipped,
|
||||
[
|
||||
("Closed", "its art is not one open path"),
|
||||
("Two paths", "its art is not one open path"),
|
||||
("Upright", "its ends are not apart both across and down"),
|
||||
("Dense", "its path has too many anchors for a bevel"),
|
||||
("Notch", "another symbol has this name"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A curve is cut into straight lines, and a path of many points keeps the ones that matter, at
|
||||
/// most 64 in all, ends included.
|
||||
#[test]
|
||||
fn curves_and_long_paths_fit_in_the_points_a_bevel_holds() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
// A quarter circle from (0, 0) to (100, 100), bulging up and right.
|
||||
let k = 0.5523 * 100.0;
|
||||
let mut a = Anchor::corner(Point::new(0.0, 0.0));
|
||||
a.h_out = Point::new(k, 0.0);
|
||||
let mut b = Anchor::corner(Point::new(100.0, 100.0));
|
||||
b.h_in = Point::new(100.0, 100.0 - k);
|
||||
let arc = Node::path(NodeId(0), PathData::single(SubPath::new(vec![a, b], false)), Appearance::default());
|
||||
add_symbol(&mut d, "Arc", arc);
|
||||
let wavy: Vec<(f64, f64)> = (0..=3000).map(|i| (i as f64 / 30.0, i as f64 / 30.0 + 5.0 * (i as f64 / 50.0).sin())).collect();
|
||||
add_symbol(&mut d, "Wavy", line(&wavy, false));
|
||||
let read = bevels_of(&d);
|
||||
assert!(read.skipped.is_empty(), "{:?}", read.skipped);
|
||||
for b in &read.bevels {
|
||||
assert!((3..=effects::BevelProfile::MAX_POINTS).contains(&b.points.len()), "{}: {}", b.name, b.points.len());
|
||||
assert!(close(b.points[0], (0.0, 0.0)) && close(*b.points.last().unwrap(), (1.0, 1.0)), "{}", b.name);
|
||||
assert!(effects::BevelProfile::new(&b.points).is_some(), "{}", b.name);
|
||||
}
|
||||
// The arc's points lie on the circle: across first, then down.
|
||||
let arc = &read.bevels[0];
|
||||
assert!(arc.points.iter().all(|&(x, y)| (((x - 0.0).powi(2) + (y - 1.0).powi(2)).sqrt() - 1.0).abs() < 0.01), "{:?}", arc.points);
|
||||
}
|
||||
|
||||
/// A path of many tall curves, cut into more straight lines than a bevel's path may take, is
|
||||
/// skipped as too detailed.
|
||||
#[test]
|
||||
fn a_path_cut_into_too_many_lines_is_skipped() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let anchors: Vec<Anchor> = (0..4000)
|
||||
.map(|i| {
|
||||
let p = Point::new(f64::from(i), f64::from(i) / 4.0);
|
||||
let swing = if i % 2 == 0 { 1000.0 } else { -1000.0 };
|
||||
let mut a = Anchor::corner(p);
|
||||
a.h_in = Point::new(p.x - 0.5, p.y - swing);
|
||||
a.h_out = Point::new(p.x + 0.5, p.y + swing);
|
||||
a
|
||||
})
|
||||
.collect();
|
||||
let wild = Node::path(NodeId(0), PathData::single(SubPath::new(anchors, false)), Appearance::default());
|
||||
add_symbol(&mut d, "Wild", wild);
|
||||
let read = bevels_of(&d);
|
||||
assert!(read.bevels.is_empty());
|
||||
assert_eq!(read.skipped, [("Wild".to_string(), "its path is too detailed for a bevel".to_string())]);
|
||||
}
|
||||
|
||||
/// Simplifying the paths of one file measures at most a fixed number of point-to-line distances:
|
||||
/// a path that needs more than are left is skipped as too detailed, and a short one still reads.
|
||||
#[test]
|
||||
fn simplifying_the_bevels_of_a_file_has_a_work_limit() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let wavy: Vec<(f64, f64)> = (0..=3000).map(|i| (i as f64 / 30.0, i as f64 / 30.0 + 5.0 * (i as f64 / 50.0).sin())).collect();
|
||||
add_symbol(&mut d, "Wavy", line(&wavy, false));
|
||||
add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (20.0, 60.0), (70.0, 40.0), (100.0, 100.0)], false));
|
||||
let read = bevels::bevels_within(&d, 5_000);
|
||||
let names: Vec<&str> = read.bevels.iter().map(|b| b.name.as_str()).collect();
|
||||
assert_eq!(names, ["Notch"]);
|
||||
assert_eq!(read.skipped, [("Wavy".to_string(), "its path is too detailed for a bevel".to_string())]);
|
||||
assert_eq!(bevels_of(&d).bevels.len(), 2);
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: u32) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn params(s: &Session, id: NodeId) -> Value {
|
||||
s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bevels_file_is_made_opened_and_reloaded_when_saved() {
|
||||
let dir = folder("edit");
|
||||
let file = dir.join(bevels::FILE_NAME).to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = rect(&mut s, 20);
|
||||
s.attach_bevels_file(file.clone());
|
||||
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
|
||||
assert_eq!((list["bevels"].as_array().unwrap().len(), list["file"].as_str()), (0, Some(file.as_str())));
|
||||
let apply = json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Example Bevel"}}});
|
||||
assert!(s.execute("effect.apply", &apply).unwrap_err().to_string().contains("no custom bevel Example Bevel"));
|
||||
let r = s.execute("threeD.bevels.edit", &json!({})).unwrap();
|
||||
assert_eq!(r["created"], true);
|
||||
assert_eq!(s.doc().unwrap().path.as_deref(), Some(file.as_str()), "the file is the active document");
|
||||
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
|
||||
assert_eq!(list["bevels"][0]["name"], "Example Bevel");
|
||||
assert_eq!(list["bevels"][0]["points"].as_array().unwrap().len(), 4);
|
||||
// A second bevel drawn in the file is listed once the file is saved.
|
||||
let st = s.doc_mut().unwrap();
|
||||
add_symbol(Arc::make_mut(&mut st.doc), "Steps", line(&[(0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 100.0), (100.0, 100.0)], false));
|
||||
assert_eq!(s.execute("threeD.bevels.list", &json!({})).unwrap()["bevels"].as_array().unwrap().len(), 1);
|
||||
s.execute("document.save", &json!({})).unwrap();
|
||||
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
|
||||
let names: Vec<&str> = list["bevels"].as_array().unwrap().iter().filter_map(|b| b["name"].as_str()).collect();
|
||||
assert_eq!(names, ["Example Bevel", "Steps"]);
|
||||
assert_eq!(s.execute("threeD.bevels.reload", &json!({})).unwrap()["count"], 2);
|
||||
// Editing again brings the open file to the front, without making it anew.
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(s.execute("threeD.bevels.edit", &json!({})).unwrap()["created"], false);
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
// The rectangle takes the bevel with a copy of its points, in both Extrude & Bevels.
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Steps"}}})).unwrap();
|
||||
let p = params(&s, id);
|
||||
assert_eq!((p["bevel"].as_str(), p[effects::BEVEL_NAME].as_str()), (Some("custom"), Some("Steps")));
|
||||
assert_eq!(p[effects::BEVEL_PROFILE], json!([[0.0, 0.0], [0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [1.0, 1.0]]));
|
||||
let set = |bevel: Value| json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": bevel}});
|
||||
s.execute("effect.setParams", &set(json!({"custom": "Example Bevel"}))).unwrap();
|
||||
assert_eq!(params(&s, id)[effects::BEVEL_NAME], "Example Bevel");
|
||||
for bad in [json!({"custom": 3}), json!({"custom": "Nope"}), json!({"name": "Steps"})] {
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
assert!(s.execute("effect.setParams", &set(bad.clone())).is_err(), "{bad}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{bad}: no undo step");
|
||||
}
|
||||
let classic = rect(&mut s, 200);
|
||||
s.execute(
|
||||
"effect.apply",
|
||||
&json!({"effect": effects::CLASSIC_EXTRUDE, "ids": [classic.0], "item": null, "params": {"bevel": {"custom": "Steps"}}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(params(&s, classic)[effects::BEVEL_NAME], "Steps");
|
||||
// A built-in shape again draws that shape.
|
||||
s.execute("effect.setParams", &set(json!("rounded"))).unwrap();
|
||||
assert!(matches!(effects::extrude_options(¶ms(&s, id)).bevel.map(|b| b.shape.id()), Some("rounded")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `effect.apply` and `effect.setParams` given a custom bevel by name record its points as
|
||||
/// `savedBevel`, so a replay draws that bevel after the bevels file no longer has it.
|
||||
#[test]
|
||||
fn a_replay_draws_the_custom_bevel_the_command_recorded() {
|
||||
let dir = folder("replay");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = rect(&mut s, 20);
|
||||
s.attach_bevels_file(dir.join(bevels::FILE_NAME).to_string_lossy().to_string());
|
||||
s.execute("threeD.bevels.edit", &json!({})).unwrap();
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
let apply = json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Example Bevel"}}});
|
||||
s.execute("effect.apply", &apply).unwrap();
|
||||
let applied = params(&s, id);
|
||||
let (cmd, recorded) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(cmd, "effect.apply");
|
||||
assert_eq!(recorded[bevels::SAVED_BEVEL], applied[effects::BEVEL_PROFILE]);
|
||||
let set = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": {"custom": "Example Bevel"}, "bevelWidth": 9}});
|
||||
s.execute("effect.setParams", &set).unwrap();
|
||||
let edited = params(&s, id);
|
||||
let (_, set_recorded) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(set_recorded[bevels::SAVED_BEVEL], applied[effects::BEVEL_PROFILE]);
|
||||
// The bevels file no longer has the bevel: by name it is refused, and the replays draw it.
|
||||
s.attach_bevels_file(dir.join("Other.vectorcraft").to_string_lossy().to_string());
|
||||
assert!(s.execute("effect.apply", &apply).is_err());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().appearance.effects.is_empty());
|
||||
s.replay("effect.apply", &recorded).unwrap();
|
||||
assert_eq!(params(&s, id), applied);
|
||||
s.replay("effect.setParams", &set_recorded).unwrap();
|
||||
assert_eq!(params(&s, id), edited);
|
||||
// Points given with the name are used in place of the file's.
|
||||
let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]);
|
||||
let mut given = set.clone();
|
||||
given["savedBevel"] = notch.clone();
|
||||
s.execute("effect.setParams", &given).unwrap();
|
||||
assert_eq!((¶ms(&s, id)[effects::BEVEL_PROFILE], ¶ms(&s, id)[effects::BEVEL_NAME]), (¬ch, &json!("Example Bevel")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_keeps_its_custom_bevels_without_the_bevels_file() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
let id = rect(&mut s, 100);
|
||||
let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]);
|
||||
let custom = json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch, "bevelWidth": 12, "bevelHeight": 12});
|
||||
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": custom})).unwrap();
|
||||
let ink = |s: &Session| {
|
||||
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default())
|
||||
};
|
||||
let with_bevel = ink(&s);
|
||||
// Saved and opened in a session that has no bevels file: the bevel is drawn the same.
|
||||
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone();
|
||||
let mut o = Session::new();
|
||||
o.execute("document.open", &json!({"name": "a.vectorcraft", "dataBase64": saved})).unwrap();
|
||||
assert_eq!(params(&o, id)[effects::BEVEL_PROFILE], params(&s, id)[effects::BEVEL_PROFILE]);
|
||||
assert_eq!(ink(&o).pixels, with_bevel.pixels);
|
||||
// The classic chamfer draws differently.
|
||||
let set = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": "classic"}});
|
||||
o.execute("effect.setParams", &set).unwrap();
|
||||
assert_ne!(ink(&o).pixels, with_bevel.pixels);
|
||||
o.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(ink(&o).pixels, with_bevel.pixels);
|
||||
// Points that do not make a bevel are refused before the document changes.
|
||||
let bad = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevelProfile": [[0, 0], [0.5, 2], [1, 1]]}});
|
||||
assert!(o.execute("effect.setParams", &bad).unwrap_err().to_string().contains("bevelProfile must be"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_extrudes_take_a_custom_bevels_points_and_refuse_a_name_that_is_not_a_string() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]);
|
||||
for effect in [effects::EXTRUDE, effects::CLASSIC_EXTRUDE] {
|
||||
let id = rect(&mut s, 100);
|
||||
let apply = |name: Value| json!({"effect": effect, "ids": [id.0], "item": null, "params": {"bevel": "custom", "bevelName": name, "bevelProfile": notch}});
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("effect.apply", &apply(json!(3))).unwrap_err().to_string();
|
||||
assert!(e.contains("bevelName must be a string"), "{effect}: {e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before, "{effect}");
|
||||
s.execute("effect.apply", &apply(json!("Notch"))).unwrap();
|
||||
assert_eq!((¶ms(&s, id)[effects::BEVEL_PROFILE], ¶ms(&s, id)[effects::BEVEL_NAME]), (¬ch, &json!("Notch")), "{effect}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_bevels_file_editing_is_refused_and_none_are_listed() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
|
||||
assert_eq!((list["bevels"].as_array().unwrap().len(), &list["file"]), (0, &Value::Null));
|
||||
assert!(s.execute("threeD.bevels.edit", &json!({})).is_err());
|
||||
assert!(s.execute("threeD.bevels.reload", &json!({})).is_err());
|
||||
// A file that is not a document lists no bevels and says why.
|
||||
let dir = folder("unreadable");
|
||||
let file = dir.join(bevels::FILE_NAME);
|
||||
std::fs::write(&file, b"not a document").unwrap();
|
||||
s.attach_bevels_file(file.to_string_lossy().to_string());
|
||||
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
|
||||
assert!(list["error"].is_string(), "{list}");
|
||||
assert!(s.execute("threeD.bevels.reload", &json!({})).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Automation roots that grant reading `read` alone.
|
||||
fn read_roots(read: &[&std::path::Path]) -> Arc<crate::file_access::AutomationRoots> {
|
||||
crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_outside_the_bevels_files_folder_sees_its_file_name_alone_and_cannot_reload_it() {
|
||||
let dir = folder("roots-list");
|
||||
let (prefs, other) = (dir.join("prefs"), dir.join("other"));
|
||||
std::fs::create_dir_all(&prefs).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let file = prefs.join(bevels::FILE_NAME);
|
||||
std::fs::write(&file, b"not a drawing").unwrap();
|
||||
let (file, prefs_text) = (file.to_string_lossy().to_string(), prefs.to_string_lossy().to_string());
|
||||
let mut s = Session::new();
|
||||
s.attach_bevels_file(file.clone());
|
||||
let (outside, inside) = (read_roots(&[&other]), read_roots(&[&prefs]));
|
||||
let list = crate::file_access::confine(Some(&outside), || s.execute("threeD.bevels.list", &json!({}))).unwrap();
|
||||
assert_eq!(list["file"], Value::Null, "{list}");
|
||||
let error = list["error"].as_str().unwrap();
|
||||
assert!(error.starts_with(bevels::FILE_NAME) && !error.contains(&prefs_text), "{error}");
|
||||
let list = crate::file_access::confine(Some(&inside), || s.execute("threeD.bevels.list", &json!({}))).unwrap();
|
||||
assert_eq!(list["file"].as_str(), Some(file.as_str()));
|
||||
assert!(list["error"].as_str().unwrap().starts_with(&file), "{list}");
|
||||
// A good file now: an agent outside the folder cannot have it read.
|
||||
std::fs::write(&file, vectorcraft_format::save_file(&bevels::starter())).unwrap();
|
||||
let e = crate::file_access::confine(Some(&outside), || s.execute("threeD.bevels.reload", &json!({}))).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the read root") && e.ends_with(bevels::FILE_NAME) && !e.contains(&prefs_text), "{e}");
|
||||
let list = s.execute("threeD.bevels.list", &json!({})).unwrap();
|
||||
assert!(list["bevels"].as_array().unwrap().is_empty() && list["error"].is_string(), "not read again: {list}");
|
||||
let r = crate::file_access::confine(Some(&inside), || s.execute("threeD.bevels.reload", &json!({}))).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_edits_the_bevels_file_only_inside_its_read_roots() {
|
||||
let dir = folder("roots-edit");
|
||||
let (prefs, other) = (dir.join("prefs"), dir.join("other"));
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let file = prefs.join(bevels::FILE_NAME).to_string_lossy().to_string();
|
||||
let prefs_text = prefs.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.attach_bevels_file(file.clone());
|
||||
let first_doc = s.doc().unwrap().uid;
|
||||
let outside = read_roots(&[&other]);
|
||||
let edit = |s: &mut Session, roots: &Arc<crate::file_access::AutomationRoots>| {
|
||||
crate::file_access::confine(Some(roots), || s.execute("threeD.bevels.edit", &json!({})))
|
||||
};
|
||||
// Refused before the folder or the file is made, or anything is opened.
|
||||
let e = edit(&mut s, &outside).unwrap_err().to_string();
|
||||
assert!(e.ends_with(bevels::FILE_NAME) && !e.contains(&prefs_text), "{e}");
|
||||
assert!(!prefs.exists(), "no folder made");
|
||||
assert_eq!((s.documents().len(), s.doc().unwrap().uid), (1, first_doc));
|
||||
// From the 3D and Materials panel (no roots), the file is made and opened.
|
||||
assert_eq!(s.execute("threeD.bevels.edit", &json!({})).unwrap()["created"], true);
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
// Open already: still not brought to the front for an agent outside the folder.
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert!(edit(&mut s, &outside).is_err());
|
||||
assert_eq!((s.documents().len(), s.doc().unwrap().uid), (2, first_doc));
|
||||
// Inside the read roots: opened under them, with its path.
|
||||
let inside = read_roots(&[&prefs]);
|
||||
let mut agent = Session::new();
|
||||
agent.attach_bevels_file(file.clone());
|
||||
let r = edit(&mut agent, &inside).unwrap();
|
||||
assert_eq!((r["path"].as_str(), &r["created"]), (Some(file.as_str()), &json!(false)));
|
||||
let st = agent.doc().unwrap();
|
||||
assert_eq!(st.path.as_deref(), Some(file.as_str()));
|
||||
assert!(st.opened_by.as_ref().is_some_and(|r| Arc::ptr_eq(r, &inside)), "opened under the agent's roots");
|
||||
// A missing file inside the roots is still made first.
|
||||
let fresh = dir.join("fresh").join(bevels::FILE_NAME).to_string_lossy().to_string();
|
||||
let mut agent = Session::new();
|
||||
agent.attach_bevels_file(fresh.clone());
|
||||
let r = edit(&mut agent, &read_roots(&[&dir])).unwrap();
|
||||
assert_eq!(r["created"], true);
|
||||
assert!(std::path::Path::new(&fresh).is_file());
|
||||
assert_eq!(agent.doc().unwrap().path.as_deref(), Some(fresh.as_str()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -114,6 +114,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"bristle-brushes",
|
||||
"paint",
|
||||
"pattern-borders",
|
||||
"decorative",
|
||||
"scatter-shapes",
|
||||
"stipple",
|
||||
"game-trails",
|
||||
@@ -122,10 +123,26 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"tech-circuit",
|
||||
"engraving",
|
||||
"arrows",
|
||||
"image-brush"
|
||||
"image-brush",
|
||||
"artistic",
|
||||
"vector-packs"
|
||||
]
|
||||
);
|
||||
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
|
||||
// None of them is a default brush.
|
||||
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
|
||||
for id in ids {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
|
||||
}
|
||||
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_builtin_libraries_list_their_brush_names_and_counts() {
|
||||
let mut s = Session::new();
|
||||
let list = run(&mut s, "brush.libraries", json!({}));
|
||||
let libs = list["libraries"].as_array().unwrap();
|
||||
// Looked up by id, so a library added to the list does not shift these checks.
|
||||
let entry = |id: &str| libs.iter().find(|l| l["id"] == id).unwrap();
|
||||
let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"}));
|
||||
@@ -134,6 +151,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"]
|
||||
);
|
||||
assert_eq!(entry("art-ribbons")["count"].as_u64(), Some(5));
|
||||
assert_eq!((entry("decorative")["name"].as_str(), entry("decorative")["count"].as_u64()), (Some("Decorative"), Some(4)));
|
||||
let trails = run(&mut s, "brush.library", json!({"library": "game-trails"}));
|
||||
assert_eq!(
|
||||
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
@@ -163,6 +181,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
|
||||
assert_eq!(strs(&added["added"]), ["Laser Bolt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_library_brush_has_its_kind_and_draws() {
|
||||
let s = Session::new();
|
||||
// One kind of brush per library (Ink and Wash: art brushes and a calligraphic one), every
|
||||
// brush drawing something.
|
||||
for (id, kind) in [
|
||||
@@ -173,6 +196,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
("bristle-brushes", "bristle"),
|
||||
("paint", "art"),
|
||||
("pattern-borders", "pattern"),
|
||||
("decorative", "pattern"),
|
||||
("scatter-shapes", "scatter"),
|
||||
("stipple", "scatter"),
|
||||
("game-trails", "art"),
|
||||
@@ -180,6 +204,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
("dry-media", "art"),
|
||||
("arrows", "art"),
|
||||
("image-brush", "scatter"),
|
||||
("artistic", "art"),
|
||||
("vector-packs", "scatter"),
|
||||
] {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.len() >= 4, "{id}");
|
||||
@@ -193,6 +219,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &stroke).is_empty(), "{} draws nothing", b.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_library_brushes_bring_the_resources_their_art_uses() {
|
||||
let s = Session::new();
|
||||
// The resources their art uses come with them: Striped Ribbon's pattern, Sparkles' symbol.
|
||||
let (_, ribbons) = cmd::brushlib::library(&s, "art-ribbons").unwrap();
|
||||
assert_eq!(art_patterns(ribbons.brush("Striped Ribbon").unwrap()), ["Pinstripes"]);
|
||||
@@ -201,13 +232,88 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
let BrushKind::Scatter(sparkles) = &shapes.brush("Sparkles").unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert!(matches!(&sparkles.art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Sparkle"));
|
||||
assert!(shapes.doc.symbols.iter().any(|x| x.name == "Sparkle"));
|
||||
// None of them is a default brush.
|
||||
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
|
||||
for id in ids {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap();
|
||||
let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap();
|
||||
assert_eq!(alias.brushes, lib.brushes);
|
||||
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic");
|
||||
let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"];
|
||||
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();
|
||||
let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0);
|
||||
for b in &lib.brushes {
|
||||
let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) };
|
||||
assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name);
|
||||
for path in [line_to(180.0), line_to(1.0)] {
|
||||
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name);
|
||||
}
|
||||
// The art is black, so with Tints every path takes the stroke color itself.
|
||||
let mut fills = vec![];
|
||||
for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) {
|
||||
piece.walk(&mut |n| {
|
||||
if n.path_data().is_some() {
|
||||
fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb()));
|
||||
}
|
||||
});
|
||||
}
|
||||
let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5);
|
||||
assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name);
|
||||
let before = undo_len(&s);
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "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!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
|
||||
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 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]
|
||||
@@ -247,6 +353,26 @@ fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
|
||||
assert_eq!(reopened.images, lib.doc.images);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() {
|
||||
let mut file = vectorcraft_doc::Document::new(100.0, 100.0);
|
||||
vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]);
|
||||
let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file));
|
||||
let mut s = session();
|
||||
let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"}));
|
||||
assert_eq!(loaded["name"], "Artistic");
|
||||
let id = loaded["library"].as_str().unwrap();
|
||||
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id);
|
||||
assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id);
|
||||
assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works");
|
||||
// A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id.
|
||||
let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"}));
|
||||
assert_eq!(full["name"], "Artistic Brushes");
|
||||
let full_id = full["library"].as_str().unwrap();
|
||||
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic");
|
||||
assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id);
|
||||
}
|
||||
|
||||
/// Every path of brush art `n`: (anchors, opacity).
|
||||
fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> {
|
||||
let mut out = vec![];
|
||||
@@ -500,6 +626,41 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Decorative").unwrap();
|
||||
let names = ["Leaf Vine", "Blossom Chain", "Pennant Garland", "Lantern String"];
|
||||
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
|
||||
let mut signatures = std::collections::HashSet::new();
|
||||
for b in &lib.brushes {
|
||||
let BrushKind::Pattern(pattern) = &b.kind else { panic!("{} is not a pattern brush", b.name) };
|
||||
assert_eq!(pattern.colorization, vectorcraft_brush::Colorization::Tints);
|
||||
let points = |len: f64| anchors(&vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(len), &black_stroke()).iter().collect::<Vec<_>>());
|
||||
let (one, four) = (points(48.0), points(192.0));
|
||||
assert!(!one.is_empty() && four.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
|
||||
// A path four tiles long places the motif four times, each copy one tile further along.
|
||||
assert_eq!(four.len(), 4 * one.len(), "{} repeats its motif", b.name);
|
||||
for (i, p) in four.iter().enumerate() {
|
||||
let q = one[i % one.len()];
|
||||
let shift = 48.0 * (i / one.len()) as f64;
|
||||
assert!((p.x - q.x - shift).abs() < 1e-3 && (p.y - q.y).abs() < 1e-3, "{} copy {} at {p:?}, not {q:?}", b.name, i / one.len());
|
||||
}
|
||||
signatures.insert(one.iter().map(|p| ((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64)).collect::<Vec<_>>());
|
||||
let before = undo_len(&s);
|
||||
let applied = run(&mut s, "brush.addFromLibrary", json!({"library": "decorative", "name": b.name, "apply": true, "ids": [path]}));
|
||||
assert_eq!((strs(&applied["added"]), &applied["applied"]), (vec![b.name.as_str()], &json!([path])));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
|
||||
}
|
||||
assert_eq!(signatures.len(), names.len(), "each design produces a different repeating shape");
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let reopened = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -3434,6 +3434,65 @@ fn live_paint_bucket_gradient_preset_and_sampled_stop_follow_the_active_proxy()
|
||||
assert_eq!(node(&s, rect), art, "the selection keeps its paint");
|
||||
}
|
||||
|
||||
/// The Gradient panel's eyedropper, used on a stop of the Live Paint Bucket's gradient, samples the
|
||||
/// color clicked into that stop of the bucket's fill, and the selection keeps its paint. A Cmd-click
|
||||
/// with the bucket, or with the Eyedropper armed for it, which the selection tool takes, leaves the
|
||||
/// bucket's colors as they were.
|
||||
#[test]
|
||||
fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_click() {
|
||||
let v = ViewInfo::default();
|
||||
let click = |s: &mut Session, mods: Mods| {
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 320.0, 320.0).with_mods(mods), v).unwrap();
|
||||
}
|
||||
};
|
||||
let mut s = session();
|
||||
live(&mut s);
|
||||
let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap();
|
||||
s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
|
||||
let art = node(&s, rect);
|
||||
// The panel's eyedropper (`stop_eyedropper`): the Eyedropper, set to switch back to the bucket.
|
||||
s.select_tool("eyedropper", v).unwrap();
|
||||
s.set_tool_option("stop", &json!("livePaintBucket"));
|
||||
assert_eq!(s.selected_stop(), Some(1), "the bucket's stop stays selected for the pick");
|
||||
// A Cmd-click while the pick is armed selects the rectangle and leaves the bucket's gradient.
|
||||
let fill = s.paint.fill.clone();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
click(&mut s, Mods { cmd: true, ..Mods::default() });
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![rect], "the selection tool took the click");
|
||||
assert_eq!((s.paint.fill.clone(), s.selected_stop()), (fill, Some(1)), "the bucket's fill and stop stay");
|
||||
click(&mut s, Mods::default());
|
||||
let Paint::Gradient(g) = &s.paint.fill else { panic!("the bucket's fill is not a gradient") };
|
||||
assert_eq!(g.gradient.stops[1].color, Color::from_hex("#00ff00").unwrap(), "the sampled stop");
|
||||
assert_eq!(node(&s, rect), art, "the selection keeps its paint");
|
||||
// A Cmd-click selects the rectangle; the bucket keeps its gradient.
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
let fill = s.paint.fill.clone();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
click(&mut s, Mods { cmd: true, ..Mods::default() });
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![rect], "the selection tool took the click");
|
||||
assert_eq!(s.paint.fill, fill, "the bucket's fill stays");
|
||||
// Armed again, a Cmd-click on another object deselects the stop; the next click (a Shift-click,
|
||||
// which would sample a color) ends the pick and leaves the bucket's gradient.
|
||||
let other = self::rect(&mut s, 400.0, 400.0, 40.0, 40.0);
|
||||
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
|
||||
s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
|
||||
s.select_tool("eyedropper", v).unwrap();
|
||||
s.set_tool_option("stop", &json!("livePaintBucket"));
|
||||
for mods in [Mods { cmd: true, ..Mods::default() }, Mods { shift: true, ..Mods::default() }] {
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 420.0, 420.0).with_mods(mods), v).unwrap();
|
||||
}
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![other], "the Cmd-click selected the other object");
|
||||
assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample");
|
||||
}
|
||||
|
||||
/// A gradient stop selected on the selection's gradient is not selected once the Live Paint
|
||||
/// Bucket is active (its proxies show the default paint), and one selected on the bucket's
|
||||
/// gradient is not selected once another tool is chosen.
|
||||
@@ -9491,9 +9550,12 @@ fn image_trace_split_view_keeps_and_validates_its_divider() {
|
||||
assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25));
|
||||
// Bad dividers are refused and change nothing.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] {
|
||||
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5]), json!(null)] {
|
||||
assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}");
|
||||
}
|
||||
// A null divider with another view is refused too, and the view stays.
|
||||
assert!(s.execute("imageTrace.setView", &json!({"view": "outlines", "split": null})).is_err());
|
||||
assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::Split);
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25));
|
||||
for edge in [0.0, 1.0] {
|
||||
s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap();
|
||||
|
||||
@@ -318,6 +318,45 @@ fn convert_query_and_intents() {
|
||||
assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err());
|
||||
}
|
||||
|
||||
/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color;
|
||||
/// a CMYK color's display color, not its naive separation, sets them.
|
||||
#[test]
|
||||
fn convert_to_oklch_answers_lightness_chroma_and_hue() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap();
|
||||
assert_eq!(r["model"], "oklch");
|
||||
let v: Vec<f64> = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}");
|
||||
let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]);
|
||||
assert!(!lowered);
|
||||
assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000");
|
||||
assert_eq!(r["hex"], "#ff0000");
|
||||
let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap();
|
||||
assert_eq!(gray["values"][2], 0.0, "{gray}");
|
||||
let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0});
|
||||
let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap();
|
||||
let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0)));
|
||||
let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]);
|
||||
let c: Vec<f64> = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
let got = [c[0] / 100.0, c[1], c[2]];
|
||||
assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}");
|
||||
assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}");
|
||||
// A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB.
|
||||
let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap();
|
||||
let w: Vec<f64> = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0));
|
||||
let clipped = vectorcraft_color::oklab::to_oklch(shown);
|
||||
assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}");
|
||||
assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}");
|
||||
assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}");
|
||||
// RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white.
|
||||
let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap();
|
||||
assert_eq!(past["hex"], "#ffffff");
|
||||
let l = past["values"][0].as_f64().unwrap();
|
||||
assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assign_profile_is_stored_and_undoable() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
|
||||
@@ -1002,6 +1002,27 @@ fn dcs_transparency_counts_a_transparent_dcs_image_over_another() {
|
||||
assert!(marked(b), "the opaque image it overlaps");
|
||||
}
|
||||
|
||||
/// Replace measures a DCS file's clipping group by its bounds, not by its plates' image, so a
|
||||
/// distorted plate image does not stop an image replacing the group.
|
||||
#[test]
|
||||
fn replace_is_not_refused_for_a_dcs_group_whose_image_is_distorted() {
|
||||
let dir = temp_dir("replace-distorted");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let mut s = session();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
|
||||
let group = r["ids"][0].clone();
|
||||
let image = image_of(&s, &group).id;
|
||||
let b = s.doc().unwrap().doc.node(image).unwrap().geometric_bounds().unwrap();
|
||||
let (x0, y0, x1, y1) = (b.x0, b.y0, b.x1, b.y1);
|
||||
let corners = json!([[x0 + 4.0, y0], [x1 - 4.0, y0], [x1, y1], [x0, y1]]);
|
||||
s.execute("object.distort", &json!({ "ids": [image.0], "corners": corners })).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image());
|
||||
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
|
||||
let png = crate::tests_links::png(2, 2, [0, 0, 255]);
|
||||
let out = s.execute("file.place", &json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
|
||||
assert!(out.is_ok(), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dcs_transparency_counts_characters_with_a_transparent_gradient() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
|
||||
@@ -579,6 +579,9 @@ fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut
|
||||
/// natural size or anything else a symbol is measured with checks them all.
|
||||
#[test]
|
||||
fn refreshing_only_changed_trees_matches_the_full_pass() {
|
||||
// Both sessions lay out type, and the test rescans the fonts: a font another test adds between
|
||||
// the full pass and the fast one would change how the type resolves in only one of them.
|
||||
let _fonts = crate::adding_fonts();
|
||||
let setup = |s: &mut Session| {
|
||||
circle_symbol(s, "Tap", 10.0);
|
||||
circle_symbol(s, "Dot", 6.0);
|
||||
|
||||
@@ -588,6 +588,81 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
|
||||
assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's");
|
||||
}
|
||||
|
||||
/// Update Links gives a distorted image its file's new pixels between the same corners: its
|
||||
/// Placement Options' fill and clip do not move or clip it. Its transform takes the new pixel size,
|
||||
/// and Link Info measures its scale at its middle.
|
||||
#[test]
|
||||
fn update_links_keeps_a_distorted_images_corners() {
|
||||
let dir = Folder::new("distorted-update");
|
||||
let photo = dir.file("photo.png");
|
||||
write(&photo, &png(20, 10, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
|
||||
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
let before = corners(&s);
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
|
||||
// The far corner of the pixels as the transform alone places them.
|
||||
let far = |s: &Session| {
|
||||
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
|
||||
im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height))
|
||||
};
|
||||
let far_before = far(&s);
|
||||
// Link Info measures the scale where the effective resolution is measured: at the middle.
|
||||
let scale_matches_ppi = |s: &mut Session| {
|
||||
let info = s.execute("links.info", &json!({"id": id.0})).unwrap();
|
||||
for i in 0..2 {
|
||||
let (scale, ppi, eff) = (info["scale"][i].as_f64().unwrap(), info["ppi"][i].as_f64().unwrap(), info["effectivePpi"][i].as_f64().unwrap());
|
||||
assert!((scale - ppi / eff * 100.0).abs() < 1e-6, "{info}");
|
||||
}
|
||||
};
|
||||
scale_matches_ppi(&mut s);
|
||||
// A copy in a symbol, distorted the same way, shows the same file.
|
||||
let copy = place(&mut s, &photo);
|
||||
s.execute("links.placementOptions", &json!({"ids": [copy.0], "preserve": "fill", "clip": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [copy.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap();
|
||||
let in_symbol = |s: &Session| {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
out.push((n.is_distorted_image(), (im.width, im.height)));
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let symbol_corners = |s: &Session| {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| out.extend(n.image_corners()));
|
||||
out
|
||||
};
|
||||
assert_eq!(in_symbol(&s), [(true, (20, 10))]);
|
||||
let symbol_before = symbol_corners(&s);
|
||||
assert_eq!(symbol_before.len(), 1);
|
||||
write(&photo, &png(60, 20, BLUE));
|
||||
let u = s.execute("links.update", &json!({})).unwrap();
|
||||
assert_eq!(u["updated"].as_array().unwrap().len(), 2, "{u}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(id).unwrap();
|
||||
assert!(n.is_distorted_image());
|
||||
assert_eq!(corners(&s), before);
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
|
||||
assert_eq!((im.width, im.height), (60, 20));
|
||||
// The transform takes the new pixel size, so a placement by the transform keeps the old size.
|
||||
assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(!matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })), "not clipped");
|
||||
let mut clipped = false;
|
||||
d.symbols[0].art.walk(&mut |n| clipped |= matches!(n.kind, NodeKind::Group { clip: true, .. }));
|
||||
assert!(!clipped, "the symbol's image is not clipped");
|
||||
assert_eq!(in_symbol(&s), [(true, (60, 20))]);
|
||||
assert_eq!(symbol_corners(&s), symbol_before, "the symbol's image keeps its corners");
|
||||
scale_matches_ppi(&mut s);
|
||||
}
|
||||
|
||||
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
|
||||
/// masks too: those showing the same content as an image in the layers, and those no object in the
|
||||
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
|
||||
|
||||
@@ -59,6 +59,107 @@ fn a_whole_rectangle_rounds_all_corners_and_given_corners_alone() {
|
||||
assert_eq!(corners(&s, id).1[3], CornerKind::Chamfer);
|
||||
}
|
||||
|
||||
/// The Corner menus of Rectangle Properties: a kind for all four corners or one, set on corners
|
||||
/// with no radius too and leaving the radii as they are, in one undo step; the kind the corners
|
||||
/// already have adds no step.
|
||||
#[test]
|
||||
fn rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"corners": [1], "radius": 12}));
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let undo = steps(&s);
|
||||
run(&mut s, json!({"corners": [0, 1, 2, 3], "kind": "invertedRound"}));
|
||||
assert_eq!(corners(&s, id).0, [0.0, 12.0, 0.0, 0.0]);
|
||||
assert_eq!(corners(&s, id).1, [CornerKind::InvertedRound; 4]);
|
||||
assert_eq!(steps(&s), undo + 1);
|
||||
run(&mut s, json!({"corners": [0, 1, 2, 3], "kind": "invertedRound"}));
|
||||
run(&mut s, json!({"corners": [2], "kind": "invertedRound"}));
|
||||
assert_eq!(steps(&s), undo + 1, "no step when nothing changes");
|
||||
run(&mut s, json!({"corners": [2], "kind": "chamfer"}));
|
||||
assert_eq!(corners(&s, id).1, [CornerKind::InvertedRound, CornerKind::InvertedRound, CornerKind::Chamfer, CornerKind::InvertedRound]);
|
||||
assert_eq!(corners(&s, id).0, [0.0, 12.0, 0.0, 0.0]);
|
||||
assert_eq!(steps(&s), undo + 2);
|
||||
}
|
||||
|
||||
/// A kind the corners already have leaves a rectangle saved stretched by an older version as it
|
||||
/// is, alone or beside a rectangle the kind changes: its scale stays in its transform.
|
||||
#[test]
|
||||
fn a_kind_the_corners_have_leaves_a_stretched_rectangle() {
|
||||
let (mut s, id) = session();
|
||||
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
let stretched = LiveShape::Rectangle {
|
||||
w: 50.0,
|
||||
h: 60.0,
|
||||
radii: [10.0; 4],
|
||||
kinds: [CornerKind::Chamfer; 4],
|
||||
radii_relative: false,
|
||||
xf: Affine::translate((10.0, 10.0)) * Affine::scale_non_uniform(2.0, 1.0),
|
||||
};
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let NodeKind::Path { path, live: Some(live), .. } = &mut d.node_mut(id).unwrap().kind else { panic!("not live") };
|
||||
**live = stretched.clone();
|
||||
*path = live.to_path();
|
||||
}
|
||||
let live = |s: &Session| node_path(s, id).1;
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let undo = steps(&s);
|
||||
run(&mut s, json!({"ids": [id.0], "kind": "chamfer"}));
|
||||
assert_eq!(live(&s), Some(stretched.clone()));
|
||||
assert_eq!(steps(&s), undo, "no step when nothing changes");
|
||||
run(&mut s, json!({"ids": [id.0, other.0], "kind": "chamfer"}));
|
||||
assert_eq!(live(&s), Some(stretched));
|
||||
assert_eq!(corners(&s, other).1, [CornerKind::Chamfer; 4]);
|
||||
assert_eq!(steps(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// A radius is stored on a corner that stores a larger radius drawn at the new value, alone or
|
||||
/// beside another rectangle; the radius every target already stores adds no undo step.
|
||||
#[test]
|
||||
fn a_radius_reaches_a_rectangle_that_already_draws_it() {
|
||||
let (mut s, id) = session();
|
||||
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
// 80 pt on every corner draws at 30 pt, half the 60 pt side.
|
||||
run(&mut s, json!({"ids": [id.0], "radius": 80}));
|
||||
assert_eq!(corners(&s, id).0, [80.0; 4]);
|
||||
let (path, live) = node_path(&s, id);
|
||||
let drawn = LiveCorners::new(&path, live.as_ref()).unwrap().drawn_radius(0);
|
||||
assert!((drawn - 30.0).abs() < 1e-9, "draws at {drawn}");
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let undo = steps(&s);
|
||||
run(&mut s, json!({"ids": [id.0], "corners": [1], "radius": 30}));
|
||||
assert_eq!(corners(&s, id).0, [80.0, 30.0, 80.0, 80.0]);
|
||||
assert_eq!(steps(&s), undo + 1);
|
||||
run(&mut s, json!({"ids": [id.0, other.0], "corners": [0], "radius": 30}));
|
||||
assert_eq!(corners(&s, id).0[0], 30.0);
|
||||
assert_eq!(corners(&s, other).0[0], 30.0);
|
||||
// The radius both already store adds no step.
|
||||
run(&mut s, json!({"ids": [id.0, other.0], "corners": [0], "radius": 30}));
|
||||
assert_eq!(steps(&s), undo + 2);
|
||||
}
|
||||
|
||||
/// `rectanglesOnly` sets the live rectangles among the selection and leaves a polygon as it is; an
|
||||
/// action that records it holds no ids, so playing it sets the rectangles selected then.
|
||||
#[test]
|
||||
fn rectangles_only_sets_the_selected_rectangles_when_an_action_plays() {
|
||||
let (mut s, id) = session();
|
||||
let polygon = NodeId(s.execute("shape.polygon", &json!({"cx": 300, "cy": 300, "radius": 40, "sides": 6})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0, polygon.0]})).unwrap();
|
||||
let start = s.journal.len();
|
||||
run(&mut s, json!({"rectanglesOnly": true, "corners": [0], "kind": "chamfer"}));
|
||||
assert_eq!(corners(&s, id).1[0], CornerKind::Chamfer);
|
||||
let NodeKind::Path { live: Some(l), .. } = &s.doc().unwrap().doc.node(polygon).unwrap().kind else { panic!("not live") };
|
||||
let LiveShape::Polygon { kinds, .. } = &**l else { panic!("not a polygon") };
|
||||
assert!(kinds.iter().all(|k| *k == CornerKind::Round), "the polygon keeps its corners: {kinds:?}");
|
||||
let action = s.journal_for_action(start);
|
||||
assert_eq!(action.len(), 1);
|
||||
assert_eq!(action[0].1.get("ids"), None);
|
||||
let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [other.0, polygon.0]})).unwrap();
|
||||
s.replay(&action[0].0, &action[0].1).unwrap();
|
||||
assert_eq!(corners(&s, other).1[0], CornerKind::Chamfer);
|
||||
}
|
||||
|
||||
/// #938: `items` rounds several objects in one step, each its own corners (or all of them).
|
||||
#[test]
|
||||
fn items_round_several_objects_each_its_own_corners() {
|
||||
|
||||
@@ -707,12 +707,13 @@ fn an_effect_parameter_without_a_default_is_held_to_its_type() {
|
||||
use crate::cmd::params::undefaulted_type;
|
||||
use vectorcraft_render::effects::effect_catalog;
|
||||
// Read by checks of their own: a stored texture or a texture to load, an SVG filter and its axes, a Warp's
|
||||
// map and the style of Crop Marks.
|
||||
// map, the style of Crop Marks and a custom bevel's name and points.
|
||||
let own_check = |effect: &str, key: &str| match key {
|
||||
"textureImage" | "name" | "xml" => true,
|
||||
"axes" => effect == "svg.filter",
|
||||
"version" => effect.starts_with("warp."),
|
||||
"style" => effect == "cropMarks",
|
||||
"bevelName" | "bevelProfile" => matches!(effect, "threeD.extrude" | "threeD.classicExtrude"),
|
||||
_ => false,
|
||||
};
|
||||
let mut unlisted = vec![];
|
||||
|
||||
@@ -1907,6 +1907,166 @@ fn pathfinder_journal_entries_replay_with_the_options_they_used() {
|
||||
assert!(s.execute("object.pathfinder.divide", &json!({"precision": 20})).is_err());
|
||||
}
|
||||
|
||||
/// The leaf objects of `n`, in paint order.
|
||||
fn leaves_of(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::Node>) {
|
||||
match n.children() {
|
||||
Some(children) => children.iter().for_each(|c| leaves_of(c, out)),
|
||||
None => out.push(n.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the live Pathfinder effect `effect` with `params` to the selection, then expand its
|
||||
/// appearance: the objects it draws.
|
||||
fn live_pieces(s: &mut Session, effect: &str, params: Value) -> Vec<vectorcraft_doc::Node> {
|
||||
let g = ids(&s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap())[0];
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
|
||||
let mut out = vec![];
|
||||
leaves_of(&node(s, g), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The parameters of the first effect of the selected object.
|
||||
fn first_effect_params(s: &Session) -> Value {
|
||||
let st = s.doc().unwrap();
|
||||
st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[0].params.clone()
|
||||
}
|
||||
|
||||
/// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those its params
|
||||
/// give aside, and its journal entry carries them.
|
||||
#[test]
|
||||
fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
|
||||
s.execute("object.pathfinder.options", &json!({"precision": 1, "removeRedundantPoints": true, "removeUnpainted": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap();
|
||||
let all = json!({"precision": 1.0, "removeRedundantPoints": true, "removeUnpainted": true});
|
||||
assert_eq!(first_effect_params(&s), all);
|
||||
assert_eq!(s.journal.last().unwrap().1["params"], all, "the journal entry gives the options it used");
|
||||
s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"precision": 0.5}})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let mix = &st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[1].params;
|
||||
assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true}));
|
||||
}
|
||||
|
||||
/// A live Pathfinder effect evaluates with its own options as the panel's operations do with
|
||||
/// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled
|
||||
/// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing.
|
||||
#[test]
|
||||
fn a_pathfinder_effect_evaluates_with_its_own_options() {
|
||||
for (precision, faces) in [(0.01, 3), (1.0, 2)] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 0.0, 99.5, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
assert_eq!(live_pieces(&mut s, "pathfinder.divide", json!({"precision": precision})).len(), faces, "precision {precision}");
|
||||
}
|
||||
for on in [false, true] {
|
||||
let mut s = session();
|
||||
filled_and_unfilled(&mut s);
|
||||
let divided = live_pieces(&mut s, "pathfinder.divide", json!({"removeUnpainted": on}));
|
||||
let unfilled = divided.iter().filter(|n| n.appearance.fill_paint().is_none()).count();
|
||||
assert_eq!((unfilled, divided.len() - unfilled), (if on { 0 } else { 2 }, 1), "removeUnpainted {on}");
|
||||
}
|
||||
for on in [false, true] {
|
||||
let mut s = session();
|
||||
let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
|
||||
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
|
||||
let a = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 20.0, 20.0, 60.0, 60.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let united = live_pieces(&mut s, "pathfinder.add", json!({"removeRedundantPoints": on}));
|
||||
let count = united[0].path_data().unwrap().anchor_count();
|
||||
assert!(if on { count == 4 } else { count > 4 }, "removeRedundantPoints {on}: {count} anchors");
|
||||
}
|
||||
}
|
||||
|
||||
/// An effect saved before Pathfinder effects kept their own options draws as one given their
|
||||
/// defaults, so older documents look as they did.
|
||||
#[test]
|
||||
fn a_pathfinder_effect_saved_without_options_draws_as_before() {
|
||||
let draw = |params: Value| {
|
||||
let mut s = session();
|
||||
filled_and_unfilled(&mut s);
|
||||
let g = ids(&s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap())[0];
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(g).unwrap().appearance.effects[0].params = params;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
|
||||
serde_json::to_value(node(&s, g)).unwrap()
|
||||
};
|
||||
assert_eq!(draw(json!({})), draw(json!({"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false})));
|
||||
}
|
||||
|
||||
/// `effect.setParams` edits a Pathfinder effect's options as one undo step, records none for the
|
||||
/// values it already evaluates with, and refuses values out of range or of the wrong type.
|
||||
#[test]
|
||||
fn pathfinder_effect_options_edit_as_one_step_and_refuse_bad_values() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();
|
||||
let before = steps(&s);
|
||||
let same = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 0.01, "removeUnpainted": false}})).unwrap();
|
||||
assert_eq!((same, steps(&s)), (json!({"ids": []}), before), "the values it has: no step");
|
||||
// An effect saved without options evaluates with the defaults: given them, it is unchanged.
|
||||
let g = s.doc().unwrap().selection.objects[0];
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(g).unwrap().appearance.effects[0].params = json!({});
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = steps(&s);
|
||||
let defaults = json!({"index": 0, "params": {"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false}});
|
||||
assert_eq!(s.execute("effect.setParams", &defaults).unwrap(), json!({"ids": []}));
|
||||
assert_eq!(steps(&s), before);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 2, "removeRedundantPoints": true}})).unwrap();
|
||||
assert_eq!(steps(&s), before + 1, "one step");
|
||||
assert_eq!(first_effect_params(&s), json!({"precision": 2, "removeRedundantPoints": true}));
|
||||
let kept = doc(&s);
|
||||
for bad in [
|
||||
json!({"precision": 0}),
|
||||
json!({"precision": 11}),
|
||||
json!({"precision": "1 pt"}),
|
||||
json!({"precision": null}),
|
||||
json!({"removeRedundantPoints": "yes"}),
|
||||
json!({"removeUnpainted": 1}),
|
||||
] {
|
||||
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": bad})).is_err(), "setParams {bad}");
|
||||
assert!(s.execute("effect.apply", &json!({"effect": "pathfinder.trim", "params": bad})).is_err(), "apply {bad}");
|
||||
assert_eq!(doc(&s), kept, "{bad} changes nothing");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(first_effect_params(&s), json!({}), "undo restores the options");
|
||||
}
|
||||
|
||||
/// A precision that Scale Strokes & Effects took past the range evaluates at its bound, and setting
|
||||
/// the bound is still an edit: a later scale then starts from the value set.
|
||||
#[test]
|
||||
fn a_precision_set_after_a_scale_past_its_range_is_kept() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "pathfinder.add", "params": {"precision": 8}})).unwrap();
|
||||
let precision = |s: &Session| first_effect_params(s)["precision"].as_f64();
|
||||
s.execute("object.scale", &json!({"sx": 200, "strokes": true})).unwrap();
|
||||
assert_eq!(precision(&s), Some(16.0));
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let out = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 10}})).unwrap();
|
||||
assert_ne!(out, json!({"ids": []}), "an edit");
|
||||
assert_eq!((precision(&s), s.doc().unwrap().history.undo.len()), (Some(10.0), steps + 1));
|
||||
s.execute("object.scale", &json!({"sx": 50, "strokes": true})).unwrap();
|
||||
assert_eq!(precision(&s), Some(5.0));
|
||||
// The value it stores is still no edit.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 5}})).unwrap(), json!({"ids": []}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
}
|
||||
|
||||
/// A single group containing multiple overlapping paths is accepted by Crop.
|
||||
#[test]
|
||||
fn crop_operates_on_a_single_selected_group_of_paths() {
|
||||
|
||||
@@ -1422,6 +1422,26 @@ fn theme_picker_marquee_takes_the_area_and_picks_add_up() {
|
||||
assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]);
|
||||
}
|
||||
|
||||
/// A distorted image is read where its pixels are drawn, between its corners.
|
||||
#[test]
|
||||
fn theme_picker_reads_a_distorted_image_where_it_is_drawn() {
|
||||
let mut s = session();
|
||||
let (id, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]);
|
||||
let (x, y0, y1) = (b.x1 + 20.0, b.y0, b.y1);
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "object.distort", json!({"corners": [[x + 40.0, y0], [x + 60.0, y0], [x + 100.0, y1], [x, y1]]}));
|
||||
// The lower left of the trapezoid, outside the rectangle the image was placed in: red.
|
||||
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [x + 2.0, y1 - 4.0, x + 20.0, y1 - 1.0]}]})), ["rgb 255 0 0"]);
|
||||
// Where the image was: nothing.
|
||||
assert!(pick_theme(&mut s, json!({"picks": [{"rect": [b.x0 + 1.0, b.y0 + 1.0, b.x1 - 1.0, b.y1 - 1.0]}]})).is_empty());
|
||||
// A marquee reaching past the horizon its sides meet at (a quarter of its height above its
|
||||
// top) still reads every pixel it covers.
|
||||
let h = y1 - y0;
|
||||
let mut both = pick_theme(&mut s, json!({"picks": [{"rect": [x - 10.0, y0 - h, x + 110.0, y1 + 1.0]}]}));
|
||||
both.sort();
|
||||
assert_eq!(both, ["rgb 0 0 255", "rgb 255 0 0"]);
|
||||
}
|
||||
|
||||
/// Pixels less than half opaque are left out, and so is an image whose pixels can't be read.
|
||||
#[test]
|
||||
fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() {
|
||||
|
||||
@@ -180,6 +180,48 @@ fn average_at_the_mean_adds_no_undo_step() {
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
|
||||
/// An instance the brush reaches but leaves as it is (the Symbol Screener with Alt on an opaque
|
||||
/// instance, or without Alt on one at the lowest opacity it gives) is not counted, and a stroke
|
||||
/// that changes no instance adds no undo step.
|
||||
#[test]
|
||||
fn an_instance_left_as_it_is_is_not_counted() {
|
||||
let mut s = session();
|
||||
let (opaque, faint) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
|
||||
s.execute("transparency.set", &json!({"ids": [faint.0], "opacity": 5})).unwrap();
|
||||
let before = state(&s);
|
||||
let r = adjust(&mut s, json!({"tool": "screen", "points": [[100, 150]], "radius": 30, "intensity": 10, "alt": true}));
|
||||
assert_eq!(r["count"], 0, "Alt on an opaque instance");
|
||||
let r = adjust(&mut s, json!({"tool": "screen", "points": [[300, 150]], "radius": 30, "intensity": 10}));
|
||||
assert_eq!(r["count"], 0, "an instance at 5%");
|
||||
assert!(state(&s) == before, "a stroke that changes nothing changed the document or its history");
|
||||
// A stroke over both counts only the instance it changes.
|
||||
let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 150, "intensity": 10}));
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(node(&s, opaque).opacity < 1.0 && node(&s, faint).opacity == 0.05);
|
||||
}
|
||||
|
||||
/// Average gives an opacity below 5% when that is the mean: the Symbol Sprayer's new instance and
|
||||
/// the Symbol Screener's instances take the mean of the instances under the brush.
|
||||
#[test]
|
||||
fn average_keeps_a_mean_opacity_below_five_percent() {
|
||||
let mut s = session();
|
||||
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
|
||||
let first = members(&s, set)[0];
|
||||
s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 2})).unwrap();
|
||||
s.select(|_, sel| sel.set([set])).unwrap();
|
||||
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[215, 150]], "radius": 30})).unwrap();
|
||||
let sprayed = *members(&s, set).last().unwrap();
|
||||
assert!((node(&s, sprayed).opacity - 0.02).abs() < 1e-6, "{}", node(&s, sprayed).opacity);
|
||||
// Two instances at 0% and 4%: Average brings both toward 2%, and neither goes past it.
|
||||
let mut s = session();
|
||||
let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0));
|
||||
s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 0})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [b.0], "opacity": 4})).unwrap();
|
||||
adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"}));
|
||||
let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity);
|
||||
assert!(pa > 0.0 && pa <= 0.02 + 1e-6 && (0.02 - 1e-6..0.04).contains(&pb), "{pa} {pb}");
|
||||
}
|
||||
|
||||
/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing.
|
||||
#[test]
|
||||
fn average_evens_out_the_stain_and_the_spacing() {
|
||||
@@ -279,6 +321,38 @@ fn an_unknown_method_is_refused() {
|
||||
assert_eq!(center(&s, a), Point::new(200.0, 150.0));
|
||||
}
|
||||
|
||||
/// `tool.setOption` refuses a Symbolism Tools Options value of the wrong kind or name, and the
|
||||
/// tool's options stay as they were.
|
||||
#[test]
|
||||
fn tool_set_option_refuses_bad_symbolism_options() {
|
||||
let mut s = session();
|
||||
let before = s.tool_options_of("symbolSizer");
|
||||
for (key, bad, want) in [
|
||||
("method", json!("smooth"), "`method` must be one of userDefined, average, random"),
|
||||
("sprayStain", json!("random"), "`sprayStain` must be one of average, userDefined"),
|
||||
("usePressure", json!("yes"), "`usePressure` must be true or false"),
|
||||
("diameter", json!("big"), "`diameter` must be a number from 2 to 2000"),
|
||||
("style", json!(3), "`style` must be a string or null"),
|
||||
("diameter", json!(1), "`diameter` must be a number from 2 to 2000"),
|
||||
] {
|
||||
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}}));
|
||||
assert_eq!(r, Err(want.to_string()), "{key}");
|
||||
assert_eq!(s.tool_options_of("symbolSizer"), before, "{key}");
|
||||
}
|
||||
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap();
|
||||
assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined")));
|
||||
// Every option the options dialog sends is taken, together.
|
||||
let all = json!({
|
||||
"diameter": 100.0, "intensity": 6.0, "density": 4.0, "usePressure": true, "method": "average", "showBrush": false,
|
||||
"sprayScrunch": "userDefined", "spraySize": "userDefined", "spraySpin": "userDefined", "sprayScreen": "userDefined",
|
||||
"sprayStain": "average", "sprayStyle": "userDefined", "proportional": false, "affectsDensity": true,
|
||||
});
|
||||
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": all})).unwrap();
|
||||
for (key, v) in all.as_object().unwrap() {
|
||||
assert_eq!(&r[key], v, "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is
|
||||
/// not used. A pressure that isn't a number is an error.
|
||||
#[test]
|
||||
@@ -316,6 +390,13 @@ fn pen_pressure_is_the_intensity_with_use_pressure() {
|
||||
json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}),
|
||||
"a point's pressure must be a number, not \"hard\"",
|
||||
);
|
||||
// Also on a point without coordinates, beside one that has them.
|
||||
refused(
|
||||
&mut s,
|
||||
"symbol.adjust",
|
||||
json!({"tool": tool, "points": [[200, 150], [null, 0, "bad"]], "usePressure": true}),
|
||||
"a point's pressure must be a number, not \"bad\"",
|
||||
);
|
||||
}
|
||||
for key in ["usePressure", "proportional", "affectsDensity"] {
|
||||
let mut p = json!({"tool": "size", "points": [[200, 150]]});
|
||||
@@ -644,6 +725,45 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() {
|
||||
assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a));
|
||||
}
|
||||
|
||||
/// A set duplicated packs from the density recorded for its source, and a pasted set from the
|
||||
/// density its source had at Copy: after Cut, after the source is given another density, and in
|
||||
/// another document.
|
||||
#[test]
|
||||
fn a_copied_set_packs_from_the_density_of_its_source() {
|
||||
for copy in ["duplicate", "paste", "cut", "changed after copy", "other document"] {
|
||||
let mut s = session();
|
||||
let row: Vec<Value> = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect();
|
||||
let set =
|
||||
NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
s.select(|_, sel| sel.set([set])).unwrap();
|
||||
let first = match copy {
|
||||
"duplicate" => "edit.duplicate",
|
||||
"cut" => "edit.cut",
|
||||
_ => "edit.copy",
|
||||
};
|
||||
s.execute(first, &json!({})).unwrap();
|
||||
if copy == "changed after copy" {
|
||||
s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap();
|
||||
}
|
||||
if copy == "other document" {
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
}
|
||||
if copy != "duplicate" {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
let copied = s.doc().unwrap().selection.objects.clone();
|
||||
assert!(copied.len() == 1 && (copy == "other document" || copied[0] != set), "{copy}: {copied:?}");
|
||||
let ids = members(&s, copied[0]);
|
||||
let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::<Vec<_>>();
|
||||
let was = xs(&s);
|
||||
let middle = was.iter().sum::<f64>() / 4.0;
|
||||
s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [copied[0].0]})).unwrap();
|
||||
for (before, after) in was.iter().zip(xs(&s)) {
|
||||
assert!((after - (middle + (before - middle) * 0.25 / 0.95)).abs() < 1e-9, "{copy}: {before} -> {after}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of one instance takes the new density without moving, as one undo step, so a later change
|
||||
/// packs it from that density; setting the density it already has adds no undo step.
|
||||
#[test]
|
||||
@@ -719,6 +839,102 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() {
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
|
||||
/// The Symbol Styler applies the style gradually, by the brush's strength at the instance: the pen
|
||||
/// pressure with Use Pressure Pen, else the intensity, less toward the brush's edge. Random gives
|
||||
/// each instance a share of that amount.
|
||||
#[test]
|
||||
fn the_styler_applies_the_style_by_the_brushs_strength() {
|
||||
let styled = |extra: Value, x: f64| {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 100.0, 150.0);
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
let mut p = json!({"tool": "style", "points": [[x, 150]], "radius": 10, "style": "Blue"});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
adjust(&mut s, p);
|
||||
node(&s, a).appearance.fill().map_or(0.0, |f| f.opacity)
|
||||
};
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 1e-6;
|
||||
assert!(near(styled(json!({"intensity": 10}), 100.0), 1.0), "full strength at the center");
|
||||
assert!(near(styled(json!({"intensity": 5}), 100.0), 0.5));
|
||||
assert!(near(styled(json!({"intensity": 10}), 105.0), 0.5), "half way to the edge");
|
||||
assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25));
|
||||
assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0));
|
||||
assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style");
|
||||
// Random: instances the same distance from the point take different amounts, each from none to
|
||||
// the User Defined amount there (0.25: pressure 0.5, half way to the brush's edge).
|
||||
let mut s = session();
|
||||
let ring: Vec<NodeId> = (0..6)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) * std::f64::consts::TAU / 6.0;
|
||||
dot(&mut s, 100.0 + 5.0 * a.cos(), 150.0 + 5.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
adjust(&mut s, json!({"tool": "style", "points": [[100, 150, 0.5]], "radius": 10, "usePressure": true, "method": "random", "style": "Blue"}));
|
||||
let amounts: Vec<f32> = ring.iter().map(|a| node(&s, *a).appearance.fill().map_or(0.0, |f| f.opacity)).collect();
|
||||
assert!(amounts.iter().all(|a| *a <= 0.25 + 1e-6), "{amounts:?}");
|
||||
assert!(amounts.iter().any(|a| *a > 0.0), "{amounts:?}");
|
||||
assert!(amounts.iter().any(|a| (a - amounts[0]).abs() > 1e-6), "{amounts:?}");
|
||||
}
|
||||
|
||||
/// A sprayed instance's Average stain is the stain of the nearest instance whose stain shows: one
|
||||
/// at no opacity is passed over and counts as no stain in the mean amount.
|
||||
#[test]
|
||||
fn average_spray_passes_over_a_stain_at_no_opacity() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
let set =
|
||||
NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [130, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
|
||||
let ids = members(&s, set);
|
||||
assert_eq!(ids.len(), 2);
|
||||
s.edit("Stains", |d, _| {
|
||||
for (id, color, amount) in [(ids[0], Color::rgb(1.0, 0.0, 0.0), 0.0), (ids[1], Color::rgb(0.0, 0.0, 1.0), 1.0)] {
|
||||
let n = d.node_mut(id).unwrap();
|
||||
n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_)));
|
||||
let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
|
||||
f.opacity = amount;
|
||||
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 40})).unwrap();
|
||||
let new: Vec<NodeId> = members(&s, set).into_iter().filter(|id| !ids.contains(id)).collect();
|
||||
assert_eq!(new.len(), 1);
|
||||
let f = node(&s, new[0]).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
assert!((f.opacity - 0.5).abs() < 1e-6, "{}", f.opacity);
|
||||
}
|
||||
|
||||
/// The Symbol Shifter moves an instance whose transform flattens it (it has no size), as it moves
|
||||
/// any other, and counts it.
|
||||
#[test]
|
||||
fn the_shifter_moves_an_instance_without_a_size() {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 200.0, 150.0);
|
||||
s.edit("Flatten", |d, _| {
|
||||
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) {
|
||||
*xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [210, 150]], "radius": 40, "intensity": 10}));
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(center(&s, a).x > 200.0, "{:?}", center(&s, a));
|
||||
// Average has no mean of such instances to move toward: it leaves them as they are.
|
||||
let (before, x) = (state(&s), center(&s, a).x);
|
||||
let r = adjust(&mut s, json!({"tool": "screen", "method": "average", "points": [[x, 150]], "radius": 40, "intensity": 10}));
|
||||
assert_eq!(r["count"], 0);
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
|
||||
/// An instance with no size is shifted and screened as before; only Average, which needs its size,
|
||||
/// leaves it as it is.
|
||||
#[test]
|
||||
@@ -759,6 +975,29 @@ fn an_instance_without_a_size_is_changed_by_every_method_but_average() {
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
|
||||
/// Average Stainer: an instance whose stain is at no opacity has no stain of its own, so it takes
|
||||
/// the stain the mean picks, not its hidden paint.
|
||||
#[test]
|
||||
fn average_stain_replaces_a_stain_at_no_opacity() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 120.0, 150.0));
|
||||
s.edit("Stains", |d, _| {
|
||||
for (id, color, amount) in [(a, Color::rgb(1.0, 0.0, 0.0), 0.0), (b, Color::rgb(0.0, 0.0, 1.0), 1.0)] {
|
||||
let n = d.node_mut(id).unwrap();
|
||||
let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
|
||||
f.opacity = amount;
|
||||
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
adjust(&mut s, json!({"tool": "stain", "method": "average", "points": [[100, 150]], "radius": 40, "intensity": 10}));
|
||||
let f = node(&s, a).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
assert!(f.opacity > 0.0, "{}", f.opacity);
|
||||
}
|
||||
|
||||
/// A stroke that leaves every instance under the brush as it is (each already at full stain, or
|
||||
/// at the least opacity) counts none and adds no undo step.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
//! The symbolism tools' Shift forms in `symbol.adjust {shift}`: the Symbol Shifter's stacking
|
||||
//! order, the Symbol Sizer keeping the set's density, and the Symbol Stainer and Symbol Styler
|
||||
//! keeping their amount while the color or style changes.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A document with the 20 pt square symbol "Dot" and nothing selected.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Dot"})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// An instance of Dot centered on (`x`, `y`), not selected.
|
||||
fn dot(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap());
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn center(s: &Session, id: NodeId) -> Point {
|
||||
match node(s, id).kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => xf * Point::ZERO,
|
||||
other => panic!("not an instance: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn width(s: &Session, id: NodeId) -> f64 {
|
||||
node(s, id).geometric_bounds().unwrap().width()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn state(s: &Session) -> (Document, usize) {
|
||||
((*s.doc().unwrap().doc).clone(), undo_len(s))
|
||||
}
|
||||
|
||||
fn adjust(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("symbol.adjust", &p).unwrap()
|
||||
}
|
||||
|
||||
/// The children of symbol set `set`, in stacking order (the first is at the back).
|
||||
fn members(s: &Session, set: NodeId) -> Vec<NodeId> {
|
||||
node(s, set).children().unwrap().iter().map(|c| c.id).collect()
|
||||
}
|
||||
|
||||
/// The instance's fill: its color as RGB and its amount.
|
||||
fn fill(s: &Session, id: NodeId) -> Option<([f32; 3], f32)> {
|
||||
node(s, id).appearance.fill().map(|f| (f.paint.color().map_or([0.0; 3], |c| c.to_rgb()), f.opacity))
|
||||
}
|
||||
|
||||
/// A symbol set of four instances in a row at x = 40, 120, 200 and 280, selected.
|
||||
fn row(s: &mut Session) -> (NodeId, Vec<NodeId>) {
|
||||
let pts: Vec<Value> = (0..4).map(|i| json!([40.0 + 80.0 * f64::from(i), 150.0])).collect();
|
||||
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": pts, "radius": 4})).unwrap()["id"].as_u64().unwrap());
|
||||
let ids = members(s, set);
|
||||
assert_eq!(ids.len(), 4);
|
||||
(set, ids)
|
||||
}
|
||||
|
||||
/// Shift-click with the Symbol Shifter brings the instances under the brush one place forward in
|
||||
/// the set, and Alt+Shift-click sends them one place backward, without moving them on the canvas.
|
||||
#[test]
|
||||
fn shift_click_with_the_shifter_changes_the_stacking_order() {
|
||||
let mut s = session();
|
||||
let (set, ids) = row(&mut s);
|
||||
let centers: Vec<Point> = ids.iter().map(|id| center(&s, *id)).collect();
|
||||
let click = |s: &mut Session, x: f64, alt: bool| {
|
||||
adjust(s, json!({"tool": "shift", "points": [[x, 150]], "radius": 10, "intensity": 10, "shift": true, "alt": alt}))["count"].clone()
|
||||
};
|
||||
let steps = undo_len(&s);
|
||||
assert_eq!(click(&mut s, 120.0, false), 1);
|
||||
assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
|
||||
assert_eq!(undo_len(&s), steps + 1, "one undo step");
|
||||
assert_eq!(ids.iter().map(|id| center(&s, *id)).collect::<Vec<_>>(), centers, "nothing moves on the canvas");
|
||||
assert_eq!(click(&mut s, 120.0, false), 1);
|
||||
assert_eq!(members(&s, set), [ids[0], ids[2], ids[3], ids[1]]);
|
||||
// Already in front of the others: nothing changes and no undo step is added.
|
||||
let before = state(&s);
|
||||
assert_eq!(click(&mut s, 120.0, false), 0);
|
||||
assert!(state(&s) == before);
|
||||
// Alt sends it back one place at a time; at the back it stays.
|
||||
assert_eq!(click(&mut s, 120.0, true), 1);
|
||||
assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
|
||||
click(&mut s, 120.0, true);
|
||||
click(&mut s, 120.0, true);
|
||||
assert_eq!(members(&s, set), [ids[1], ids[0], ids[2], ids[3]]);
|
||||
assert_eq!(click(&mut s, 120.0, true), 0);
|
||||
// Two instances under the brush move together past the next one.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let both = adjust(&mut s, json!({"tool": "shift", "points": [[40, 150], [120, 150]], "radius": 10, "intensity": 10, "shift": true}));
|
||||
assert_eq!(both["count"], 2);
|
||||
assert_eq!(members(&s, set), [ids[2], ids[0], ids[1], ids[3]]);
|
||||
// Without Shift a drag moves the instances, as before.
|
||||
adjust(&mut s, json!({"tool": "shift", "points": [[280, 150], [290, 150]], "radius": 30, "intensity": 10}));
|
||||
assert!(center(&s, ids[3]).x > centers[3].x);
|
||||
}
|
||||
|
||||
/// Shift with the Symbol Sizer resizes the instances and keeps their centers where they are, even
|
||||
/// with Resizing Affects Density.
|
||||
#[test]
|
||||
fn shift_with_the_sizer_keeps_the_density() {
|
||||
let at = |affects: bool, shift: bool| {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 220.0, 150.0);
|
||||
adjust(
|
||||
&mut s,
|
||||
json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "affectsDensity": affects, "shift": shift}),
|
||||
);
|
||||
(center(&s, a), width(&s, a))
|
||||
};
|
||||
let (moved, _) = at(true, false);
|
||||
assert!(moved.x > 220.5, "{moved:?}");
|
||||
let (kept, grown) = at(true, true);
|
||||
assert!((kept.x - 220.0).abs() < 1e-9 && (kept.y - 150.0).abs() < 1e-9 && grown > 20.5, "{kept:?} {grown}");
|
||||
// It resizes as the Sizer does with Resizing Affects Density off.
|
||||
assert_eq!(at(false, false), (kept, grown));
|
||||
assert_eq!(at(false, true), (kept, grown));
|
||||
}
|
||||
|
||||
/// Shift with the Symbol Stainer keeps the stain's amount and moves its color toward the fill
|
||||
/// color; an instance without a stain is left as it is.
|
||||
#[test]
|
||||
fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() {
|
||||
let mut s = session();
|
||||
let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
|
||||
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
|
||||
let (red, amount) = fill(&s, a).unwrap();
|
||||
assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}");
|
||||
// A second fill below the stain, which Shift leaves as it is.
|
||||
s.edit("Add fill", |d, _| {
|
||||
let n = d.node_mut(a).unwrap();
|
||||
let lower = n.appearance.fill().unwrap().clone();
|
||||
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { opacity: 0.5, ..lower }));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let lower = node(&s, a).appearance.items[0].clone();
|
||||
let stain = |s: &mut Session, x: f64| {
|
||||
adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true}))
|
||||
};
|
||||
assert_eq!(stain(&mut s, 100.0)["count"], 1);
|
||||
let (color, kept) = fill(&s, a).unwrap();
|
||||
assert_eq!(kept, amount, "the amount stays");
|
||||
assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}");
|
||||
assert_eq!((node(&s, a).appearance.items.len(), &node(&s, a).appearance.items[0]), (2, &lower), "the other fill stays");
|
||||
// More strokes go on toward blue, with the amount still the same.
|
||||
for _ in 0..30 {
|
||||
stain(&mut s, 100.0);
|
||||
}
|
||||
let (bluer, kept) = fill(&s, a).unwrap();
|
||||
assert_eq!(kept, amount);
|
||||
assert!(bluer[2] > 0.9 && bluer[0] < 0.1, "{bluer:?}");
|
||||
// Alt has no effect with Shift.
|
||||
let green = json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#00ff00", "shift": true});
|
||||
adjust(&mut s, green.clone());
|
||||
let plain = fill(&s, a);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let mut with_alt = green;
|
||||
with_alt["alt"] = json!(true);
|
||||
adjust(&mut s, with_alt);
|
||||
assert_eq!(fill(&s, a), plain);
|
||||
// No stain on b: nothing changes and no undo step is added.
|
||||
let before = state(&s);
|
||||
assert_eq!(stain(&mut s, 300.0)["count"], 0);
|
||||
assert!(state(&s) == before && fill(&s, b).is_none());
|
||||
}
|
||||
|
||||
/// Shift with the Symbol Styler keeps the amount of the instance's stain or style and moves its
|
||||
/// fill toward the selected style's fill.
|
||||
#[test]
|
||||
fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 100.0, 150.0);
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
// A red stain at part strength.
|
||||
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
|
||||
let (red, amount) = fill(&s, a).unwrap();
|
||||
assert!(red[0] > 0.99 && amount > 0.0 && amount < 0.5, "{red:?} {amount}");
|
||||
// Half the brush's strength at a point 2.5 pt from the instance: half way to blue.
|
||||
adjust(&mut s, json!({"tool": "style", "points": [[102.5, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
|
||||
let (mixed, kept) = fill(&s, a).unwrap();
|
||||
assert_eq!(kept, amount);
|
||||
assert!(mixed[0] < 0.99 && mixed[2] > 0.01, "{mixed:?}");
|
||||
// At the brush's center with full intensity it takes the style's fill.
|
||||
adjust(&mut s, json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
|
||||
let (blue, kept) = fill(&s, a).unwrap();
|
||||
assert_eq!(kept, amount);
|
||||
assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}");
|
||||
}
|
||||
|
||||
/// A stain or style with no form between it and the new paint (a pattern and a solid color) takes
|
||||
/// the new paint at once, at any strength, and keeps its amount.
|
||||
#[test]
|
||||
fn shift_changes_a_paint_that_has_no_form_in_between() {
|
||||
use vectorcraft_color::Paint;
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 100.0, 150.0);
|
||||
s.edit("Pattern fill", |d, _| {
|
||||
let mut f = vectorcraft_doc::FillLayer::new(Paint::Pattern { pattern: "Tile".into(), xf: Default::default() });
|
||||
f.opacity = 0.4;
|
||||
d.node_mut(a).unwrap().appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Low intensity, near the brush's edge: far below half strength.
|
||||
let r = adjust(&mut s, json!({"tool": "stain", "points": [[104, 150]], "radius": 5, "intensity": 1, "color": "#ff0000", "shift": true}));
|
||||
assert_eq!(r["count"], 1);
|
||||
let f = node(&s, a).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(f.opacity, 0.4, "the amount stays");
|
||||
assert!(f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.99), "{:?}", f.paint);
|
||||
}
|
||||
|
||||
/// A style name the document has no style for (the Styler's style from another document, or one
|
||||
/// since renamed or deleted) moves the fill toward the document's first style after the default
|
||||
/// one, as no name does, and the stain's amount stays.
|
||||
#[test]
|
||||
fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let styled = |style: Option<&str>| {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 100.0, 150.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
|
||||
let mut p = json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "shift": true});
|
||||
if let Some(n) = style {
|
||||
p["style"] = json!(n);
|
||||
}
|
||||
let stained = node(&s, a).appearance.fill().map(|f| f.opacity);
|
||||
adjust(&mut s, p);
|
||||
let f = node(&s, a).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(Some(f.opacity), stained, "the amount stays");
|
||||
let first = s.doc().unwrap().doc.graphic_styles[1].appearance.fill_paint();
|
||||
(f.paint, first)
|
||||
};
|
||||
let (missing, first) = styled(Some("No Such Style"));
|
||||
let (none, _) = styled(None);
|
||||
assert_eq!(missing, none);
|
||||
// The paint is the first style's, not the active fill color.
|
||||
assert_eq!(none, first);
|
||||
assert_ne!(none, Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
/// A `shift` that is not true, false or null is refused and changes nothing.
|
||||
#[test]
|
||||
fn a_bad_shift_is_refused() {
|
||||
let mut s = session();
|
||||
dot(&mut s, 100.0, 150.0);
|
||||
for tool in ["shift", "size", "stain", "style"] {
|
||||
let before = state(&s);
|
||||
let r = s.execute("symbol.adjust", &json!({"tool": tool, "points": [[100, 150]], "shift": "yes"}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "`shift` must be true or false"), "{tool}: {r:?}");
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,86 @@ fn a_dropped_press_does_not_keep_what_its_drag_changed() {
|
||||
assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides");
|
||||
}
|
||||
|
||||
/// An option set with `tool.setOption` while a press is held survives the dropped press, in the
|
||||
/// tool and in the stored options, while what the drag itself changed is put back in both.
|
||||
#[test]
|
||||
fn an_option_set_during_a_dropped_press_is_kept() {
|
||||
let mut s = session();
|
||||
select(&mut s, "rectangularGrid");
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
|
||||
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
|
||||
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
|
||||
assert_eq!((s.tool_options()["rows"].clone(), s.tool_options()["columns"].clone()), (json!(6), json!(6)));
|
||||
s.set_tool_option_cmd(&json!({"key": "columns", "value": 9})).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
let o = s.tool_options();
|
||||
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "the drag's rows go back; the set columns stay");
|
||||
let saved = &s.prefs.tool_settings["rectangularGrid"];
|
||||
assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(9)), "the drag's rows are not stored; the set columns are");
|
||||
select(&mut s, "selection");
|
||||
select(&mut s, "rectangularGrid");
|
||||
let o = s.tool_options();
|
||||
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "a tool switch keeps the set columns");
|
||||
// The same through the desktop app's setter.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
|
||||
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
|
||||
s.set_tool_option("columns", &json!(3));
|
||||
s.drop_tool_press(v).unwrap();
|
||||
let o = s.tool_options();
|
||||
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(3)));
|
||||
let saved = &s.prefs.tool_settings["rectangularGrid"];
|
||||
assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(3)));
|
||||
}
|
||||
|
||||
/// A Corner Radius preference set while a Rounded Rectangle press is held survives the dropped
|
||||
/// press, in the tool and in the preference.
|
||||
#[test]
|
||||
fn a_corner_radius_set_during_a_dropped_press_is_kept() {
|
||||
let mut s = session();
|
||||
select(&mut s, "roundedRectangle");
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
|
||||
let mut p = s.prefs.clone();
|
||||
p.corner_radius = 30.0;
|
||||
s.apply_prefs(p);
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
|
||||
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
|
||||
}
|
||||
|
||||
/// An option set with `tool.setOption` on a tool that lent a selection tool for a Cmd-drag
|
||||
/// survives the dropped press, in the tool and in the stored options. So does a Corner Radius
|
||||
/// preference set while the Rounded Rectangle lends one.
|
||||
#[test]
|
||||
fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() {
|
||||
let mut s = session();
|
||||
select(&mut s, "rectangularGrid");
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
let cmd = Mods { cmd: true, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("rectangularGrid"), "the press lent a selection tool");
|
||||
s.set_tool_option_cmd(&json!({"tool": "rectangularGrid", "key": "columns", "value": 9})).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert_eq!(s.tool_id(), "rectangularGrid", "the lending tool is back");
|
||||
assert_eq!(s.tool_options()["columns"], json!(9), "the tool keeps the set columns");
|
||||
assert_eq!(s.prefs.tool_settings["rectangularGrid"]["columns"], json!(9), "and stores them");
|
||||
select(&mut s, "roundedRectangle");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("roundedRectangle"), "the press lent a selection tool");
|
||||
let mut p = s.prefs.clone();
|
||||
p.corner_radius = 30.0;
|
||||
s.apply_prefs(p);
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
|
||||
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
|
||||
}
|
||||
|
||||
/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with
|
||||
/// the next click.
|
||||
#[test]
|
||||
|
||||
@@ -754,6 +754,406 @@ fn distort_perspective_midpoint_is_projective() {
|
||||
assert!((c.y - 100.0 / 6.0).abs() < 1e-3, "{c:?}");
|
||||
}
|
||||
|
||||
/// A 2 × 2 px image placed at (0, 0)–(100, 100), selected.
|
||||
fn placed_image(s: &mut Session) -> NodeId {
|
||||
s.edit("Place", |d, sel| {
|
||||
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![]));
|
||||
let id = d.alloc_id();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "pic".into(),
|
||||
width: 2,
|
||||
height: 2,
|
||||
xf: vectorcraft_geom::Affine::scale(50.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(d.default_layer(), 0, Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn corners(s: &Session, id: NodeId) -> [Point; 4] {
|
||||
s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap()
|
||||
}
|
||||
|
||||
fn assert_corners(got: [Point; 4], want: [(f64, f64); 4]) {
|
||||
for (g, (x, y)) in got.iter().zip(want) {
|
||||
assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?} against {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Perspective Distort and Free Distort put an image's corners exactly on the handles, in one
|
||||
/// undo step; the image is bounded and clicked by its corners, and a move takes them along.
|
||||
#[test]
|
||||
fn distort_puts_an_images_corners_on_the_handles() {
|
||||
for want in [[(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)], [(10.0, 5.0), (90.0, 0.0), (120.0, 110.0), (0.0, 100.0)]] {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
let undo = undo_len(&s);
|
||||
let corners_json: Vec<[f64; 2]> = want.iter().map(|(x, y)| [*x, *y]).collect();
|
||||
s.execute("object.distort", &json!({ "corners": corners_json })).unwrap();
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert_corners(corners(&s, img), want);
|
||||
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
|
||||
let b = bounds(&s, img);
|
||||
let xs = want.map(|c| c.0);
|
||||
let ys = want.map(|c| c.1);
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
|
||||
assert!(near(b.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(b.x1, xs.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
|
||||
assert!(near(b.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(b.y1, ys.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
|
||||
s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap();
|
||||
assert_corners(corners(&s, img), want.map(|(x, y)| (x + 10.0, y + 20.0)));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
|
||||
}
|
||||
// Clicks: inside the trapezoid hits the image; inside its old square but outside the
|
||||
// trapezoid does not.
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let opt = vectorcraft_doc::hit::HitOptions::default();
|
||||
assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(50.0, 50.0), opt).map(|h| h.leaf), Some(img));
|
||||
assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(5.0, 10.0), opt).map(|h| h.leaf), None);
|
||||
}
|
||||
|
||||
/// Distorted together with a path, the image's corners and the path's anchors follow one warp.
|
||||
#[test]
|
||||
fn distort_moves_an_image_and_a_path_as_one() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
let path = rect(&mut s, 100.0, 0.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [200, 100], [50, 100]]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let anchors: Vec<Point> = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
|
||||
let q = corners(&s, img);
|
||||
// The image's right edge and the path's left edge were one line, and stay one where the warp
|
||||
// moves it.
|
||||
assert!(q[2].distance(Point::new(100.0, 100.0)) > 1.0, "{q:?}");
|
||||
for p in [q[1], q[2]] {
|
||||
assert!(anchors.iter().any(|a| a.distance(p) < 1e-9), "{p:?} not in {anchors:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Corners that would fold an image over are refused: nothing changes and no undo step is kept.
|
||||
/// A distorted image keeps its distortion where commands that cannot keep it are asked to work.
|
||||
#[test]
|
||||
fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
|
||||
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [0, 100], [100, 100]]})).unwrap_err().to_string();
|
||||
assert!(e.contains("convex"), "{e}");
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
// Three corners on one line give no perspective map at all.
|
||||
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [100, 50], [0, 100]]})).unwrap_err().to_string();
|
||||
assert!(e.contains("convex"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
// A convex shape too small for a perspective map: the corners could not reach the handles.
|
||||
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1e-7, 0], [8e-8, 1e-7], [0, 1e-7]]})).unwrap_err().to_string();
|
||||
assert!(e.contains("too close together"), "{e}");
|
||||
// The same shape far from the origin: its distance from it does not hide the missed corner.
|
||||
let x = 1_000_000.0;
|
||||
let e = s.execute("object.distort", &json!({"corners": [[x, 0], [x + 1e-7, 0], [x + 8e-8, 1e-7], [x, 1e-7]]})).unwrap_err().to_string();
|
||||
assert!(e.contains("too close together"), "{e}");
|
||||
// A long, thin shape with one side all but gone.
|
||||
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1_000_000, 0], [1_000_000, 1e-19], [0, 1]]})).unwrap_err().to_string();
|
||||
assert!(e.contains("too close together"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
// A small shape near the edge of the canvas is still distorted.
|
||||
let o = vectorcraft_doc::MAX_COORD - 2.0;
|
||||
let far = [[o, o], [o + 1.0, o], [o + 0.2130712, o + 1.0], [o, o + 1.0]];
|
||||
s.execute("object.distort", &json!({ "from": [0, 0, 100, 100], "corners": far })).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
for (cmd, params) in [
|
||||
("object.cropImage", json!({})),
|
||||
("imageTrace.make", json!({})),
|
||||
("links.relink", json!({"path": "/nowhere/pic.png"})),
|
||||
// Refused before the folder is searched, so a file missing there does not hide it.
|
||||
("links.relink", json!({"folder": "/nowhere"})),
|
||||
("links.embed", json!({"ids": [img.0]})),
|
||||
("links.unembed", json!({})),
|
||||
// Refused before any file is written.
|
||||
("links.unembed", json!({"folder": "/nowhere"})),
|
||||
("object.createObjectMosaic", json!({})),
|
||||
("object.mesh.create", json!({})),
|
||||
(
|
||||
"file.place",
|
||||
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
|
||||
),
|
||||
] {
|
||||
let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
// Every command gives the one shared refusal, which the complete-message catalogs translate.
|
||||
assert!(e.contains("is an image changed by Perspective Distort or Free Distort, which this command does not work on"), "{cmd}: {e}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
// Type replaces a distorted image by its bounds, which the corners give: not refused.
|
||||
let text = json!({"replace": true, "name": "note.txt", "dataBase64": vectorcraft_format::base64_encode(b"Hello")});
|
||||
let out = s.execute("file.place", &text).unwrap();
|
||||
let id = NodeId(out["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Text(_)));
|
||||
}
|
||||
|
||||
/// Create Gradient Mesh on a path and a distorted image converts the path and names the image it
|
||||
/// left as it is, with the shared refusal.
|
||||
#[test]
|
||||
fn mesh_create_reports_the_distorted_image_it_skips() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
let path = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
|
||||
let out = s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap();
|
||||
assert_eq!(out["ids"].as_array().map(Vec::len), Some(1), "{out}");
|
||||
let skipped = out["skipped"].as_array().expect("the skipped image");
|
||||
assert_eq!(skipped.len(), 1, "{out}");
|
||||
assert_eq!(skipped[0]["id"], json!(img.0));
|
||||
assert!(skipped[0]["reason"].as_str().unwrap().contains("Perspective Distort or Free Distort"), "{out}");
|
||||
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
|
||||
// Without a distorted image, no `skipped`.
|
||||
let other = rect(&mut s, 400.0, 0.0, 100.0, 100.0);
|
||||
let out = s.execute("object.mesh.create", &json!({"ids": [other.0], "rows": 1, "cols": 1})).unwrap();
|
||||
assert!(out.get("skipped").is_none(), "{out}");
|
||||
}
|
||||
|
||||
/// A blend takes the warp's affine approximation whole, so an image inside it does not stop a
|
||||
/// distort whose corners an image could not follow.
|
||||
#[test]
|
||||
fn distort_of_a_blend_holding_an_image_is_not_refused() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
let r = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
|
||||
let out = s.execute("object.blend.make", &json!({"ids": [img.0, r.0]})).unwrap();
|
||||
let blend = NodeId(out["id"].as_u64().unwrap());
|
||||
let undo = undo_len(&s);
|
||||
s.execute("object.distort", &json!({"ids": [blend.0], "corners": [[0, 0], [300, 0], [100, 50], [0, 100]]})).unwrap();
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
|
||||
}
|
||||
|
||||
/// The Control bar's Mask clips a distorted image to the shape between its corners.
|
||||
#[test]
|
||||
fn mask_on_a_distorted_image_follows_its_corners() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
let want = [(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
let out = s.execute("object.maskImage", &json!({})).unwrap();
|
||||
let path = NodeId(out["path"].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let anchors: Vec<Point> = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
|
||||
assert_eq!(anchors.len(), 4, "{anchors:?}");
|
||||
for (x, y) in want {
|
||||
assert!(anchors.iter().any(|a| a.distance(Point::new(x, y)) < 1e-9), "{x},{y} not in {anchors:?}");
|
||||
}
|
||||
assert!(d.node(img).unwrap().is_distorted_image());
|
||||
}
|
||||
|
||||
/// A Transform effect moves a distorted image's corners with it: expanded, the image stands
|
||||
/// where the effect drew it.
|
||||
#[test]
|
||||
fn a_transform_effect_moves_a_distorted_images_corners() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let mut found = vec![];
|
||||
for layer in &s.doc().unwrap().doc.layers {
|
||||
layer.walk(&mut |n| {
|
||||
if let Some(q) = n.image_corners() {
|
||||
found.push(q);
|
||||
}
|
||||
});
|
||||
}
|
||||
let want = [(240.0, 0.0), (260.0, 0.0), (300.0, 100.0), (200.0, 100.0)];
|
||||
assert!(found.iter().any(|q| q.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-6)), "{found:?}");
|
||||
}
|
||||
|
||||
/// A Transform effect after a Warp effect moves a distorted image's warped pixels once: the art
|
||||
/// stands where the Warp alone draws it, moved by the Transform.
|
||||
#[test]
|
||||
fn a_transform_after_a_warp_moves_a_distorted_image_once() {
|
||||
let expanded_bounds = |transform: bool| {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "warp.bulge", "params": {"bend": 50}})).unwrap();
|
||||
if transform {
|
||||
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let mut images = None;
|
||||
for layer in &s.doc().unwrap().doc.layers {
|
||||
layer.walk(&mut |n| {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
let r = im.xf.transform_rect_bbox(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)));
|
||||
images = Some(images.map_or(r, |b: vectorcraft_geom::Rect| b.union(r)));
|
||||
}
|
||||
});
|
||||
}
|
||||
images.expect("the warped pieces")
|
||||
};
|
||||
let (alone, moved) = (expanded_bounds(false), expanded_bounds(true));
|
||||
assert!((moved.x0 - alone.x0 - 200.0).abs() < 1e-6 && (moved.x1 - alone.x1 - 200.0).abs() < 1e-6, "{alone:?} {moved:?}");
|
||||
assert!((moved.y0 - alone.y0).abs() < 1e-6 && (moved.y1 - alone.y1).abs() < 1e-6, "{alone:?} {moved:?}");
|
||||
}
|
||||
|
||||
/// A raster effect's baked pixels already show the distortion: the image that replaces a
|
||||
/// distorted one is placed by its own transform.
|
||||
#[test]
|
||||
fn baked_raster_effect_pixels_replace_a_distortion() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
let v = s.doc().unwrap().doc.node(img).unwrap().clone();
|
||||
let baked = Node::new(NodeId(99), v.kind.clone());
|
||||
let out = crate::cmd::rasterfx::replace_with_image(v, baked);
|
||||
assert!(!out.is_distorted_image());
|
||||
assert!(out.extras().image_quad.is_none());
|
||||
}
|
||||
|
||||
/// A distorted image is saved with its corners and reads back the same.
|
||||
#[test]
|
||||
fn a_distorted_image_saves_and_reads_back() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let bytes = vectorcraft_format::save(doc, false);
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(back.node(img).unwrap().image_corners(), doc.node(img).unwrap().image_corners());
|
||||
assert!(back.node(img).unwrap().is_distorted_image());
|
||||
assert!(String::from_utf8_lossy(&bytes).contains("image_quad"));
|
||||
// An image without a distortion is saved without the field, and opens as it was.
|
||||
let mut plain = session();
|
||||
let img = placed_image(&mut plain);
|
||||
let doc = &plain.doc().unwrap().doc;
|
||||
let bytes = vectorcraft_format::save(doc, false);
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("image_quad"));
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(back.node(img), doc.node(img));
|
||||
// Corners in a file that fold the image over leave it placed by its transform.
|
||||
let mut bad = (**doc).clone();
|
||||
bad.node_mut(img).unwrap().extras_mut().image_quad =
|
||||
Some(Box::new([(0.0, 0.0), (100.0, 0.0), (0.0, 100.0), (100.0, 100.0)].map(|(x, y)| Point::new(x, y))));
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&bad, false)).unwrap();
|
||||
assert!(!back.node(img).unwrap().is_distorted_image());
|
||||
assert_corners(back.node(img).unwrap().image_corners().unwrap(), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
}
|
||||
|
||||
/// A distort whose corners cross the warp's horizon at the image is refused with that reason, and
|
||||
/// a distort that leaves a distorted image where it is records nothing.
|
||||
#[test]
|
||||
fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
|
||||
// The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at
|
||||
// y = 15, inside the image.
|
||||
let e = s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string();
|
||||
assert!(e.contains("horizon"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
|
||||
let b = bounds(&s, img);
|
||||
let at = [[b.x0, b.y0], [b.x1, b.y0], [b.x1, b.y1], [b.x0, b.y1]];
|
||||
s.execute("object.distort", &json!({ "from": [b.x0, b.y0, b.x1, b.y1], "corners": at })).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// Image info gives a distorted image's resolution at its middle, not the resolution it had
|
||||
/// before the distort.
|
||||
#[test]
|
||||
fn image_info_measures_a_distorted_image_at_its_middle() {
|
||||
let mut s = session();
|
||||
placed_image(&mut s);
|
||||
// 2 pixels across 100 pt: 1.44 ppi.
|
||||
let ppi = |s: &mut Session| {
|
||||
let out = s.execute("image.info", &json!({})).unwrap();
|
||||
[out["ppi"][0].as_f64().unwrap(), out["ppi"][1].as_f64().unwrap()]
|
||||
};
|
||||
assert!((ppi(&mut s)[0] - 1.44).abs() < 1e-9);
|
||||
// The top squeezed to half the width: the middle of the pixels spans less than 100 pt across,
|
||||
// so the resolution across there is higher.
|
||||
s.execute("object.distort", &json!({ "corners": [[25, 0], [75, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
let [x, _] = ppi(&mut s);
|
||||
assert!(x > 1.44 * 1.1, "{x}");
|
||||
}
|
||||
|
||||
/// Rasterize draws a distorted image's pixels between its corners, and the image it makes is a
|
||||
/// plain one.
|
||||
#[test]
|
||||
fn rasterize_draws_a_distorted_image_between_its_corners() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
let mut png = std::io::Cursor::new(vec![]);
|
||||
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();
|
||||
s.edit("Pixels", |d, _| {
|
||||
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png.into_inner()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
|
||||
s.execute("select.set", &json!({ "ids": [img.0] })).unwrap();
|
||||
let out = s.execute("object.rasterize", &json!({ "ppi": 72, "background": "transparent", "addAround": 0 })).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let id = NodeId(out["id"].as_u64().unwrap());
|
||||
let n = d.node(id).unwrap();
|
||||
assert!(!n.is_distorted_image());
|
||||
let vectorcraft_doc::NodeKind::Image(im) = &n.kind else { panic!("an image") };
|
||||
// The raster covers the corners' bounds.
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!([b.x0, b.y0, b.x1 - 100.0, b.y1 - 100.0].iter().all(|v| v.abs() <= 1.0), "{b:?}");
|
||||
let px = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap();
|
||||
let (w, h) = px.dimensions();
|
||||
let rgba = px.to_rgba8();
|
||||
let alpha = |x: f64, y: f64| {
|
||||
let p = im.xf.inverse() * Point::new(x, y);
|
||||
assert!(p.x >= 0.0 && p.y >= 0.0 && p.x < f64::from(w) && p.y < f64::from(h), "({x}, {y}) is outside the raster: {p:?}");
|
||||
let (i, j) = (p.x as u32, p.y as u32);
|
||||
rgba[((j * w + i) * 4 + 3) as usize]
|
||||
};
|
||||
assert_eq!(alpha(50.0, 90.0), 255, "inside the corners");
|
||||
assert_eq!(alpha(10.0, 10.0), 0, "inside the old rectangle, outside the corners");
|
||||
}
|
||||
|
||||
/// A Free Transform drag in Free Distort mode on an image puts the dragged corner where the drag
|
||||
/// ends, in one undo step, also when a position on the way would have folded the image.
|
||||
#[test]
|
||||
fn free_transform_distort_drag_on_an_image_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
let img = placed_image(&mut s);
|
||||
let undo = undo_len(&s);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("freeTransform", v).unwrap();
|
||||
s.set_tool_option("mode", &json!("distort"));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
// Past the top left corner: the image would fold over.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, -50.0, -50.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 120.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 120.0), v).unwrap();
|
||||
assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (130.0, 120.0), (0.0, 100.0)]);
|
||||
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_transform_distort_mode_via_pointer() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -298,6 +298,10 @@ impl Session {
|
||||
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
|
||||
lent.set_option("meshPoints", &points);
|
||||
}
|
||||
// The Cmd/Ctrl held for the loan is not the Cmd/Ctrl that mirrors a dragged handle (#7842).
|
||||
if id == "directSelection" {
|
||||
lent.set_option("lentByCmd", &Value::Bool(true));
|
||||
}
|
||||
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
|
||||
self.lender = Some(std::mem::replace(&mut self.tool, lent));
|
||||
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
|
||||
@@ -611,13 +615,18 @@ impl Session {
|
||||
/// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what
|
||||
/// the tool asks for along the way, only a cancel and a notify run, so a marquee selects
|
||||
/// nothing and a click opens no size dialog. The tool gets back the persistent options it had
|
||||
/// when the press began, and none of the press's changes to them are stored. A dropped Type
|
||||
/// press restores the prior selection. The freeform gradient point selected once the tool
|
||||
/// took the press is selected again. A press held while the tool computes an edit on another
|
||||
/// thread has not reached the tool: it is removed from the held input with the pointer events
|
||||
/// and tool keys held after it, and the tool is left as it is. A perspective plane key held
|
||||
/// after it stays held, since the plane it picks outlasts a dropped press. Pointer events held
|
||||
/// after the last held release belong to the press the tool has, and are removed with it.
|
||||
/// when the press began, and none of the press's changes to them are stored. An option set
|
||||
/// during the press with [`Self::set_tool_option`] or [`Self::set_tool_options`], or a General ›
|
||||
/// Corner Radius change during a Rounded Rectangle press, keeps its new value, also when the
|
||||
/// tool lent a selection tool for the press (a Cmd-drag). Setting an option stores all of the
|
||||
/// tool's options, the press's changes included, so the dropped press then stores the options
|
||||
/// it puts back. A dropped Type press restores the prior selection. The freeform gradient
|
||||
/// point selected once the tool took the press is selected again. A press held while the tool
|
||||
/// computes an edit on another thread has not reached the tool: it is removed from the held
|
||||
/// input with the pointer events and tool keys held after it, and the tool is left as it is.
|
||||
/// A perspective plane key held after it stays held, since the plane it picks outlasts a
|
||||
/// dropped press. Pointer events held after the last held release belong to the press the tool
|
||||
/// has, and are removed with it.
|
||||
pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> {
|
||||
let (from, held) = self.held_press();
|
||||
let keep: Vec<bool> = (self.held_input.iter().enumerate())
|
||||
@@ -635,6 +644,7 @@ impl Session {
|
||||
// Nothing to roll back without a document; the tool still drops the press and gets the release.
|
||||
let _ = self.cancel_interaction();
|
||||
let before = self.press_options.take();
|
||||
let stored = std::mem::take(&mut self.press_options_stored);
|
||||
let type_selection = self.press_type_selection.take();
|
||||
let point = self.press_point.take();
|
||||
let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx));
|
||||
@@ -669,6 +679,11 @@ impl Session {
|
||||
self.tool.set_option(k, v);
|
||||
}
|
||||
}
|
||||
// An option set during the press stored every option the tool had then, the press's
|
||||
// changes included: those stored values are put back too.
|
||||
if stored {
|
||||
self.keep_tool_settings();
|
||||
}
|
||||
}
|
||||
r.map(drop)
|
||||
}
|
||||
@@ -706,6 +721,7 @@ impl Session {
|
||||
match ev.kind {
|
||||
PointerKind::Down => {
|
||||
self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref())));
|
||||
self.press_options_stored = false;
|
||||
self.press_type_selection =
|
||||
if matches!(self.tool.id(), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath") {
|
||||
self.active().map(|st| (st.selection.clone(), st.active_layer))
|
||||
@@ -715,6 +731,7 @@ impl Session {
|
||||
}
|
||||
PointerKind::Up => {
|
||||
self.press_options = None;
|
||||
self.press_options_stored = false;
|
||||
self.press_type_selection = None;
|
||||
}
|
||||
_ => {}
|
||||
@@ -1309,9 +1326,12 @@ impl Session {
|
||||
if key == "queue" && self.tool.id() == "place" {
|
||||
self.note_place_queue_roots();
|
||||
}
|
||||
let before_press = self.options_before_press_set();
|
||||
let sets_pressed = self.press_taken_by(self.tool.id());
|
||||
self.tool.set_option(key, v);
|
||||
self.tool_set_since_reset = true;
|
||||
self.keep_tool_settings();
|
||||
self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed);
|
||||
}
|
||||
|
||||
/// Keep the automation roots in force now as those the place cursor's queue, being loaded,
|
||||
@@ -1356,6 +1376,8 @@ impl Session {
|
||||
self.note_place_queue_roots();
|
||||
}
|
||||
let active = id.is_none_or(|id| id == self.tool.id());
|
||||
let before_press = self.options_before_press_set();
|
||||
let sets_pressed = self.press_taken_by(id.unwrap_or(self.tool.id()));
|
||||
// The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again
|
||||
// when the drag ends.
|
||||
let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id));
|
||||
@@ -1393,9 +1415,46 @@ impl Session {
|
||||
let set = other.id();
|
||||
Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store));
|
||||
}
|
||||
self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed);
|
||||
out
|
||||
}
|
||||
|
||||
/// The tool that took the press under way: the active tool, or the tool that lent a selection
|
||||
/// tool for it (a Cmd-drag), which the dropped press gives its options back to.
|
||||
fn pressed_tool(&self) -> Option<&dyn Tool> {
|
||||
let (pressed, _) = self.press_options.as_ref()?;
|
||||
std::iter::once(&self.tool).chain(self.lender.as_ref()).map(|t| t.as_ref()).find(|t| t.id() == pressed)
|
||||
}
|
||||
|
||||
/// Tool `id` took the press under way ([`Self::pressed_tool`]).
|
||||
pub(crate) fn press_taken_by(&self, id: &str) -> bool {
|
||||
self.pressed_tool().is_some_and(|t| t.id() == id)
|
||||
}
|
||||
|
||||
/// The persistent options of the tool that took the press under way ([`Self::pressed_tool`])
|
||||
/// before an option is set: a dropped press puts back the options it began with, except those
|
||||
/// the set changes ([`Self::keep_press_set`]).
|
||||
fn options_before_press_set(&self) -> Option<Map<String, Value>> {
|
||||
self.pressed_tool().map(Self::persistent_options)
|
||||
}
|
||||
|
||||
/// After an option is set during a held press, the press's saved options take the options of
|
||||
/// the tool that took the press that the set changed from `before` or named (`named`), so a
|
||||
/// dropped press keeps them. `stored`: the set stored that tool's options, the press's changes
|
||||
/// included, so a dropped press stores the options it puts back.
|
||||
fn keep_press_set(&mut self, before: Option<Map<String, Value>>, named: impl Fn(&str) -> bool, stored: bool) {
|
||||
let Some(before) = before else { return };
|
||||
let Some(now) = self.pressed_tool().map(Self::persistent_options) else { return };
|
||||
self.press_options_stored |= stored;
|
||||
if let Some((_, saved)) = self.press_options.as_mut() {
|
||||
for (k, v) in now {
|
||||
if before.get(&k) != Some(&v) || named(&k) {
|
||||
saved.insert(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the
|
||||
/// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default:
|
||||
/// the tool active when the call arrives, named before the edit in progress is finished) → its
|
||||
@@ -1519,6 +1578,10 @@ impl Session {
|
||||
/// Apply tool actions. Errors from previews are reported but keep the interaction alive.
|
||||
pub fn apply_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
|
||||
let outer = std::mem::replace(&mut self.in_tool_actions, true);
|
||||
let outer_bucket = self.back_to_bucket;
|
||||
// The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket.
|
||||
self.back_to_bucket |=
|
||||
self.tool.id() == "eyedropper" && acts.iter().any(|a| matches!(a, Action::SwitchTool(t) if t == crate::cmd::LIVE_PAINT_BUCKET));
|
||||
// A preview that settling applied (typing kept as its own step before a drag begins) shows
|
||||
// its warning in the status bar, as the tool's own commit shows its preview's.
|
||||
let r = if !outer && self.depth == 0 {
|
||||
@@ -1528,6 +1591,7 @@ impl Session {
|
||||
self.apply_tool_actions(acts)
|
||||
};
|
||||
self.in_tool_actions = outer;
|
||||
self.back_to_bucket = outer_bucket;
|
||||
if !outer && self.depth == 0 {
|
||||
self.trim_histories();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user