mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 11:05:03 +00:00
Merge remote-tracking branch 'origin/main' into fix/8479
# Conflicts: # crates/engine/src/cmd/brushlib.rs # 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/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 # docs/gaps.md # docs/mcp.md # docs/roadmap.md # docs/target-app-parity.md # docs/ui-parity.md
This commit is contained in:
@@ -907,7 +907,7 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry};
|
||||
pub use buildcmds::{TracePreset, TracePresetChange};
|
||||
|
||||
/// An Image Trace made off the UI thread, and what it traced (#3098).
|
||||
pub use buildcmds::{TraceRun, Traced};
|
||||
pub use buildcmds::{TraceRun, Traced, image_trace_target};
|
||||
|
||||
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
|
||||
pub(crate) use buildcmds::TracePresetChanges;
|
||||
|
||||
@@ -175,6 +175,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
|
||||
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
|
||||
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: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
|
||||
@@ -182,6 +183,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
|
||||
BuiltinBrushLibrary { id: "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 },
|
||||
@@ -274,6 +276,49 @@ fn artistic() -> BrushLibrary {
|
||||
)
|
||||
}
|
||||
|
||||
/// Original fine-line art for an engraving-style brush library.
|
||||
fn engraving() -> BrushLibrary {
|
||||
let lines = |count: usize, width: f64, spacing: f64| {
|
||||
group(
|
||||
(0..count)
|
||||
.map(|i| {
|
||||
let y = (i as f64 - (count - 1) as f64 / 2.0) * spacing;
|
||||
black(shapes::rectangle(Rect::new(0.0, y - width / 2.0, 100.0, y + width / 2.0)))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
let taper = group(
|
||||
(0..5)
|
||||
.map(|i| {
|
||||
let y = (i as f64 - 2.0) * 2.2;
|
||||
black(polygon(&[(0.0, y - 0.35), (80.0, y - 0.35), (100.0, y), (80.0, y + 0.35), (0.0, y + 0.35)]))
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let broken = group(
|
||||
(0..5)
|
||||
.flat_map(|row| {
|
||||
(0..4).map(move |segment| {
|
||||
let x = segment as f64 * 25.0 + if row % 2 == 0 { 0.0 } else { 8.0 };
|
||||
let y = (row as f64 - 2.0) * 2.2;
|
||||
black(shapes::rectangle(Rect::new(x, y - 0.3, (x + 16.0).min(100.0), y + 0.3)))
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
built(
|
||||
"Engraving",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
art("Fine Hatching", lines(5, 0.65, 2.2), Colorization::Tints),
|
||||
art("Dense Hatching", lines(9, 0.42, 1.2), Colorization::Tints),
|
||||
art("Tapered Hatching", taper, Colorization::Tints),
|
||||
art("Broken Hatching", broken, Colorization::Tints),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length).
|
||||
fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush {
|
||||
Brush {
|
||||
@@ -587,6 +632,45 @@ fn spacer(r: Rect) -> Node {
|
||||
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
|
||||
}
|
||||
|
||||
/// Paint: original filled vector art with broad, broken, loaded, and fanned marks. Each is one
|
||||
/// stroke stretched along the path, with an intentionally different edge and paint distribution.
|
||||
fn paint() -> BrushLibrary {
|
||||
let flat_sweep = group(vec![
|
||||
black(band(100.0, 5.0, 64, |x| 0.8 * (x / 100.0 * std::f64::consts::TAU).sin())),
|
||||
black(polygon(&[(0.0, -2.5), (7.0, -3.8), (18.0, -2.5)])),
|
||||
black(polygon(&[(78.0, 2.5), (94.0, 4.0), (100.0, 2.5)])),
|
||||
]);
|
||||
let mut dry_drag = vec![];
|
||||
for (y, shift) in [(-5.0, 0.0), (-3.2, 4.0), (-1.3, 1.0), (0.8, 6.0), (2.8, 3.0), (4.8, 8.0)] {
|
||||
dry_drag.push(black(shapes::rectangle(Rect::new(2.0 + shift, y, 35.0 + shift, y + 0.8))));
|
||||
dry_drag.push(black(shapes::rectangle(Rect::new(40.0 + shift, y, 75.0 - shift / 2.0, y + 0.8))));
|
||||
dry_drag.push(black(shapes::rectangle(Rect::new(80.0 - shift / 2.0, y, 98.0, y + 0.8))));
|
||||
}
|
||||
let mut loaded_stroke = vec![black(band(100.0, 6.0, 64, |x| 1.2 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin()))];
|
||||
for (x, r) in [(12.0, 4.2), (39.0, 3.6), (64.0, 4.8), (88.0, 3.9)] {
|
||||
loaded_stroke.push(black(shapes::ellipse(Rect::new(x - r, -r - 1.5, x + r, r + 1.5))));
|
||||
}
|
||||
let mut fan_sweep = vec![];
|
||||
for i in -2..=2 {
|
||||
let offset = i as f64;
|
||||
fan_sweep.push(black(band(100.0, 1.2, 48, |x| offset * (1.4 + x * 0.045) + 0.3 * (x / 100.0 * std::f64::consts::TAU).sin())));
|
||||
}
|
||||
let paint_art = |name: &str, art: Node| Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Art(ArtBrush { art, width: 150.0, colorization: Colorization::Tints, ..Default::default() }),
|
||||
};
|
||||
built(
|
||||
"Paint",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
paint_art("Flat Sweep", flat_sweep),
|
||||
paint_art("Dry Drag", group(dry_drag)),
|
||||
paint_art("Loaded Stroke", group(loaded_stroke)),
|
||||
paint_art("Fan Sweep", group(fan_sweep)),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles.
|
||||
fn pattern_borders() -> BrushLibrary {
|
||||
let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)]));
|
||||
|
||||
@@ -42,7 +42,7 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced};
|
||||
pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target};
|
||||
use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view};
|
||||
|
||||
/// Name of an Image Trace group.
|
||||
|
||||
@@ -606,6 +606,30 @@ struct Prepared {
|
||||
library: Vec<([u8; 3], Paint)>,
|
||||
}
|
||||
|
||||
/// The object `imageTrace.make` would trace, without preparing settings or reading image bytes.
|
||||
pub fn image_trace_target(s: &Session, p: &Value) -> Result<NodeId> {
|
||||
target_image(s, "imageTrace.make", p).map(|(target, _)| target)
|
||||
}
|
||||
|
||||
fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObject>)> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
roots
|
||||
.iter()
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ if is_trace_group(n) => match &n.children()?.first()?.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))
|
||||
}
|
||||
|
||||
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
|
||||
fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let mut params = trace_params(s, c, p)?;
|
||||
@@ -625,25 +649,7 @@ 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(),
|
||||
};
|
||||
let roots = root_ids(s, p)?;
|
||||
// The image (inside a trace group, or selected directly).
|
||||
let (target, image) = {
|
||||
let d = &s.doc()?.doc;
|
||||
roots
|
||||
.iter()
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ if is_trace_group(n) => match &n.children()?.first()?.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))?
|
||||
};
|
||||
let (target, image) = target_image(s, c, p)?;
|
||||
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
|
||||
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
|
||||
}
|
||||
|
||||
@@ -26,6 +26,8 @@ use vectorcraft_render::proof;
|
||||
use super::EngineError;
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param};
|
||||
|
||||
pub mod proof_file;
|
||||
|
||||
/// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated
|
||||
/// to `Document::color_profiles` on load).
|
||||
pub const PROFILES_KEY: &str = vectorcraft_doc::profiles::LEGACY_PROFILES_KEY;
|
||||
@@ -100,10 +102,46 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Proof Setup",
|
||||
["View", "Proof Setup"],
|
||||
None,
|
||||
"{target?: \"workingCmyk\"|\"cmyk:<profile>\"|\"legacyMacRgb\"|\"srgb\"|\"monitorRgb\"|\"protanopia\"|\"deuteranopia\"|\"tritanopia\", intent?, simulatePaper?, proof?: bool (also turn Proof Colors on)} → proof state",
|
||||
"{target?: \"workingCmyk\"|\"cmyk:<profile>\"|\"rgb:<profile>\"|\"legacyMacRgb\"|\"srgb\"|\"monitorRgb\"|\"protanopia\"|\"deuteranopia\"|\"tritanopia\" (cmyk: and rgb: name a CMYK or RGB profile of color.loadProfile or the built-in ones: the device to simulate), intent? (used while preserveNumbers is off), simulatePaper?: bool, preserveNumbers?: bool (Preserve CMYK or RGB Numbers: the colors' numbers in the document's space go to the device unchanged), simulateBlack?: bool (Simulate Black Ink: the device's black shows as the dark gray it prints; simulatePaper does this too; CMYK devices only, as simulatePaper), proof?: bool (also turn Proof Colors on)} → proof state",
|
||||
always,
|
||||
proof_setup
|
||||
),
|
||||
cmd!(
|
||||
query "view.proofSetup.save",
|
||||
"Save Proof Setup…",
|
||||
[],
|
||||
None,
|
||||
"{path?: file | name?: a setup in the Proof Setups folder next to the preferences (at most 100 characters and no path characters; exactly one of the two), target?, intent?, simulatePaper?, preserveNumbers?, simulateBlack? (as view.proofSetup; default: the current proof setup's)} write a custom proof setup to a VectorCraft proof setup file (.vcproof, JSON) without changing the proof view. The target must be a device: workingCmyk, cmyk:<profile> or rgb:<profile> → {path, target, intent, simulatePaper, preserveNumbers, simulateBlack}",
|
||||
always,
|
||||
proof_file::save
|
||||
),
|
||||
cmd!(
|
||||
query "view.proofSetup.load",
|
||||
"Load Proof Setup…",
|
||||
[],
|
||||
None,
|
||||
"{path?: file | name?: a setup in the Proof Setups folder (exactly one of the two)} read a proof setup file of at most 64 KiB that view.proofSetup.save wrote, make it the proof setup and turn Proof Colors on → {path} and the proof state. A file whose device names a profile that is not loaded is refused and nothing changes",
|
||||
always,
|
||||
proof_file::load
|
||||
),
|
||||
cmd!(
|
||||
query "view.proofSetup.read",
|
||||
"Read Proof Setup",
|
||||
[],
|
||||
None,
|
||||
"{path?: file | name?: a setup in the Proof Setups folder (exactly one of the two)} the settings of a proof setup file, read as view.proofSetup.load reads it, without changing the proof view → {path, target, intent, simulatePaper, preserveNumbers, simulateBlack}",
|
||||
always,
|
||||
proof_file::read
|
||||
),
|
||||
cmd!(
|
||||
query "view.proofSetup.list",
|
||||
"Saved Proof Setups",
|
||||
[],
|
||||
None,
|
||||
"{} the proof setup files in the Proof Setups folder next to the preferences, by name, at most 100 → {folder (null without the folder), setups: [{name, path}], truncated}",
|
||||
always,
|
||||
proof_file::list
|
||||
),
|
||||
cmd!(query "view.proofColors", "Proof Colors", ["View"], None, "{on?: bool (default: toggle)} → proof state", always, |s, p| {
|
||||
toggle_view(s, p, "view.proofColors", |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors))
|
||||
}),
|
||||
@@ -261,7 +299,7 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use_front_profiles(s);
|
||||
touch_all(s);
|
||||
} else if proof_targets(&info.name) {
|
||||
// A new file of the CMYK profile View → Proof Setup targets: redraw.
|
||||
// A new file of the profile View → Proof Setup targets: redraw.
|
||||
touch_all(s);
|
||||
} else {
|
||||
// Documents behind the front one draw through their own profiles: those assigned it redraw.
|
||||
@@ -292,7 +330,7 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if active.rgb == name || active.cmyk == name {
|
||||
use_front_profiles(s);
|
||||
}
|
||||
// The CMYK profile View → Proof Setup targets: redraw.
|
||||
// The profile View → Proof Setup targets: redraw.
|
||||
if proof_targets(&info.name) {
|
||||
touch_all(s);
|
||||
}
|
||||
@@ -311,9 +349,9 @@ fn touch_assigned(s: &mut Session, name: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether View → Proof Setup targets the CMYK profile `name`.
|
||||
/// Whether View → Proof Setup targets the CMYK or RGB profile `name`.
|
||||
fn proof_targets(name: &str) -> bool {
|
||||
matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name)
|
||||
matches!(proof::view().setup.target, ProofTarget::Cmyk(t) | ProofTarget::Rgb(t) if t == name)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -1003,7 +1041,7 @@ impl PasteProfile {
|
||||
if o.keys().any(|k| k != "rgb" && k != "cmyk") {
|
||||
return Err(refuse());
|
||||
}
|
||||
let model = |m: &str| o.get(m).map(&one).transpose();
|
||||
let model = |m: &str| o.get(m).map(one).transpose();
|
||||
Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? }))
|
||||
}
|
||||
Some(v) => {
|
||||
@@ -1392,6 +1430,8 @@ fn view_json(v: &proof::ProofView) -> Value {
|
||||
"target": v.setup.target.id(),
|
||||
"intent": v.setup.intent.id(),
|
||||
"simulatePaper": v.setup.simulate_paper,
|
||||
"preserveNumbers": v.setup.preserve_numbers,
|
||||
"simulateBlack": v.setup.simulate_black,
|
||||
"proofColors": v.proof_colors,
|
||||
"overprintPreview": v.overprint,
|
||||
"separations": v.separations,
|
||||
@@ -1401,19 +1441,7 @@ fn view_json(v: &proof::ProofView) -> Value {
|
||||
fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "view.proofSetup";
|
||||
let mut v = proof::view();
|
||||
if let Some(t) = text_param(p, "target", C)? {
|
||||
let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?;
|
||||
if let ProofTarget::Cmyk(name) = &t
|
||||
&& !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk)
|
||||
{
|
||||
return Err(bad(C, format!("unknown CMYK profile `{name}`")));
|
||||
}
|
||||
v.setup.target = t;
|
||||
}
|
||||
if let Some(i) = intent_param(p, C)? {
|
||||
v.setup.intent = i;
|
||||
}
|
||||
v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?;
|
||||
setup_params(p, &mut v.setup, C)?;
|
||||
if let Some(on) = on_param(p, "proof", C)? {
|
||||
v.proof_colors = on;
|
||||
}
|
||||
@@ -1421,6 +1449,33 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(view_json(&v))
|
||||
}
|
||||
|
||||
/// Take the proof setup settings `p` gives (`target`, `intent`, `simulatePaper`, `preserveNumbers`
|
||||
/// and `simulateBlack`, as `view.proofSetup` reads them) into `setup`. A `cmyk:` or `rgb:` target
|
||||
/// must name a CMYK or RGB profile that is loaded.
|
||||
fn setup_params(p: &Value, setup: &mut cms::ProofSetup, cmd: &str) -> Result<()> {
|
||||
if let Some(t) = text_param(p, "target", cmd)? {
|
||||
let t = ProofTarget::parse(t).ok_or_else(|| bad(cmd, format!("unknown proof target `{t}`")))?;
|
||||
if let ProofTarget::Cmyk(name) = &t
|
||||
&& !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk)
|
||||
{
|
||||
return Err(bad(cmd, format!("unknown CMYK profile `{name}`")));
|
||||
}
|
||||
if let ProofTarget::Rgb(name) = &t
|
||||
&& !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Rgb)
|
||||
{
|
||||
return Err(bad(cmd, format!("unknown RGB profile `{name}`")));
|
||||
}
|
||||
setup.target = t;
|
||||
}
|
||||
if let Some(i) = intent_param(p, cmd)? {
|
||||
setup.intent = i;
|
||||
}
|
||||
setup.simulate_paper = switch_or(p, "simulatePaper", setup.simulate_paper, cmd)?;
|
||||
setup.preserve_numbers = switch_or(p, "preserveNumbers", setup.preserve_numbers, cmd)?;
|
||||
setup.simulate_black = switch_or(p, "simulateBlack", setup.simulate_black, cmd)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make `v` the proof view and redraw every document. When `v` equals the current view, the view
|
||||
/// and the revisions stay as they are; Separations Preview's visible plates are compared as a set.
|
||||
fn store_view(s: &mut Session, v: proof::ProofView) {
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
//! View → Proof Setup → Customize…'s Save… and Load…: a custom proof setup (the device to simulate,
|
||||
//! Preserve Numbers, the rendering intent, Simulate Paper Color and Simulate Black Ink) in a file,
|
||||
//! and the setups saved in the `Proof Setups` folder next to the preferences, which View → Proof
|
||||
//! Setup lists ([`Session::attach_proof_setups`]). `view.proofSetup.read` reads a file without
|
||||
//! applying it, which is how Load… fills the dialog.
|
||||
//!
|
||||
//! The file format is VectorCraft's own: JSON with `format` [`FORMAT`], `version` 1, `target`,
|
||||
//! `intent`, `simulatePaper`, `preserveNumbers` and `simulateBlack`, as `view.proofSetup` names
|
||||
//! them, at most [`MAX_FILE`] bytes.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::cms::{self, Intent, ProofSetup, ProofTarget};
|
||||
use vectorcraft_render::proof;
|
||||
|
||||
use super::super::{EngineError, fileio};
|
||||
use super::{Result, Session, bad, setup_params, store_view, text_param, view_json};
|
||||
|
||||
/// The extension of a proof setup file.
|
||||
pub const EXT: &str = "vcproof";
|
||||
/// The `format` a proof setup file names.
|
||||
pub const FORMAT: &str = "vectorcraft-proof-setup";
|
||||
/// The format version this build writes and reads.
|
||||
const VERSION: u64 = 1;
|
||||
/// The largest proof setup file `view.proofSetup.load` reads, bytes (VectorCraft's own limit).
|
||||
pub const MAX_FILE: usize = 64 << 10;
|
||||
/// The most setups `view.proofSetup.list` lists.
|
||||
pub const MAX_LISTED: usize = 100;
|
||||
/// The most folder entries `view.proofSetup.list` looks at, setup files or not.
|
||||
const MAX_SCANNED: usize = 100_000;
|
||||
/// The longest `name`, in characters.
|
||||
const MAX_NAME: usize = 100;
|
||||
|
||||
impl Session {
|
||||
/// Keep the proof setups that `view.proofSetup.save` saves by name in the folder `dir` (`Proof
|
||||
/// Setups` next to the preferences), which `view.proofSetup.list` lists. The folder is made
|
||||
/// when a setup is first saved there.
|
||||
pub fn attach_proof_setups(&mut self, dir: std::path::PathBuf) {
|
||||
self.proof_setup_dir = Some(dir);
|
||||
}
|
||||
|
||||
/// The saved proof setups' folder ([`Session::attach_proof_setups`]); none on the web.
|
||||
pub fn proof_setup_dir(&self) -> Option<&std::path::Path> {
|
||||
self.proof_setup_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
}
|
||||
|
||||
/// How many proof setup files `view.proofSetup.save` wrote in this session; the menus list the
|
||||
/// Proof Setups folder again when it changes.
|
||||
pub fn proof_setup_saves(&self) -> u64 {
|
||||
self.proof_setup_saves
|
||||
}
|
||||
}
|
||||
|
||||
/// The file `p` names for `cmd`: its `path`, or the setup `name` in the Proof Setups folder.
|
||||
fn file_path(s: &Session, p: &Value, cmd: &str) -> Result<(String, bool)> {
|
||||
match (text_param(p, "path", cmd)?, text_param(p, "name", cmd)?) {
|
||||
(Some(path), None) if path.trim().is_empty() => Err(bad(cmd, "`path` is empty")),
|
||||
(Some(path), None) => Ok((path.to_string(), false)),
|
||||
(None, Some(name)) => {
|
||||
let name = setup_name(name, cmd)?;
|
||||
let dir = s.proof_setup_dir().ok_or_else(|| bad(cmd, "saved proof setups need the preferences folder, which this run doesn't have"))?;
|
||||
let path = dir.join(format!("{name}.{EXT}"));
|
||||
let path = path.to_str().ok_or_else(|| bad(cmd, format!("{}: the folder's path is not valid Unicode", dir.display())))?;
|
||||
Ok((path.to_string(), true))
|
||||
}
|
||||
(Some(_), Some(_)) => Err(bad(cmd, "give `path` or `name`, not both")),
|
||||
(None, None) => Err(bad(cmd, "missing `path` or `name`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` trimmed, when it can name a file in the Proof Setups folder: not empty, at most
|
||||
/// [`MAX_NAME`] characters, no path or control characters, and not starting with a dot.
|
||||
fn setup_name<'a>(name: &'a str, cmd: &str) -> Result<&'a str> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(bad(cmd, "`name` is empty"));
|
||||
}
|
||||
if name.chars().count() > MAX_NAME {
|
||||
return Err(bad(cmd, format!("`name` is longer than {MAX_NAME} characters")));
|
||||
}
|
||||
if name.starts_with('.') || name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) {
|
||||
return Err(bad(cmd, format!("`name` can't hold path characters: `{name}`")));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// `Ok` when `t` is a device a custom proof setup can simulate and its profile is loaded.
|
||||
fn check_device(t: &ProofTarget) -> std::result::Result<(), String> {
|
||||
let loaded = |name: &str, kind| cms::profile(name).is_some_and(|k| k.kind == kind);
|
||||
match t {
|
||||
ProofTarget::WorkingCmyk => Ok(()),
|
||||
ProofTarget::Cmyk(name) if loaded(name, cms::ProfileKind::Cmyk) => Ok(()),
|
||||
ProofTarget::Rgb(name) if loaded(name, cms::ProfileKind::Rgb) => Ok(()),
|
||||
ProofTarget::Cmyk(name) => Err(format!("the device to simulate is the CMYK profile `{name}`, which is not loaded")),
|
||||
ProofTarget::Rgb(name) => Err(format!("the device to simulate is the RGB profile `{name}`, which is not loaded")),
|
||||
t => Err(format!("`{}` is not a device to simulate: a custom proof setup simulates workingCmyk, cmyk:<profile> or rgb:<profile>", t.id())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings of `setup`, as `view.proofSetup` names them.
|
||||
fn setup_json(setup: &ProofSetup) -> serde_json::Map<String, Value> {
|
||||
let v = json!({
|
||||
"target": setup.target.id(),
|
||||
"intent": setup.intent.id(),
|
||||
"simulatePaper": setup.simulate_paper,
|
||||
"preserveNumbers": setup.preserve_numbers,
|
||||
"simulateBlack": setup.simulate_black,
|
||||
});
|
||||
match v {
|
||||
Value::Object(m) => m,
|
||||
_ => serde_json::Map::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The proof setup in a file's `bytes`, or why it can't be read.
|
||||
pub fn parse(bytes: &[u8]) -> std::result::Result<ProofSetup, String> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| format!("not a proof setup file: {e}"))?;
|
||||
if v.get("format").and_then(Value::as_str) != Some(FORMAT) {
|
||||
return Err("not a VectorCraft proof setup file".into());
|
||||
}
|
||||
match v.get("version").and_then(Value::as_u64) {
|
||||
Some(VERSION) => {}
|
||||
Some(n) if n > VERSION => return Err(format!("the file is version {n}, made by a newer VectorCraft")),
|
||||
_ => return Err("the file has no version VectorCraft reads".into()),
|
||||
}
|
||||
let text = |key: &str| v.get(key).and_then(Value::as_str);
|
||||
let target = text("target").ok_or("the file names no device to simulate")?;
|
||||
let target = ProofTarget::parse(target).ok_or_else(|| format!("unknown proof target `{target}`"))?;
|
||||
let intent = text("intent").ok_or("the file names no rendering intent")?;
|
||||
let intent = Intent::parse(intent).ok_or_else(|| format!("unknown intent `{intent}`"))?;
|
||||
let on = |key: &str| match v.get(key) {
|
||||
None | Some(Value::Null) => Ok(false),
|
||||
Some(Value::Bool(b)) => Ok(*b),
|
||||
Some(_) => Err(format!("`{key}` must be true or false")),
|
||||
};
|
||||
Ok(ProofSetup {
|
||||
target,
|
||||
intent,
|
||||
simulate_paper: on("simulatePaper")?,
|
||||
preserve_numbers: on("preserveNumbers")?,
|
||||
simulate_black: on("simulateBlack")?,
|
||||
separations: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A proof setup file holding `setup`.
|
||||
pub fn encode(setup: &ProofSetup) -> Vec<u8> {
|
||||
let mut m = serde_json::Map::new();
|
||||
m.insert("format".into(), json!(FORMAT));
|
||||
m.insert("version".into(), json!(VERSION));
|
||||
m.extend(setup_json(setup));
|
||||
let mut bytes = serde_json::to_vec_pretty(&Value::Object(m)).unwrap_or_default();
|
||||
bytes.push(b'\n');
|
||||
bytes
|
||||
}
|
||||
|
||||
pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "view.proofSetup.save";
|
||||
let (path, named) = file_path(s, p, C)?;
|
||||
let mut setup = proof::view().setup;
|
||||
setup_params(p, &mut setup, C)?;
|
||||
check_device(&setup.target).map_err(|e| bad(C, e))?;
|
||||
// A file `view.proofSetup.load` would refuse is not written (a device with a very long name).
|
||||
let bytes = encode(&setup);
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
if named
|
||||
&& let Some(dir) = std::path::Path::new(&path).parent()
|
||||
&& !dir.is_dir()
|
||||
{
|
||||
crate::file_access::check_write(&path).map_err(EngineError::Other)?;
|
||||
std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?;
|
||||
}
|
||||
fileio::write_file(&path, &bytes)?;
|
||||
s.proof_setup_saves += 1;
|
||||
let mut r = setup_json(&setup);
|
||||
r.insert("path".into(), json!(path));
|
||||
Ok(Value::Object(r))
|
||||
}
|
||||
|
||||
/// The file `p` names for `cmd` and the usable proof setup in it.
|
||||
fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> {
|
||||
let (path, _) = file_path(s, p, cmd)?;
|
||||
// One byte past the limit shows a file over it, which is not read further.
|
||||
let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?;
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
Ok((path, setup))
|
||||
}
|
||||
|
||||
pub(super) fn read(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (path, setup) = read_setup(s, p, "view.proofSetup.read")?;
|
||||
let mut r = setup_json(&setup);
|
||||
r.insert("path".into(), json!(path));
|
||||
Ok(Value::Object(r))
|
||||
}
|
||||
|
||||
pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (path, setup) = read_setup(s, p, "view.proofSetup.load")?;
|
||||
let mut v = proof::view();
|
||||
// Separations Preview's plates are not part of a proof setup file.
|
||||
v.setup = ProofSetup { separations: v.setup.separations.take(), ..setup };
|
||||
v.proof_colors = true;
|
||||
store_view(s, v.clone());
|
||||
let mut r = view_json(&v);
|
||||
r["path"] = json!(path);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub(super) fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let none = json!({"folder": null, "setups": [], "truncated": false});
|
||||
let Some(dir) = s.proof_setup_dir() else { return Ok(none) };
|
||||
listed(dir).map(|l| l.unwrap_or(none))
|
||||
}
|
||||
|
||||
/// The web keeps no saved setups ([`Session::proof_setup_dir`]).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn listed(_: &std::path::Path) -> Result<Option<Value>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The listing of the Proof Setups folder `dir`, as `view.proofSetup.list` gives it; `None` for a
|
||||
/// request that may not read it. The app calls it on another thread, without a session.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn listed(dir: &std::path::Path) -> Result<Option<Value>> {
|
||||
const C: &str = "view.proofSetup.list";
|
||||
let folder = dir.to_string_lossy().into_owned();
|
||||
// A request that may not read the folder learns nothing of it, nor where it is.
|
||||
if crate::file_access::check_read(&folder).is_err() {
|
||||
return Ok(None);
|
||||
}
|
||||
// The listed paths are text: a folder whose path is not valid Unicode can't be named in them.
|
||||
if dir.to_str().is_none() {
|
||||
return Err(bad(C, format!("{folder}: the folder's path is not valid Unicode")));
|
||||
}
|
||||
let entries = match std::fs::read_dir(dir) {
|
||||
Ok(entries) => entries,
|
||||
// No folder yet: nothing has been saved.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Some(json!({"folder": folder, "setups": [], "truncated": false}))),
|
||||
Err(e) => return Err(bad(C, format!("{folder}: {e}"))),
|
||||
};
|
||||
// The setups' names, the first MAX_LISTED by name; other entries are passed over before the
|
||||
// limit applies. A link is not followed. A file is listed only when it is named
|
||||
// `<name>.vcproof` and `name` takes that name unchanged, so each listed name loads its own
|
||||
// file. An entry that can't be read, or whose file name is not valid Unicode, leaves the
|
||||
// listing incomplete.
|
||||
let (mut names, mut truncated) = (Vec::<String>::new(), false);
|
||||
for (i, e) in entries.enumerate() {
|
||||
if i == MAX_SCANNED {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
let Ok(e) = e else {
|
||||
truncated = true;
|
||||
continue;
|
||||
};
|
||||
let Ok(file) = e.file_name().into_string() else {
|
||||
truncated = true;
|
||||
continue;
|
||||
};
|
||||
let Some(name) = file.strip_suffix(EXT).and_then(|s| s.strip_suffix('.')) else { continue };
|
||||
if setup_name(name, C).ok() != Some(name) {
|
||||
continue;
|
||||
}
|
||||
match e.file_type() {
|
||||
Ok(t) if t.is_file() => {}
|
||||
Ok(_) => continue,
|
||||
Err(_) => {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
names.push(name.to_string());
|
||||
if names.len() > 2 * MAX_LISTED {
|
||||
names.sort();
|
||||
names.truncate(MAX_LISTED);
|
||||
truncated = true;
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
truncated |= names.len() > MAX_LISTED;
|
||||
names.truncate(MAX_LISTED);
|
||||
let setups: Vec<Value> = names.iter().map(|name| json!({"name": name, "path": dir.join(format!("{name}.{EXT}")).to_string_lossy()})).collect();
|
||||
Ok(Some(json!({"folder": folder, "setups": setups, "truncated": truncated})))
|
||||
}
|
||||
@@ -105,6 +105,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
arc
|
||||
),
|
||||
cmd!(
|
||||
"shape.threePointArc",
|
||||
"Three-Point Arc",
|
||||
[],
|
||||
None,
|
||||
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
three_point_arc
|
||||
),
|
||||
cmd!(
|
||||
"shape.rectangularGrid",
|
||||
"Rectangular Grid",
|
||||
@@ -680,6 +689,50 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
|
||||
}
|
||||
|
||||
/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or
|
||||
/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is.
|
||||
fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.threePointArc";
|
||||
let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]")));
|
||||
let (start, end) = (point("start")?, point("end")?);
|
||||
let from_end = match p.get("at") {
|
||||
None => false,
|
||||
Some(Value::String(v)) if v == "start" || v == "end" => v == "end",
|
||||
Some(_) => return Err(bad(C, "`at` must be \"start\" or \"end\"")),
|
||||
};
|
||||
// The arc, and the point it passes through (an anchor of the path, so the path meets it exactly).
|
||||
let (arc, via) = match (p.get("through"), p.get("toward")) {
|
||||
(Some(_), None) if p.get("at").is_some() => return Err(bad(C, "give `at` only with `toward`")),
|
||||
(Some(_), None) => {
|
||||
let through = point("through")?;
|
||||
(shapes::CircularArc::through(start, end, through), Some(through))
|
||||
}
|
||||
(None, Some(_)) if from_end => {
|
||||
let toward = point("toward")?;
|
||||
(shapes::CircularArc::arriving(start, end, end - toward), None)
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
let toward = point("toward")?;
|
||||
(shapes::CircularArc::leaving(start, toward - start, end), None)
|
||||
}
|
||||
_ => return Err(bad(C, "give exactly one of `through` and `toward`")),
|
||||
};
|
||||
let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?;
|
||||
let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v));
|
||||
let look = s.new_art_look(
|
||||
vectorcraft_color::Paint::None,
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
s.paint.stroke_width.max(0.1),
|
||||
);
|
||||
// Not pixel-aligned: the ends stay on the given points.
|
||||
let mut out = insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, 0.0, false)?;
|
||||
out["cx"] = json!(arc.center.x);
|
||||
out["cy"] = json!(arc.center.y);
|
||||
out["radius"] = json!(arc.radius);
|
||||
out["sweep"] = json!(arc.sweep.to_degrees());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
|
||||
/// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group
|
||||
/// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle).
|
||||
|
||||
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Dimension",
|
||||
[],
|
||||
None,
|
||||
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
|
||||
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
|
||||
has_doc,
|
||||
create
|
||||
),
|
||||
@@ -565,7 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
|
||||
LineType::Solid => None,
|
||||
};
|
||||
if arrows {
|
||||
let head = o.arrow_style.arrowhead();
|
||||
let head = o.arrowhead();
|
||||
st.start_arrow = head.clone();
|
||||
st.end_arrow = head;
|
||||
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
|
||||
|
||||
@@ -24,20 +24,28 @@
|
||||
//! Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color, Lighter Color) is merged with the
|
||||
//! layers below it in its group. A Dissolve layer's partly transparent pixels are merged as opaque
|
||||
//! or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern
|
||||
//! that differs from layer to layer. When a merge's canvases would need more memory than allowed,
|
||||
//! the layer comes in alone: in the Normal mode, or unclipped.
|
||||
//! Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need a merge
|
||||
//! (one in a mode VectorCraft lacks, one that layers are clipped to, one clipped to another, or
|
||||
//! one below a merged layer) is always left out, with the layers clipped to it. Adjustment layers,
|
||||
//! fill layers that store no pixels and whose fill isn't read or whose shape is a vector mask,
|
||||
//! layer effects that are switched on, knockouts and vector masks aren't applied; the warnings
|
||||
//! count them and the hidden layers left out.
|
||||
//! that differs from layer to layer. A layer or group in a group whose Knockout setting is 1 (read
|
||||
//! as a shallow knockout) is merged with the layers below it in its group too, as the import option
|
||||
//! describes: where it has pixels, they are cleared to transparency and it is drawn there at its fill
|
||||
//! opacity, and its opacity fades that back toward them. In a pass-through group this is done only
|
||||
//! when it and the visible layers below it are in the Normal mode. When a merge's canvases would need more
|
||||
//! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its
|
||||
//! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need
|
||||
//! a merge (one in a mode VectorCraft lacks, one with a knockout in a group that changes the layers
|
||||
//! below it, one that layers are clipped to, one clipped to another, or one below a merged layer) is
|
||||
//! always left out, with the layers clipped to it. Adjustment layers, fill layers that store no
|
||||
//! pixels and whose fill isn't read or whose shape is a vector mask, layer effects that are switched
|
||||
//! on, vector masks, and the knockouts of top-level layers, of clipped layers, of layers that others
|
||||
//! are clipped to and of layers in a pass-through group with a layer in another mode, and other
|
||||
//! Knockout values, aren't applied; the warnings count them and the hidden layers left out.
|
||||
//!
|
||||
//! The file is untrusted: every count, length and size is checked before anything is allocated,
|
||||
//! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the
|
||||
//! group around them, with a warning), each layer's pixels, like the canvases one step of a
|
||||
//! merge holds together, must fit the memory allowed, and all the pixels decoded and the canvases
|
||||
//! the merges make must fit [`TOTAL_DECODED`] times that.
|
||||
//! the merges make must fit [`TOTAL_DECODED`] times that. A merge being tried may take that much
|
||||
//! past what was read before it. What the merges that aren't made, or that a hidden layer would
|
||||
//! need, decoded and made is counted apart, against the same limit.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::Arc;
|
||||
@@ -66,6 +74,13 @@ const MAX_CHANNELS: usize = 56;
|
||||
const MIN_RECORD: usize = 34;
|
||||
const DAMAGED: &str = "the PSD file's layer records are damaged";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The layer lists imports on this thread have walked, and the most a test lets them walk
|
||||
/// before the import stops with an error.
|
||||
pub(super) static WALKS: Cell<(usize, usize)> = const { Cell::new((0, usize::MAX)) };
|
||||
}
|
||||
|
||||
/// The keys of the tagged blocks that make a layer an adjustment layer.
|
||||
const ADJUSTMENTS: [&[u8; 4]; 18] = [
|
||||
b"levl", b"curv", b"brit", b"blnc", b"hue ", b"hue2", b"selc", b"mixr", b"grdm", b"phfl", b"expA", b"vibA", b"thrs", b"nvrt", b"post", b"clrL",
|
||||
@@ -227,7 +242,9 @@ struct Record<'a> {
|
||||
content: Content,
|
||||
effects: bool,
|
||||
vector_mask: bool,
|
||||
knockout: bool,
|
||||
/// The Knockout setting's byte (`knko`): 0 none, 1 a shallow knockout. Any other value isn't
|
||||
/// applied.
|
||||
knockout: u8,
|
||||
}
|
||||
|
||||
/// The layer records of `info` (the layer count, the records, then their channels' data).
|
||||
@@ -285,7 +302,7 @@ fn record<'a>(r: &mut Reader<'a>, psb: bool) -> Result<(Record<'a>, Vec<(i16, us
|
||||
content: Content::Pixels,
|
||||
effects: false,
|
||||
vector_mask: false,
|
||||
knockout: false,
|
||||
knockout: 0,
|
||||
};
|
||||
rec.read_extra(extra, psb)?;
|
||||
Ok((rec, lengths))
|
||||
@@ -345,8 +362,7 @@ impl Record<'_> {
|
||||
b"lfx2" | b"lmfx" => effects = Some(effects == Some(true) || effects_on(data)),
|
||||
b"lrFX" => old_effects = true,
|
||||
b"vmsk" | b"vsms" => self.vector_mask = true,
|
||||
// Shallow or deep knockout.
|
||||
b"knko" => self.knockout = data.first().is_some_and(|&k| k != 0),
|
||||
b"knko" => self.knockout = data.first().copied().unwrap_or(0),
|
||||
k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment,
|
||||
_ => {}
|
||||
}
|
||||
@@ -612,6 +628,8 @@ struct Unit<'i> {
|
||||
body: Body<'i>,
|
||||
/// While layers are clipped to it: how its merged canvas is shaped.
|
||||
clip: Option<Clip>,
|
||||
/// Layers are clipped to it, merged into it or not.
|
||||
base: bool,
|
||||
}
|
||||
|
||||
impl Unit<'_> {
|
||||
@@ -640,13 +658,36 @@ enum Clip {
|
||||
enum Body<'i> {
|
||||
/// A layer record's pixels.
|
||||
Layer(usize),
|
||||
/// A group's layers.
|
||||
Group(&'i [Item]),
|
||||
/// A group's record and its layers.
|
||||
Group(usize, &'i [Item]),
|
||||
/// Layers merged into one image.
|
||||
Merged(Canvas),
|
||||
}
|
||||
|
||||
/// Where a layer list is.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Level {
|
||||
/// The file's top level.
|
||||
Top,
|
||||
/// An isolated group, or a group drawn on its own.
|
||||
Group,
|
||||
/// A pass-through group whose layers blend with what is below it.
|
||||
Pass,
|
||||
}
|
||||
|
||||
/// What a knockout's merge with the layers below it gives.
|
||||
enum Knocked {
|
||||
/// The merged canvas.
|
||||
Merged(Canvas),
|
||||
/// Nothing below it draws, it draws nothing, it is at 0 fill and cuts no painted pixel below
|
||||
/// it, or what is below it and the merge are both transparent: it comes in as a layer of its own.
|
||||
Nothing,
|
||||
/// The canvases would need more memory than allowed.
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// A unit's body drawn alone.
|
||||
#[derive(Clone)]
|
||||
enum Drawn {
|
||||
/// It draws nothing.
|
||||
Nothing,
|
||||
@@ -663,6 +704,7 @@ struct Notes {
|
||||
fills: usize,
|
||||
effects: usize,
|
||||
vector_masks: usize,
|
||||
/// Layers whose knockout wasn't applied.
|
||||
knockouts: usize,
|
||||
/// Hidden layers left out, and layers clipped to them.
|
||||
hidden: usize,
|
||||
@@ -677,11 +719,17 @@ struct Notes {
|
||||
/// The counts a merge that can't be made gives back.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Counts {
|
||||
/// The bytes spent so far (see [`Builder::spent`]).
|
||||
spent: u64,
|
||||
skipped: usize,
|
||||
/// The knockouts counted as not applied.
|
||||
unknocked: usize,
|
||||
merged: usize,
|
||||
unmerged: usize,
|
||||
unclipped: usize,
|
||||
clipped_out: usize,
|
||||
/// The groups found to read no pixels.
|
||||
blank: usize,
|
||||
}
|
||||
|
||||
/// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place
|
||||
@@ -745,8 +793,17 @@ impl Notes {
|
||||
out
|
||||
}
|
||||
|
||||
fn counts(&self, skipped: usize) -> Counts {
|
||||
Counts { skipped, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out }
|
||||
fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize) -> Counts {
|
||||
Counts {
|
||||
spent,
|
||||
skipped,
|
||||
unknocked,
|
||||
merged: self.merged.len(),
|
||||
unmerged: self.unmerged,
|
||||
unclipped: self.unclipped,
|
||||
clipped_out: self.clipped_out,
|
||||
blank,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -767,12 +824,47 @@ struct Builder<'a, F> {
|
||||
notes: Notes,
|
||||
/// The records [`Notes`] counted.
|
||||
noted: Vec<bool>,
|
||||
/// Those records, in the order they were counted.
|
||||
noted_log: Vec<usize>,
|
||||
/// The records counted as hidden layers left out.
|
||||
skipped: Vec<bool>,
|
||||
/// Those records, in the order they were counted.
|
||||
skip_log: Vec<usize>,
|
||||
/// The records counted as knockouts not applied.
|
||||
unknocked: Vec<bool>,
|
||||
/// Those records, in the order they were counted.
|
||||
unknock_log: Vec<usize>,
|
||||
/// The records counted as layers clipped to a fill that isn't drawn.
|
||||
clipped_out: Vec<bool>,
|
||||
/// Those records, in the order they were counted.
|
||||
clipped_out_log: Vec<usize>,
|
||||
/// The records counted as clipped layers left unclipped.
|
||||
unclipped: Vec<bool>,
|
||||
/// Those records, in the order they were counted.
|
||||
unclip_log: Vec<usize>,
|
||||
/// The records that came in as layers of the document (hidden ones too, with `hidden`): not left
|
||||
/// out, though a drawing for a merge that wasn't made counted them.
|
||||
kept: Vec<bool>,
|
||||
/// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far.
|
||||
spent: Cell<u64>,
|
||||
/// Those bytes that merges not made, and merges a hidden layer would need, took: given back to
|
||||
/// `spent` and counted here instead, against the same limit.
|
||||
wasted: Cell<u64>,
|
||||
/// `spent` when the innermost merge being tried began: until it is made or given up, it may
|
||||
/// spend the whole allowance past that (see [`Self::spend`]).
|
||||
trial: Cell<u64>,
|
||||
/// The layers whose pixels were read so far (each time they were).
|
||||
painted: Cell<usize>,
|
||||
/// What each group gave when drawn alone without reading any layer's pixels (nothing, or a
|
||||
/// canvas without pixels, whatever the memory left): drawing it again gives that without
|
||||
/// walking its layers.
|
||||
blank: Vec<Option<Drawn>>,
|
||||
/// The pass-through groups that laid nothing onto nothing (see [`Self::laid_nothing`]).
|
||||
laid_blank: Vec<bool>,
|
||||
/// The groups of both, in the order they were found.
|
||||
blank_log: Vec<usize>,
|
||||
/// How many times a merge was counted as not made because it needed more memory than allowed.
|
||||
squeezed: usize,
|
||||
}
|
||||
|
||||
impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
@@ -786,10 +878,38 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
}
|
||||
|
||||
/// Count `bytes` of decoded pixels, or of a canvas a merge makes, against the whole import's
|
||||
/// allowance, [`TOTAL_DECODED`] times the memory allowed for one image.
|
||||
/// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. While a merge is tried
|
||||
/// (see [`Self::try_from_here`]), only what it spent counts against the allowance.
|
||||
fn spend(&self, bytes: u64) -> Result<(), String> {
|
||||
let total = self.spent.get().saturating_add(bytes);
|
||||
self.spent.set(total);
|
||||
if total.saturating_sub(self.trial.get()) > self.max_alloc.saturating_mul(TOTAL_DECODED) {
|
||||
return Err("the PSD file's layers take more memory to read than allowed".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start trying a merge that may not be made: what it spends counts against the whole
|
||||
/// allowance, however much was spent before it. Gives what [`Self::tried`] takes back.
|
||||
fn try_from_here(&self) -> u64 {
|
||||
self.trial.replace(self.spent.get())
|
||||
}
|
||||
|
||||
/// End the merge tried since [`Self::try_from_here`] gave `outer`. A merge that is `made` keeps
|
||||
/// what it spent, which must then fit the allowance with what was spent before it.
|
||||
fn tried(&self, outer: u64, made: bool) -> Result<(), String> {
|
||||
self.trial.set(outer);
|
||||
if made { self.spend(0) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Move the bytes spent since `spent` was the count to [`Self::wasted`], which has an allowance
|
||||
/// of its own as large: what a merge that isn't made decoded doesn't take the room for reading
|
||||
/// the layers apart.
|
||||
fn refund(&self, spent: u64) -> Result<(), String> {
|
||||
let since = self.spent.get().saturating_sub(spent);
|
||||
self.spent.set(self.spent.get().min(spent));
|
||||
let total = self.wasted.get().saturating_add(since);
|
||||
self.wasted.set(total);
|
||||
if total > self.max_alloc.saturating_mul(TOTAL_DECODED) {
|
||||
return Err("the PSD file's layers take more memory to read than allowed".into());
|
||||
}
|
||||
@@ -814,6 +934,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
Paint::Cmyk(ink) => (self.cmyk)(ink),
|
||||
};
|
||||
let px = image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), 255]);
|
||||
self.painted.set(self.painted.get() + 1);
|
||||
return Ok(Some((0, 0, RgbaImage::from_pixel(h.width, h.height, px))));
|
||||
}
|
||||
Content::Pixels | Content::Type | Content::Solid(_) | Content::Fill => rec.bounds.size(),
|
||||
@@ -845,6 +966,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
let rgb = to_rgb(h, |c| planes.get(c).map_or(0.0, |p| at(p, linear, 0.0)), &self.cmyk);
|
||||
image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(at(&alpha, false, 1.0))])
|
||||
});
|
||||
self.painted.set(self.painted.get() + 1);
|
||||
Ok(Some((i64::from(rec.bounds.left), i64::from(rec.bounds.top), img)))
|
||||
}
|
||||
|
||||
@@ -897,7 +1019,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
for item in items {
|
||||
let (i, body) = match item {
|
||||
Item::Layer(i) => (*i, Body::Layer(*i)),
|
||||
Item::Group(i, children) => (*i, Body::Group(children)),
|
||||
Item::Group(i, children) => (*i, Body::Group(*i, children)),
|
||||
};
|
||||
let rec = self.record(i)?;
|
||||
let (name, hidden, clipped, blend) = (rec.name.clone(), rec.hidden, rec.clipped, rec.blend);
|
||||
@@ -920,14 +1042,26 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
Some(b) => {
|
||||
// Counted even when it draws nothing (an adjustment layer).
|
||||
self.note(i)?;
|
||||
if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? {
|
||||
// A clipped layer's knockout isn't applied.
|
||||
if self.record(i)?.knockout != 0 {
|
||||
self.unknock(i);
|
||||
}
|
||||
if let Some(u) = out.get_mut(b) {
|
||||
u.base = true;
|
||||
}
|
||||
let spent = self.spent.get();
|
||||
let outer = self.try_from_here();
|
||||
let made = !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)?;
|
||||
self.tried(outer, made)?;
|
||||
if made {
|
||||
continue;
|
||||
}
|
||||
self.refund(spent)?;
|
||||
// The merge doesn't fit: this layer and the next ones clipped to the same
|
||||
// base come in as layers of their own.
|
||||
unclipped = true;
|
||||
self.notes.unclipped += 1;
|
||||
out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None });
|
||||
self.unclip(i);
|
||||
out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false });
|
||||
}
|
||||
}
|
||||
continue;
|
||||
@@ -939,7 +1073,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
continue;
|
||||
}
|
||||
self.note(i)?;
|
||||
out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None });
|
||||
out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false });
|
||||
base = Some(Some(out.len() - 1));
|
||||
}
|
||||
for u in &mut out {
|
||||
@@ -962,7 +1096,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
};
|
||||
// A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either.
|
||||
if undrawn && u.clip.is_none() {
|
||||
self.notes.clipped_out += 1;
|
||||
self.clip_out(i);
|
||||
return Ok(true);
|
||||
}
|
||||
let layer = match self.draw_body(body, Some(i))? {
|
||||
@@ -1045,12 +1179,15 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
// Once, though a merge may draw it again.
|
||||
match self.noted.get_mut(i) {
|
||||
Some(true) => return Ok(()),
|
||||
Some(n) => *n = true,
|
||||
Some(n) => {
|
||||
*n = true;
|
||||
self.noted_log.push(i);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let (content, empty, effects, vector_mask, knockout) = {
|
||||
let (content, empty, effects, vector_mask) = {
|
||||
let rec = self.record(i)?;
|
||||
(rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask, rec.knockout)
|
||||
(rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask)
|
||||
};
|
||||
match content {
|
||||
Content::Type => self.notes.types += 1,
|
||||
@@ -1062,10 +1199,59 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
}
|
||||
self.notes.effects += usize::from(effects);
|
||||
self.notes.vector_masks += usize::from(vector_mask);
|
||||
self.notes.knockouts += usize::from(knockout);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What [`Self::note`] has counted so far: the length of its log, and the counts.
|
||||
fn noted_so_far(&self) -> (usize, [usize; 5]) {
|
||||
let n = &self.notes;
|
||||
(self.noted_log.len(), [n.types, n.adjustments, n.fills, n.effects, n.vector_masks])
|
||||
}
|
||||
|
||||
/// Forget what [`Self::note`] counted since `so_far`, for layers that are left out.
|
||||
fn unnote(&mut self, (logged, counts): (usize, [usize; 5])) {
|
||||
for i in self.noted_log.split_off(logged) {
|
||||
if let Some(n) = self.noted.get_mut(i) {
|
||||
*n = false;
|
||||
}
|
||||
}
|
||||
let n = &mut self.notes;
|
||||
[n.types, n.adjustments, n.fills, n.effects, n.vector_masks] = counts;
|
||||
}
|
||||
|
||||
/// Count record `i` as a layer whose knockout isn't applied (once).
|
||||
fn unknock(&mut self, i: usize) {
|
||||
if let Some(s) = self.unknocked.get_mut(i)
|
||||
&& !*s
|
||||
{
|
||||
*s = true;
|
||||
self.notes.knockouts += 1;
|
||||
self.unknock_log.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// Does unit `u`, at `level` above the units `below` it, take a shallow knockout this import
|
||||
/// applies? Only a layer or group in a group, neither clipped nor a base of clipped layers, does;
|
||||
/// in a pass-through group, only when it and the visible units below it are in the Normal mode, so
|
||||
/// that none of them blends with what is below the group. Any other knockout is counted as not
|
||||
/// applied. One at 0 opacity, or with no visible unit below it, changes nothing below it: it needs
|
||||
/// no merge, and a hidden one isn't left out for it.
|
||||
fn knocks(&mut self, u: &Unit<'_>, below: &[Unit<'_>], level: Level) -> Result<bool, String> {
|
||||
let rec = self.record(u.record)?;
|
||||
if rec.knockout == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
let normal = |u: &Unit<'_>| u.blend == Blend::Mode(BlendMode::Normal);
|
||||
let blends_out = level == Level::Pass && !(normal(u) && below.iter().filter(|b| b.visible).all(normal));
|
||||
let applies = rec.knockout == 1 && level != Level::Top && !blends_out && !rec.clipped && !u.base && !matches!(u.body, Body::Merged(_));
|
||||
// Its fill opacity isn't checked: at 0 fill it still clears what is below it.
|
||||
let changes = rec.opacity > 0.0 && below.iter().any(|b| b.visible);
|
||||
if !applies {
|
||||
self.unknock(u.record);
|
||||
}
|
||||
Ok(applies && changes)
|
||||
}
|
||||
|
||||
/// Count record `i` as a hidden layer left out (once).
|
||||
fn skip(&mut self, i: usize) {
|
||||
if let Some(s) = self.skipped.get_mut(i)
|
||||
@@ -1077,21 +1263,100 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `items`' units with the layers in blend modes VectorCraft lacks merged with those below.
|
||||
fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result<Vec<Unit<'i>>, String> {
|
||||
/// Count record `i` as a layer clipped to a fill that isn't drawn (once).
|
||||
fn clip_out(&mut self, i: usize) {
|
||||
if let Some(s) = self.clipped_out.get_mut(i)
|
||||
&& !*s
|
||||
{
|
||||
*s = true;
|
||||
self.notes.clipped_out += 1;
|
||||
self.clipped_out_log.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// Count record `i` as a clipped layer left unclipped (once).
|
||||
fn unclip(&mut self, i: usize) {
|
||||
self.squeezed += 1;
|
||||
if let Some(s) = self.unclipped.get_mut(i)
|
||||
&& !*s
|
||||
{
|
||||
*s = true;
|
||||
self.notes.unclipped += 1;
|
||||
self.unclip_log.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group
|
||||
/// the layers with a shallow knockout, merged with those below.
|
||||
fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result<Vec<Unit<'i>>, String> {
|
||||
#[cfg(test)]
|
||||
{
|
||||
let (walked, most) = WALKS.get();
|
||||
if walked >= most {
|
||||
return Err("the import walked more layer lists than the test allows".into());
|
||||
}
|
||||
WALKS.set((walked + 1, most));
|
||||
}
|
||||
let mut out: Vec<Unit<'i>> = vec![];
|
||||
for mut u in self.units(items, keep_hidden)? {
|
||||
// A hidden layer in a mode VectorCraft lacks would need the merge for its mode: it is left
|
||||
// out without being drawn.
|
||||
if !u.visible && matches!(u.blend, Blend::Other(_)) {
|
||||
self.skip(u.record);
|
||||
continue;
|
||||
}
|
||||
if self.knocks(&u, &out, level)? {
|
||||
let saved = self.saved();
|
||||
let noted = self.noted_so_far();
|
||||
let squeezed = self.squeezed;
|
||||
let outer = self.try_from_here();
|
||||
let knocked = self.knock(&out, &u)?;
|
||||
self.tried(outer, u.visible && matches!(knocked, Knocked::Merged(_)))?;
|
||||
match knocked {
|
||||
// A hidden layer that would need the merge is left out, and nothing its drawing
|
||||
// counted is counted.
|
||||
Knocked::Merged(_) | Knocked::TooLarge if !u.visible => {
|
||||
self.restore(saved)?;
|
||||
self.unnote(noted);
|
||||
self.skip(u.record);
|
||||
continue;
|
||||
}
|
||||
Knocked::Merged(canvas) => {
|
||||
self.take_merge(&mut out, &u, canvas);
|
||||
if let Blend::Other(other) = u.blend
|
||||
&& !self.notes.merged.contains(&other.label())
|
||||
{
|
||||
self.notes.merged.push(other.label());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Nothing below it, or nothing of its own, to knock out: it comes in as a layer,
|
||||
// with the hidden layers its drawing left out (see `kept`). What its drawing
|
||||
// read is read again when it comes in. A hidden one may still be left out by a
|
||||
// later merge: what its drawing counted is counted when it comes in instead.
|
||||
Knocked::Nothing if !u.visible => {
|
||||
self.restore(saved)?;
|
||||
self.unnote(noted);
|
||||
}
|
||||
// A merge below it that its held canvas left without the memory it needed may
|
||||
// be made when they come in without it: what drawing them counted is given back
|
||||
// and counted again then.
|
||||
Knocked::Nothing if self.squeezed != squeezed => self.restore(saved)?,
|
||||
Knocked::Nothing => self.refund(saved.spent)?,
|
||||
Knocked::TooLarge => {
|
||||
self.restore(saved)?;
|
||||
self.squeezed += 1;
|
||||
self.unknock(u.record);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Blend::Other(other) = u.blend else {
|
||||
out.push(u);
|
||||
continue;
|
||||
};
|
||||
// A hidden layer that would need the merge is left out.
|
||||
if !u.visible {
|
||||
self.skip(u.record);
|
||||
continue;
|
||||
}
|
||||
// A merge that can't be made counts nothing its groups would have counted.
|
||||
let saved = self.notes.counts(self.skip_log.len());
|
||||
let saved = self.saved();
|
||||
let outer = self.try_from_here();
|
||||
let made = match out.as_mut_slice() {
|
||||
// Onto the previous merge alone: composited onto its canvas, in place.
|
||||
[prev] if prev.is_merge() => {
|
||||
@@ -1113,45 +1378,20 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
}
|
||||
_ => match self.merge(&out, &u)? {
|
||||
Some(canvas) => {
|
||||
let mut name = String::new();
|
||||
for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() {
|
||||
if k == 0 {
|
||||
name = std::mem::take(&mut b.name);
|
||||
} else {
|
||||
name.push_str(" + ");
|
||||
name.push_str(&b.name);
|
||||
}
|
||||
}
|
||||
if out.iter().any(|b| b.visible) {
|
||||
name.push_str(" + ");
|
||||
}
|
||||
name.push_str(&u.name);
|
||||
// Hidden layers below are left out with the rest.
|
||||
for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::<Vec<_>>() {
|
||||
self.skip(b);
|
||||
}
|
||||
out.clear();
|
||||
out.push(Unit {
|
||||
name,
|
||||
visible: true,
|
||||
opacity: 1.0,
|
||||
blend: Blend::Mode(BlendMode::Normal),
|
||||
mask_of: None,
|
||||
record: u.record,
|
||||
body: Body::Merged(canvas),
|
||||
clip: None,
|
||||
});
|
||||
self.take_merge(&mut out, &u, canvas);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
};
|
||||
self.tried(outer, made)?;
|
||||
if made {
|
||||
if !self.notes.merged.contains(&other.label()) {
|
||||
self.notes.merged.push(other.label());
|
||||
}
|
||||
} else {
|
||||
self.restore(saved);
|
||||
self.restore(saved)?;
|
||||
self.squeezed += 1;
|
||||
self.notes.unmerged += 1;
|
||||
u.blend = Blend::Mode(BlendMode::Normal);
|
||||
out.push(u);
|
||||
@@ -1160,18 +1400,51 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The counts as they were before a merge that couldn't be made.
|
||||
fn restore(&mut self, c: Counts) {
|
||||
/// The counts as they are, for [`Self::restore`].
|
||||
fn saved(&self) -> Counts {
|
||||
self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len())
|
||||
}
|
||||
|
||||
/// The counts as they were before a merge that couldn't be made, the bytes it spent counted as
|
||||
/// wasted (see [`Self::refund`]).
|
||||
fn restore(&mut self, c: Counts) -> Result<(), String> {
|
||||
self.refund(c.spent)?;
|
||||
for i in self.skip_log.split_off(c.skipped) {
|
||||
if let Some(s) = self.skipped.get_mut(i) {
|
||||
*s = false;
|
||||
self.notes.hidden = self.notes.hidden.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
for i in self.unknock_log.split_off(c.unknocked) {
|
||||
if let Some(s) = self.unknocked.get_mut(i) {
|
||||
*s = false;
|
||||
self.notes.knockouts = self.notes.knockouts.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
// The groups found since: what their drawing counted is given back, so they are drawn again.
|
||||
for g in self.blank_log.split_off(c.blank) {
|
||||
if let Some(b) = self.blank.get_mut(g) {
|
||||
*b = None;
|
||||
}
|
||||
if let Some(b) = self.laid_blank.get_mut(g) {
|
||||
*b = false;
|
||||
}
|
||||
}
|
||||
for i in self.unclip_log.split_off(c.unclipped) {
|
||||
if let Some(s) = self.unclipped.get_mut(i) {
|
||||
*s = false;
|
||||
self.notes.unclipped = self.notes.unclipped.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
for i in self.clipped_out_log.split_off(c.clipped_out) {
|
||||
if let Some(s) = self.clipped_out.get_mut(i) {
|
||||
*s = false;
|
||||
self.notes.clipped_out = self.notes.clipped_out.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
self.notes.merged.truncate(c.merged);
|
||||
self.notes.unmerged = c.unmerged;
|
||||
self.notes.unclipped = c.unclipped;
|
||||
self.notes.clipped_out = c.clipped_out;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The visible units `below` with `top` composited over them; `None` when the canvas would need
|
||||
@@ -1186,24 +1459,169 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
Ok(Some(acc.unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// `out` replaced by one layer: `canvas`, the merge of its visible units with `top`, named after
|
||||
/// them, bottom first. Its hidden units are left out.
|
||||
fn take_merge<'i>(&mut self, out: &mut Vec<Unit<'i>>, top: &Unit<'_>, canvas: Canvas) {
|
||||
let mut name = String::new();
|
||||
for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() {
|
||||
if k == 0 {
|
||||
name = std::mem::take(&mut b.name);
|
||||
} else {
|
||||
name.push_str(" + ");
|
||||
name.push_str(&b.name);
|
||||
}
|
||||
}
|
||||
if out.iter().any(|b| b.visible) {
|
||||
name.push_str(" + ");
|
||||
}
|
||||
name.push_str(&top.name);
|
||||
// Hidden layers below are left out with the rest.
|
||||
for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::<Vec<_>>() {
|
||||
self.skip(b);
|
||||
}
|
||||
out.clear();
|
||||
out.push(Unit {
|
||||
name,
|
||||
visible: true,
|
||||
opacity: 1.0,
|
||||
blend: Blend::Mode(BlendMode::Normal),
|
||||
mask_of: None,
|
||||
record: top.record,
|
||||
body: Body::Merged(canvas),
|
||||
clip: None,
|
||||
base: false,
|
||||
});
|
||||
}
|
||||
|
||||
/// The visible units `below` with `top`, a layer with a shallow knockout, knocking them out: where
|
||||
/// `top` has pixels, what is below it in its group is cleared to transparency (the group's own
|
||||
/// backdrop) and `top` is drawn there at its fill opacity; its opacity then fades all of that
|
||||
/// back toward the units below as they were. Its layer mask shapes the cut.
|
||||
fn knock(&mut self, below: &[Unit<'_>], top: &Unit<'_>) -> Result<Knocked, String> {
|
||||
let (fill, opacity) = {
|
||||
let rec = self.record(top.record)?;
|
||||
(rec.fill, rec.opacity)
|
||||
};
|
||||
let k = match self.draw_body(&top.body, top.mask_of)? {
|
||||
Drawn::Nothing => return Ok(Knocked::Nothing),
|
||||
Drawn::TooLarge => return Ok(Knocked::TooLarge),
|
||||
Drawn::Canvas(c) if c.px.iter().all(|p| p[3] <= 0.0) => return Ok(Knocked::Nothing),
|
||||
Drawn::Canvas(c) => c,
|
||||
};
|
||||
// At 0 fill, beside every layer below it, it cuts nothing: no canvas for them is needed.
|
||||
if fill <= 0.0 && self.beside(below, &k)? {
|
||||
return Ok(Knocked::Nothing);
|
||||
}
|
||||
// The layer's canvas is held while the units below are drawn.
|
||||
let bytes = 16 * k.px.len() as u64;
|
||||
self.held = self.held.saturating_add(bytes);
|
||||
let mut acc: Option<Canvas> = None;
|
||||
let mut drawn = Ok(true);
|
||||
for u in below.iter().filter(|u| u.visible) {
|
||||
drawn = self.composite(&mut acc, u);
|
||||
if !matches!(drawn, Ok(true)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.held = self.held.saturating_sub(bytes);
|
||||
if !drawn? {
|
||||
return Ok(Knocked::TooLarge);
|
||||
}
|
||||
// Nothing below draws.
|
||||
let Some(below) = acc.as_ref() else { return Ok(Knocked::Nothing) };
|
||||
// At 0 fill it draws nothing of its own: where it cuts no painted pixel below, no canvas for
|
||||
// the merge is needed.
|
||||
if fill <= 0.0 && !cuts_paint(below, &k, top.blend, opacity, top.record) {
|
||||
return Ok(Knocked::Nothing);
|
||||
}
|
||||
let clear = |c: &Canvas| c.px.iter().all(|p| p[3] <= 0.0);
|
||||
let below_clear = clear(below);
|
||||
if !knock_onto(&mut acc, &k, top.blend, fill, opacity, top.record, self.room(), &|n| self.spend(n))? {
|
||||
return Ok(Knocked::TooLarge);
|
||||
}
|
||||
// Nothing below to cut, and nothing of its own drawn at its fill opacity.
|
||||
if below_clear && acc.as_ref().is_none_or(clear) {
|
||||
return Ok(Knocked::Nothing);
|
||||
}
|
||||
Ok(acc.map_or(Knocked::Nothing, Knocked::Merged))
|
||||
}
|
||||
|
||||
/// Do the pixels `knock` paints lie outside the bounds of every visible unit `below`? Only the
|
||||
/// bounds of layers and of merged canvases are known without drawing them: with a group below,
|
||||
/// `false`.
|
||||
fn beside(&self, below: &[Unit<'_>], knock: &Canvas) -> Result<bool, String> {
|
||||
let width = knock.width.max(1);
|
||||
let mut painted: Option<[i64; 4]> = None;
|
||||
for (k, _) in knock.px.iter().enumerate().filter(|(_, p)| p[3] > 0.0) {
|
||||
let (x, y) = (knock.left + (k % width) as i64, knock.top + (k / width) as i64);
|
||||
painted = Some(painted.map_or([x, y, x + 1, y + 1], |[l, t, r, b]| [l.min(x), t.min(y), r.max(x + 1), b.max(y + 1)]));
|
||||
}
|
||||
let Some([left, top, right, bottom]) = painted else { return Ok(true) };
|
||||
for u in below.iter().filter(|u| u.visible) {
|
||||
let [l, t, r, b] = match &u.body {
|
||||
Body::Merged(c) => [c.left, c.top, c.left + c.width as i64, c.top + c.height as i64],
|
||||
Body::Layer(i) => {
|
||||
let rec = self.record(*i)?;
|
||||
match rec.content {
|
||||
Content::Adjustment => continue,
|
||||
Content::Solid(Some(_)) if rec.color_over_canvas() => [0, 0, i64::from(self.h.width), i64::from(self.h.height)],
|
||||
_ => {
|
||||
let (w, h) = rec.bounds.size();
|
||||
let (l, t) = (i64::from(rec.bounds.left), i64::from(rec.bounds.top));
|
||||
[l, t, l + w as i64, t + h as i64]
|
||||
}
|
||||
}
|
||||
}
|
||||
Body::Group(..) => return Ok(false),
|
||||
};
|
||||
if l < right && left < r && t < bottom && top < b {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The bytes a merge step may still take: the memory allowed, less the copies of what is below
|
||||
/// the pass-through groups being merged.
|
||||
fn room(&self) -> u64 {
|
||||
self.max_alloc.saturating_sub(self.held)
|
||||
}
|
||||
|
||||
/// Note pass-through group `g` as laying nothing onto nothing when `acc`, nothing before, still
|
||||
/// is and no layer's pixels were read since `painted`: laying its layers onto nothing again
|
||||
/// gives nothing, with the same notes.
|
||||
fn laid_nothing(&mut self, g: usize, acc: &Option<Canvas>, painted: usize) {
|
||||
if acc.is_none()
|
||||
&& self.painted.get() == painted
|
||||
&& let Some(b) = self.laid_blank.get_mut(g)
|
||||
&& !*b
|
||||
{
|
||||
*b = true;
|
||||
self.blank_log.push(g);
|
||||
}
|
||||
}
|
||||
|
||||
/// Unit `u` composited onto `acc`. A pass-through group lays its layers onto `acc` one by one,
|
||||
/// so that they blend with what is below it; at less than full opacity or with a layer mask, the
|
||||
/// result is then faded back toward `acc` as it was by the opacity and the mask. Anything else
|
||||
/// is drawn alone first. `false` when the canvas would need more memory than allowed.
|
||||
fn composite(&mut self, acc: &mut Option<Canvas>, u: &Unit<'_>) -> Result<bool, String> {
|
||||
if let (Body::Group(items), Blend::Pass) = (&u.body, u.blend) {
|
||||
if let (Body::Group(g, items), Blend::Pass) = (&u.body, u.blend) {
|
||||
let mask = match u.mask_of {
|
||||
Some(i) if self.has_mask(Some(i))? => self.mask(i, false)?,
|
||||
_ => None,
|
||||
};
|
||||
// Onto nothing, a group that laid nothing onto nothing before lays nothing again.
|
||||
let (fresh, painted) = (acc.is_none(), self.painted.get());
|
||||
if fresh && self.laid_blank.get(*g) == Some(&true) {
|
||||
return Ok(true);
|
||||
}
|
||||
if u.opacity >= 1.0 && mask.is_none() {
|
||||
return self.lay(acc, items);
|
||||
let laid = self.lay(acc, items, Level::Pass)?;
|
||||
if laid && fresh {
|
||||
self.laid_nothing(*g, acc, painted);
|
||||
}
|
||||
return Ok(laid);
|
||||
}
|
||||
let bytes = acc.as_ref().map_or(0, |c| 16 * c.px.len() as u64);
|
||||
if bytes > self.room() {
|
||||
@@ -1212,11 +1630,14 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
self.spend(bytes)?;
|
||||
let below = acc.clone();
|
||||
self.held = self.held.saturating_add(bytes);
|
||||
let laid = self.lay(acc, items);
|
||||
let laid = self.lay(acc, items, Level::Pass);
|
||||
self.held = self.held.saturating_sub(bytes);
|
||||
if !laid? {
|
||||
return Ok(false);
|
||||
}
|
||||
if fresh {
|
||||
self.laid_nothing(*g, acc, painted);
|
||||
}
|
||||
if let Some(after) = acc.as_mut() {
|
||||
fade(after, below.as_ref(), u.opacity, mask.as_ref());
|
||||
}
|
||||
@@ -1230,10 +1651,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
blend_onto(acc, &c, u.blend, u.opacity, u.record, self.room(), &|n| self.spend(n))
|
||||
}
|
||||
|
||||
/// `items`' layers composited onto `acc` one by one; `false` when a canvas would need more
|
||||
/// memory than allowed.
|
||||
fn lay(&mut self, acc: &mut Option<Canvas>, items: &[Item]) -> Result<bool, String> {
|
||||
for c in self.merged(items, false)? {
|
||||
/// `items`' layers, the layers of a group at `level`, composited onto `acc` one by one; `false`
|
||||
/// when a canvas would need more memory than allowed.
|
||||
fn lay(&mut self, acc: &mut Option<Canvas>, items: &[Item], level: Level) -> Result<bool, String> {
|
||||
for c in self.merged(items, false, level)? {
|
||||
if !self.composite(acc, &c)? {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -1271,13 +1692,29 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
}
|
||||
None => return Ok(Drawn::Nothing),
|
||||
},
|
||||
Body::Group(items) => {
|
||||
let mut acc: Option<Canvas> = None;
|
||||
if !self.lay(&mut acc, items)? {
|
||||
return Ok(Drawn::TooLarge);
|
||||
Body::Group(g, items) => {
|
||||
let drawn = match self.blank.get(*g).cloned().flatten() {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
let painted = self.painted.get();
|
||||
let mut acc: Option<Canvas> = None;
|
||||
if !self.lay(&mut acc, items, Level::Group)? {
|
||||
return Ok(Drawn::TooLarge);
|
||||
}
|
||||
let d = acc.map_or(Drawn::Nothing, Drawn::Canvas);
|
||||
if self.painted.get() == painted
|
||||
&& let Some(b) = self.blank.get_mut(*g)
|
||||
{
|
||||
*b = Some(d.clone());
|
||||
self.blank_log.push(*g);
|
||||
}
|
||||
d
|
||||
}
|
||||
};
|
||||
match drawn {
|
||||
Drawn::Canvas(c) => c,
|
||||
other => return Ok(other),
|
||||
}
|
||||
let Some(acc) = acc else { return Ok(Drawn::Nothing) };
|
||||
acc
|
||||
}
|
||||
};
|
||||
if let Some(i) = mask_of {
|
||||
@@ -1306,10 +1743,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Layers of the document for `items`, bottom first.
|
||||
fn list(&mut self, items: &[Item]) -> Result<Vec<Arc<Node>>, String> {
|
||||
/// Layers of the document for `items`, the layers at `level`, bottom first.
|
||||
fn list(&mut self, items: &[Item], level: Level) -> Result<Vec<Arc<Node>>, String> {
|
||||
let mut out = vec![];
|
||||
for u in self.merged(items, self.hidden)? {
|
||||
for u in self.merged(items, self.hidden, level)? {
|
||||
if let Some(n) = self.node(u)? {
|
||||
out.push(Arc::new(n));
|
||||
}
|
||||
@@ -1320,6 +1757,9 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
/// The layer of the document unit `u` becomes; `None` for a layer that draws nothing (an
|
||||
/// adjustment layer, or one without pixels).
|
||||
fn node(&mut self, u: Unit<'_>) -> Result<Option<Node>, String> {
|
||||
if let Some(k) = self.kept.get_mut(u.record) {
|
||||
*k = true;
|
||||
}
|
||||
let children = match &u.body {
|
||||
Body::Layer(i) => match self.image(*i)? {
|
||||
Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)],
|
||||
@@ -1329,13 +1769,13 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
|
||||
Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)],
|
||||
None => return Ok(None),
|
||||
},
|
||||
Body::Group(items) => self.list(items)?,
|
||||
Body::Group(_, items) => self.list(items, if u.blend == Blend::Pass { Level::Pass } else { Level::Group })?,
|
||||
};
|
||||
let mut layer = self.layer(&u.name);
|
||||
layer.visible = u.visible;
|
||||
layer.opacity = u.opacity.clamp(0.0, 1.0);
|
||||
(layer.blend, layer.isolate) = match u.blend {
|
||||
Blend::Mode(m) => (m, matches!(u.body, Body::Group(_))),
|
||||
Blend::Mode(m) => (m, matches!(u.body, Body::Group(..))),
|
||||
Blend::Pass | Blend::Other(_) => (BlendMode::Normal, false),
|
||||
};
|
||||
if let Some(c) = layer.children_mut() {
|
||||
@@ -1443,6 +1883,71 @@ fn blend_onto(
|
||||
max_alloc: u64,
|
||||
spend: &dyn Fn(u64) -> Result<(), String>,
|
||||
) -> Result<bool, String> {
|
||||
if !cover(acc, src, max_alloc, spend)? {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(out) = acc.as_mut() else { return Ok(false) };
|
||||
// Only the source's rows and columns change.
|
||||
let (sw, x0, y0) = (src.width.max(1), (src.left - out.left) as usize, (src.top - out.top) as usize);
|
||||
for (k, s) in src.px.iter().enumerate() {
|
||||
let Some(p) = out.px.get_mut((y0 + k / sw) * out.width + x0 + k % sw) else { continue };
|
||||
let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record);
|
||||
*p = over(blend, *p, [s[0], s[1], s[2], a]);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `knock` (of record `record`, in `blend`, with its `fill` and `opacity`), a layer with a shallow
|
||||
/// knockout, knocking out `acc`, on a canvas covering both, as [`blend_onto`] makes it. Where
|
||||
/// `knock` has pixels, its transparency is the share of `acc` cleared and replaced by its color at
|
||||
/// `fill`; `opacity` then fades that back toward `acc` (in Dissolve, each pixel is cleared fully
|
||||
/// or not at all, at the share its transparency times `opacity` gives). `false`, with `acc` as it
|
||||
/// was, when the canvases would take more than `max_alloc` bytes.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn knock_onto(
|
||||
acc: &mut Option<Canvas>,
|
||||
knock: &Canvas,
|
||||
blend: Blend,
|
||||
fill: f32,
|
||||
opacity: f32,
|
||||
record: usize,
|
||||
max_alloc: u64,
|
||||
spend: &dyn Fn(u64) -> Result<(), String>,
|
||||
) -> Result<bool, String> {
|
||||
if !cover(acc, knock, max_alloc, spend)? {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(out) = acc.as_mut() else { return Ok(false) };
|
||||
let (fill, opacity) = (fill.clamp(0.0, 1.0), opacity.clamp(0.0, 1.0));
|
||||
let (kw, x0, y0) = (knock.width.max(1), (knock.left - out.left) as usize, (knock.top - out.top) as usize);
|
||||
for (k, s) in knock.px.iter().enumerate() {
|
||||
let Some(p) = out.px.get_mut((y0 + k / kw) * out.width + x0 + k % kw) else { continue };
|
||||
let t = coverage(blend, s[3].clamp(0.0, 1.0) * opacity, knock.left + (k % kw) as i64, knock.top + (k / kw) as i64, record);
|
||||
let below = p[3].clamp(0.0, 1.0);
|
||||
let alpha = (1.0 - t) * below + t * fill;
|
||||
if alpha <= 0.0 {
|
||||
*p = [0.0; 4];
|
||||
continue;
|
||||
}
|
||||
let mix = |i: usize| ((1.0 - t) * below * p[i] + t * fill * s[i]) / alpha;
|
||||
*p = [mix(0), mix(1), mix(2), alpha];
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Does `knock`, as [`knock_onto`] takes it, clear any of a pixel of `below` that has paint?
|
||||
fn cuts_paint(below: &Canvas, knock: &Canvas, blend: Blend, opacity: f32, record: usize) -> bool {
|
||||
let (kw, opacity) = (knock.width.max(1), opacity.clamp(0.0, 1.0));
|
||||
knock.px.iter().enumerate().any(|(k, s)| {
|
||||
let (x, y) = (knock.left + (k % kw) as i64, knock.top + (k / kw) as i64);
|
||||
below.get(x, y).is_some_and(|b| b[3] > 0.0) && coverage(blend, s[3].clamp(0.0, 1.0) * opacity, x, y, record) > 0.0
|
||||
})
|
||||
}
|
||||
|
||||
/// `acc` grown, when it doesn't already, to a canvas covering itself and `src` (a new one counted
|
||||
/// with `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a
|
||||
/// larger canvas when one is needed, would take more than `max_alloc` bytes.
|
||||
fn cover(acc: &mut Option<Canvas>, src: &Canvas, max_alloc: u64, spend: &dyn Fn(u64) -> Result<(), String>) -> Result<bool, String> {
|
||||
let (mut left, mut top, mut right, mut bottom) = (src.left, src.top, src.left + src.width as i64, src.top + src.height as i64);
|
||||
if let Some(a) = acc.as_ref() {
|
||||
left = left.min(a.left);
|
||||
@@ -1475,14 +1980,6 @@ fn blend_onto(
|
||||
}
|
||||
*acc = Some(out);
|
||||
}
|
||||
let Some(out) = acc.as_mut() else { return Ok(false) };
|
||||
// Only the source's rows and columns change.
|
||||
let (sw, x0, y0) = (src.width.max(1), (src.left - left) as usize, (src.top - top) as usize);
|
||||
for (k, s) in src.px.iter().enumerate() {
|
||||
let Some(p) = out.px.get_mut((y0 + k / sw) * width + x0 + k % sw) else { continue };
|
||||
let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record);
|
||||
*p = over(blend, *p, [s[0], s[1], s[2], a]);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -1521,11 +2018,28 @@ pub(super) fn import(
|
||||
layers: 0,
|
||||
notes: Notes::default(),
|
||||
noted: vec![false; records.len()],
|
||||
noted_log: vec![],
|
||||
skipped: vec![false; records.len()],
|
||||
skip_log: vec![],
|
||||
unknocked: vec![false; records.len()],
|
||||
unknock_log: vec![],
|
||||
clipped_out: vec![false; records.len()],
|
||||
clipped_out_log: vec![],
|
||||
unclipped: vec![false; records.len()],
|
||||
unclip_log: vec![],
|
||||
kept: vec![false; records.len()],
|
||||
spent: Cell::new(0),
|
||||
wasted: Cell::new(0),
|
||||
trial: Cell::new(0),
|
||||
painted: Cell::new(0),
|
||||
blank: vec![None; records.len()],
|
||||
laid_blank: vec![false; records.len()],
|
||||
blank_log: vec![],
|
||||
squeezed: 0,
|
||||
};
|
||||
let layers = b.list(&items)?;
|
||||
let layers = b.list(&items, Level::Top)?;
|
||||
// A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't.
|
||||
b.notes.hidden = b.skipped.iter().zip(&b.kept).filter(|&(s, k)| *s && !*k).count();
|
||||
let Builder { mut doc, notes, .. } = b;
|
||||
if !layers.is_empty() {
|
||||
doc.layers = layers;
|
||||
|
||||
@@ -646,6 +646,453 @@ fn dissolve_layers_merge_as_opaque_or_transparent_pixels() {
|
||||
assert!((32..=96).contains(&red), "{red} of 256 pixels show the lower layer: {r}");
|
||||
}
|
||||
|
||||
/// A layer with a Knockout value of `knko` and a fill opacity of `fill`.
|
||||
fn knockout(l: L, knko: u8, fill: u8) -> L {
|
||||
let mut l = l;
|
||||
l.blocks.push((*b"knko", vec![knko, 0, 0, 0]));
|
||||
l.blocks.push((*b"iOpa", vec![fill]));
|
||||
l
|
||||
}
|
||||
|
||||
/// A green layer under a group of `group_blend` holding a red layer and `cut` above it.
|
||||
fn knockout_stack(group_blend: &'static [u8; 4], cut: L) -> Vec<L> {
|
||||
vec![
|
||||
layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]),
|
||||
group_end(),
|
||||
layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]),
|
||||
cut,
|
||||
group("Group", group_blend),
|
||||
]
|
||||
}
|
||||
|
||||
/// The names of the document's layers, and of the layers in its second one.
|
||||
fn knockout_names(s: &Session) -> (Vec<String>, Vec<String>) {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let names = |ls: &[std::sync::Arc<Node>]| ls.iter().map(|l| name(l).to_string()).collect::<Vec<_>>();
|
||||
(names(&d.layers), d.layers.get(1).and_then(|g| g.children()).map_or(vec![], |c| names(c)))
|
||||
}
|
||||
|
||||
/// A layer with a shallow knockout in a group merges with the layers below it in the group: its
|
||||
/// shape clears them to transparency, it draws there at its fill opacity, and its opacity fades
|
||||
/// that. What is outside the group stays a layer of its own and shows through.
|
||||
#[test]
|
||||
fn knockout_layers_merge_with_the_layers_below_them_in_their_group() {
|
||||
let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill);
|
||||
for (fill, opacity, at_cut) in [(0, 255, [0, 0, 0, 0]), (128, 255, [0, 0, 255, 128]), (0, 128, [255, 0, 0, 127]), (255, 255, [0, 0, 255, 255])] {
|
||||
for group_blend in [b"norm", b"pass"] {
|
||||
let (s, r) = open(&file(4, 4, &knockout_stack(group_blend, cut(fill, opacity)), 8, false, false), json!({}));
|
||||
assert_eq!(r["warnings"], json!([]), "{r}");
|
||||
let (top, inner) = knockout_names(&s);
|
||||
assert_eq!((top, inner), (vec!["Outside".to_string(), "Group".into()], vec!["Lower + Cut".to_string()]), "{fill} {opacity}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers[1].isolate, group_blend == b"norm");
|
||||
let ((x, y), px) = image_of(&s, &d.layers[1].children().unwrap()[0]);
|
||||
assert_eq!(((x, y), px.dimensions()), ((0.0, 0.0), (4, 4)));
|
||||
assert_eq!((px.get_pixel(1, 1).0, px.get_pixel(3, 3).0), (at_cut, [255, 0, 0, 255]), "{fill} {opacity}");
|
||||
}
|
||||
}
|
||||
// A layer mask shapes the cut: where it hides the layer, nothing below is cleared.
|
||||
let mut masked = cut(0, 255);
|
||||
masked.mask = Some(([0, 0, 1, 1], 255, 0, vec![0]));
|
||||
let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", masked), 8, false, false), json!({}));
|
||||
let px = image_of(&s, &s.doc().unwrap().doc.layers[1].children().unwrap()[0]).1;
|
||||
assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(1, 1).0), ([255, 0, 0, 255], [0, 0, 0, 0]), "{r}");
|
||||
// Without a knockout (0), the layers stay apart.
|
||||
let (s, r) =
|
||||
open(&file(4, 4, &knockout_stack(b"norm", knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 0, 0)), 8, false, false), json!({}));
|
||||
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([])), "{r}");
|
||||
}
|
||||
|
||||
/// The knockouts this import doesn't apply come in as layers, counted in a warning: at the top level,
|
||||
/// on a clipped layer, and with a Knockout value other than 1. Hidden ones that would need the merge
|
||||
/// are left out; one that draws nothing, or nothing below it, merges nothing.
|
||||
#[test]
|
||||
fn knockouts_that_arent_applied_are_said() {
|
||||
const UNAPPLIED: &str = "the knockout of 1 layer wasn't applied";
|
||||
let cut = |l: L, knko: u8| knockout(l, knko, 0);
|
||||
let blue = || layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]);
|
||||
// At the top level.
|
||||
let layers = [layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), cut(blue(), 1)];
|
||||
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({}));
|
||||
assert_eq!((knockout_names(&s).0, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
|
||||
// Another Knockout value, and a clipped layer, in a group.
|
||||
let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(blue(), 2)), 8, false, false), json!({}));
|
||||
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
|
||||
let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(L { clipped: true, ..blue() }, 1)), 8, false, false), json!({}));
|
||||
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([UNAPPLIED])), "{r}");
|
||||
// In a pass-through group, a layer below it, or the knockout itself, in another mode blends with
|
||||
// what is outside the group: the layers stay apart, and the lower one still multiplies the green
|
||||
// outside. In an isolated group they merge.
|
||||
let mut multiply = knockout_stack(b"pass", cut(blue(), 1));
|
||||
multiply[2].blend = b"mul ";
|
||||
let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({}));
|
||||
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[1].children().unwrap()[0].blend, BlendMode::Multiply);
|
||||
let (s, r) = open(&file(4, 4, &knockout_stack(b"pass", cut(L { blend: b"mul ", ..blue() }, 1)), 8, false, false), json!({}));
|
||||
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
|
||||
multiply[4] = group("Group", b"norm");
|
||||
let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({}));
|
||||
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([])), "{r}");
|
||||
// A hidden knockout would need the merge: left out, hidden layers asked for or not.
|
||||
for hidden in [false, true] {
|
||||
let (s, r) =
|
||||
open(&file(4, 4, &knockout_stack(b"norm", cut(L { hidden: true, ..blue() }, 1)), 8, false, false), json!({"hiddenLayers": hidden}));
|
||||
assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{hidden}: {r}");
|
||||
}
|
||||
// One that stores no pixels or only transparent ones cuts nothing, and merges nothing.
|
||||
for (l, inner) in [(L { bare: true, ..blue() }, vec!["Lower"]), (layer("Cut", [0, 0, 2, 2], [0, 0, 255, 0]), vec!["Lower", "Cut"])] {
|
||||
let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(l, 1)), 8, false, false), json!({}));
|
||||
assert_eq!((knockout_names(&s).1, &r["warnings"]), (inner.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}");
|
||||
}
|
||||
// Nothing below it in its group: it comes in as a layer.
|
||||
let layers = [group_end(), cut(blue(), 1), group("Group", b"norm"), layer("Over", [0, 0, 1, 1], [9, 9, 9, 255])];
|
||||
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Cut"], "{r}");
|
||||
assert_eq!(r["warnings"], json!([]), "{r}");
|
||||
}
|
||||
|
||||
/// A knockout that changes nothing below it leaves the layers apart, hidden ones included: one at 0
|
||||
/// opacity, one at 0 fill over layers that are transparent or beside their painted pixels, and one
|
||||
/// whose layer mask hides all of it. At 0 fill over painted layers, and
|
||||
/// at a fill over transparent ones, it still merges. A knockout at 0 fill over a transparent layer
|
||||
/// stays apart without a warning when their merge would need more memory than allowed.
|
||||
#[test]
|
||||
fn knockouts_that_change_nothing_keep_the_layers_apart() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let layers = [
|
||||
group_end(),
|
||||
layer("Lower", [0, 0, 2, 2], [255, 0, 0, 0]),
|
||||
knockout(layer("Cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0),
|
||||
group("Group", b"norm"),
|
||||
];
|
||||
// The two 2 × 2 layers drawn together fit 256 bytes, but not the 4 × 4 canvas covering both.
|
||||
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 256, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Lower", "Cut"]);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let lower = |alpha: u8| layer("Lower", [0, 0, 4, 4], [255, 0, 0, alpha]);
|
||||
let hidden = L { hidden: true, ..layer("Hidden", [0, 0, 4, 4], [0, 255, 0, 255]) };
|
||||
let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill);
|
||||
let inner = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(vec![], |c| c.iter().map(|l| name(l).to_string()).collect::<Vec<_>>());
|
||||
for (alpha, fill, opacity, apart) in [(255, 0, 0, true), (0, 0, 255, true), (255, 0, 255, false), (0, 128, 255, false)] {
|
||||
let layers = [group_end(), lower(alpha), hidden.clone(), cut(fill, opacity), group("Group", b"norm")];
|
||||
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
|
||||
let (names, warnings) = if apart { (vec!["Lower", "Hidden", "Cut"], json!([])) } else { (vec!["Lower + Cut"], json!([HIDDEN_1])) };
|
||||
assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &warnings), "{alpha} {fill} {opacity}: {r}");
|
||||
}
|
||||
// A hidden knockout that needs no merge comes in with hidden layers: at 0 opacity, with nothing
|
||||
// below it in its group, at 0 fill beside the painted pixels below it, and with a layer mask that
|
||||
// hides all of it.
|
||||
let hidden_cut = |opacity: u8| L { hidden: true, ..cut(0, opacity) };
|
||||
let beside = L { hidden: true, ..knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0) };
|
||||
let masked = L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..cut(255, 255) };
|
||||
for (layers, names) in [
|
||||
(vec![group_end(), lower(255), hidden_cut(0), group("Group", b"norm")], vec!["Lower", "Cut"]),
|
||||
(vec![group_end(), hidden_cut(255), group("Group", b"norm")], vec!["Cut"]),
|
||||
(vec![group_end(), layer("Lower", [2, 2, 4, 4], [255, 0, 0, 255]), beside, group("Group", b"norm")], vec!["Lower", "Cut"]),
|
||||
(vec![group_end(), lower(255), masked.clone(), group("Group", b"norm")], vec!["Lower", "Cut"]),
|
||||
] {
|
||||
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
|
||||
assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}");
|
||||
}
|
||||
// With the mask switched off it would need the merge, and is left out.
|
||||
let unmasked = L { mask: Some(([0, 0, 2, 2], 0, 2, vec![0; 4])), ..masked };
|
||||
let (s, r) = open(&file(4, 4, &[group_end(), lower(255), unmasked, group("Group", b"norm")], 8, false, false), json!({"hiddenLayers": true}));
|
||||
assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}");
|
||||
// A hidden knockout group that would need the merge is counted once, as a hidden layer left out:
|
||||
// its type layer and its own hidden layer aren't counted.
|
||||
let mut words = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]);
|
||||
words.blocks.push((*b"TySh", vec![0; 4]));
|
||||
let layers = [
|
||||
group_end(),
|
||||
lower(255),
|
||||
group_end(),
|
||||
words.clone(),
|
||||
L { hidden: true, ..layer("Inner", [0, 0, 2, 2], [0, 0, 255, 255]) },
|
||||
L { hidden: true, ..knockout(group("Cut", b"norm"), 1, 255) },
|
||||
group("Group", b"norm"),
|
||||
];
|
||||
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
|
||||
assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}");
|
||||
// One whose layer mask hides all of it needs no merge, but a knockout above it merges the layers
|
||||
// and leaves it out: it is counted once, without its type layer.
|
||||
let layers = [
|
||||
group_end(),
|
||||
lower(255),
|
||||
group_end(),
|
||||
words,
|
||||
L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..knockout(group("Masked", b"norm"), 1, 255) },
|
||||
cut(0, 255),
|
||||
group("Group", b"norm"),
|
||||
];
|
||||
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
|
||||
assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([HIDDEN_1])), "{r}");
|
||||
}
|
||||
|
||||
/// With hidden layers asked for, the hidden layers of a group drawn for a knockout or a clip that
|
||||
/// isn't made come in, and aren't counted as left out: a knockout group over a layer that stores no
|
||||
/// pixels, and a clipped group whose merge needs more memory than allowed.
|
||||
#[test]
|
||||
fn hidden_layers_of_a_group_drawn_for_a_merge_not_made_come_in() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let children = |l: &Node| l.children().map_or(vec![], |c| c.iter().map(|l| (name(l).to_string(), l.visible)).collect::<Vec<_>>());
|
||||
let shown_and_hidden =
|
||||
|| [group_end(), layer("Shown", [0, 0, 2, 2], [0, 0, 255, 255]), L { hidden: true, ..layer("Hidden", [2, 2, 4, 4], [0, 255, 0, 255]) }];
|
||||
let both = vec![("Shown".to_string(), true), ("Hidden".to_string(), false)];
|
||||
// A knockout group over a layer that stores no pixels.
|
||||
let mut layers = vec![group_end(), L { bare: true, ..layer("Lower", [0, 0, 2, 2], [0; 4]) }];
|
||||
layers.extend(shown_and_hidden());
|
||||
layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]);
|
||||
let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let cut = &d.layers[0].children().unwrap()[0];
|
||||
assert_eq!((name(cut), children(cut), &r["warnings"]), ("Cut", both.clone(), &json!([])), "{r}");
|
||||
// A clipped group whose merge with its base doesn't fit 320 bytes.
|
||||
let mut layers = vec![layer("Base", [0, 0, 2, 2], [255, 0, 0, 255])];
|
||||
layers.extend(shown_and_hidden());
|
||||
layers[2].rect = [0, 0, 4, 4];
|
||||
layers.push(L { clipped: true, ..group("Clipped", b"norm") });
|
||||
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), true, 320, cms).unwrap().unwrap();
|
||||
let clipped = &doc.layers[1];
|
||||
assert_eq!((name(clipped), children(clipped)), ("Clipped", both), "{warnings:?}");
|
||||
assert_eq!(warnings, ["1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]);
|
||||
}
|
||||
|
||||
/// A knockout's merge whose canvases would need more memory than allowed leaves the layers apart,
|
||||
/// with a warning. One at 0 fill beside the painted pixels below it cuts nothing, and stays apart
|
||||
/// whatever the memory.
|
||||
#[test]
|
||||
fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let stack = |cut: [i32; 4]| {
|
||||
let layers = [
|
||||
group_end(),
|
||||
layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
|
||||
knockout(layer("Cut", cut, [0, 0, 255, 255]), 1, 0),
|
||||
group("Group", b"norm"),
|
||||
];
|
||||
file(4, 4, &layers, 8, false, false)
|
||||
};
|
||||
let names = |doc: &vectorcraft_doc::Document| doc.layers[0].children().unwrap().iter().map(|c| name(c).to_string()).collect::<Vec<_>>();
|
||||
let f = stack([1, 1, 3, 3]);
|
||||
// Each 2 × 2 layer fits 128 bytes (16 a pixel), but not the canvas of the layer below with the
|
||||
// knockout's canvas held beside it.
|
||||
let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap();
|
||||
assert_eq!(names(&doc), ["Lower", "Cut"]);
|
||||
assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
|
||||
let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
|
||||
assert_eq!(names(&doc), ["Lower + Cut"]);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
for max_alloc in [128, 1 << 20] {
|
||||
let (doc, warnings) = psdlayers::import(&stack([2, 2, 4, 4]), false, max_alloc, cms).unwrap().unwrap();
|
||||
assert_eq!(names(&doc), ["Lower", "Cut"], "{max_alloc}");
|
||||
assert!(warnings.is_empty(), "{max_alloc}: {warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A knockout that cuts nothing gives back what drawing the layers below it counted: here a
|
||||
/// knockout at 0 fill beside a group, whose own knockout doesn't fit 192 bytes while the outer
|
||||
/// knockout's canvas is held, but merges when the group comes in.
|
||||
#[test]
|
||||
fn a_knockout_that_cuts_nothing_doesnt_keep_what_drawing_below_it_counted() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let layers = [
|
||||
group_end(),
|
||||
group_end(),
|
||||
layer("Opaque", [0, 0, 2, 2], [255, 0, 0, 255]),
|
||||
knockout(layer("Inner cut", [0, 0, 1, 2], [0, 0, 255, 255]), 1, 0),
|
||||
group("Inner", b"norm"),
|
||||
knockout(layer("Outer cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0),
|
||||
group("Outer", b"norm"),
|
||||
];
|
||||
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 192, cms).unwrap().unwrap();
|
||||
let outer = doc.layers[0].children().unwrap();
|
||||
assert_eq!(outer.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner", "Outer cut"], "{warnings:?}");
|
||||
assert_eq!(outer[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Opaque + Inner cut"], "{warnings:?}");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// A knockout merge that can't be made leaves the import the whole allowance for reading the layers
|
||||
/// apart: here the merge decodes 22 layers over one another before the layer beside them makes its
|
||||
/// canvas too large, which used up nearly all of eight times 64 KiB. The merge has that allowance
|
||||
/// also after five layers below the group were read, and a knockout at 0 fill over 22 transparent
|
||||
/// layers, which cuts no paint after they are drawn, leaves the same room.
|
||||
#[test]
|
||||
fn a_knockout_merge_not_made_leaves_room_to_read_the_layers() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let mut layers = vec![group_end()];
|
||||
layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 255])));
|
||||
layers.push(layer("Beside", [0, 64, 32, 96], [0, 255, 0, 255]));
|
||||
layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]);
|
||||
let (doc, warnings) = psdlayers::import(&file(96, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers[0].children().unwrap().len(), 24, "{warnings:?}");
|
||||
assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
|
||||
let mut after_five = vec![layer("Outside", [0, 0, 32, 32], [0, 0, 0, 255]); 5];
|
||||
after_five.extend(layers);
|
||||
let (doc, warnings) = psdlayers::import(&file(96, 32, &after_five, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
|
||||
assert_eq!((doc.layers.len(), doc.layers[5].children().unwrap().len()), (6, 24), "{warnings:?}");
|
||||
assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
|
||||
let mut layers = vec![group_end()];
|
||||
layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 0])));
|
||||
layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]);
|
||||
let (doc, warnings) = psdlayers::import(&file(32, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers[0].children().unwrap().len(), 23, "{warnings:?}");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// A hidden knockout in a mode VectorCraft lacks is left out without being drawn, hidden layers
|
||||
/// asked for: here its pixels are larger than the memory allowed for one image.
|
||||
#[test]
|
||||
fn a_hidden_knockout_in_a_mode_vectorcraft_lacks_is_left_out_unread() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let layers = [
|
||||
group_end(),
|
||||
layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
|
||||
L { hidden: true, blend: b"diss", ..knockout(layer("Cut", [0, 0, 8, 8], [0, 0, 255, 255]), 1, 255) },
|
||||
group("Group", b"norm"),
|
||||
];
|
||||
let (doc, warnings) = psdlayers::import(&file(8, 8, &layers, 8, false, false), true, 128, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Lower"]);
|
||||
assert_eq!(warnings, [HIDDEN_1]);
|
||||
}
|
||||
|
||||
/// A Dissolve knockout at part opacity clears each pixel below it fully or not at all, at the share
|
||||
/// its opacity gives, as a Dissolve layer merges.
|
||||
#[test]
|
||||
fn a_dissolve_knockout_at_part_opacity_clears_whole_pixels() {
|
||||
let cut = knockout(L { blend: b"diss", opacity: 128, ..layer("Cut", [0, 0, 16, 16], [0, 0, 255, 255]) }, 1, 0);
|
||||
let layers = [group_end(), layer("Lower", [0, 0, 16, 16], [255, 0, 0, 255]), cut, group("Group", b"norm")];
|
||||
let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (_, px) = image_of(&s, &d.layers[0].children().unwrap()[0]);
|
||||
assert!(px.pixels().all(|p| p.0 == [255, 0, 0, 255] || p.0[3] == 0), "{r}");
|
||||
let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count();
|
||||
assert!((32..=224).contains(&red), "{red} of 256 pixels keep the lower layer: {r}");
|
||||
}
|
||||
|
||||
/// The knockout of a layer that another is clipped to isn't applied, also when the clipped layer's
|
||||
/// merge with it needs more memory than allowed and the two come in apart.
|
||||
#[test]
|
||||
fn a_clipping_base_knockout_isnt_applied_when_its_clip_doesnt_fit() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
// The 4 × 4 clipped layer and its 2 × 2 base don't fit 320 bytes together for the clip; the
|
||||
// base's knockout merge with the 2 × 2 layer below would.
|
||||
let layers = [
|
||||
group_end(),
|
||||
layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
|
||||
knockout(layer("Base", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0),
|
||||
L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 255, 0, 255]) },
|
||||
group("Group", b"norm"),
|
||||
];
|
||||
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 320, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["Lower", "Base", "Clipped"], "{warnings:?}");
|
||||
assert_eq!(
|
||||
warnings,
|
||||
["the knockout of 1 layer wasn't applied", "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]
|
||||
);
|
||||
}
|
||||
|
||||
/// A knockout group that comes in as a layer counts each layer clipped in it once in the warnings,
|
||||
/// though its layers are also drawn for the knockout: one clipped to a fill that isn't drawn, and
|
||||
/// one that a merge past the memory allowed leaves unclipped.
|
||||
#[test]
|
||||
fn a_knockout_group_that_comes_in_as_a_layer_counts_its_clipped_layers_once() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let empty = L { bare: true, ..layer("Empty", [0, 0, 2, 2], [0, 0, 0, 0]) };
|
||||
// A fill whose shape is a vector mask, with a layer clipped to it: neither is drawn.
|
||||
let mut soco = vec![0; 8];
|
||||
for (key, v) in [(b"Rd doub", 255.0f64), (b"Grn doub", 0.0), (b"Bl doub", 51.0)] {
|
||||
soco.extend(key);
|
||||
soco.extend(v.to_be_bytes());
|
||||
}
|
||||
let mut outline = layer("Outline", [0, 0, 0, 0], [0; 4]);
|
||||
outline.blocks.push((*b"SoCo", soco));
|
||||
outline.blocks.push((*b"vsms", vec![0; 8]));
|
||||
let on_outline = L { clipped: true, ..layer("On outline", [0, 0, 2, 2], [1, 1, 1, 255]) };
|
||||
// Each 2 × 2 layer fits 128 bytes, and so do the two drawn together, but not the merge of the
|
||||
// clipped one with the one below.
|
||||
let base = layer("Base", [0, 0, 2, 2], [255, 0, 0, 255]);
|
||||
let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 2, 2], [0, 0, 255, 255]) };
|
||||
for (inner, said) in [
|
||||
(vec![outline, on_outline], "1 layer clipped to a fill layer that wasn't drawn was left out"),
|
||||
(vec![base, clipped], "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"),
|
||||
] {
|
||||
let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]), group_end(), empty.clone(), group_end()];
|
||||
layers.extend(inner);
|
||||
layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]);
|
||||
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Outside", "Group"]);
|
||||
assert!(warnings.iter().any(|w| w == said), "{said}: {warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A pass-through group that draws nothing still counts what its layers count in it, also when it
|
||||
/// is drawn again inside a group that merges: a knockout above a Multiply layer isn't applied in a
|
||||
/// pass-through group, though drawn alone it would be.
|
||||
#[test]
|
||||
fn a_pass_through_group_that_draws_nothing_still_counts_its_unapplied_knockouts() {
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) };
|
||||
let layers = [
|
||||
layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]),
|
||||
group_end(),
|
||||
empty("Empty", b"norm"),
|
||||
group_end(),
|
||||
empty("Multiplied", b"mul "),
|
||||
knockout(empty("Cut", b"norm"), 1, 255),
|
||||
knockout(group("Through", b"pass"), 1, 255),
|
||||
group("Dissolved", b"diss"),
|
||||
];
|
||||
let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms).unwrap().unwrap();
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Lower + Dissolved"], "{warnings:?}");
|
||||
assert_eq!(warnings, ["the knockout of 1 layer wasn't applied".to_string(), psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]);
|
||||
}
|
||||
|
||||
/// A group that draws nothing is drawn once, however deep the groups like it nest: here each holds
|
||||
/// a layer that stores no pixels and, above it, the next group, with a knockout. The import walks
|
||||
/// at most as many layer lists as the file has records, with isolated groups, with groups that
|
||||
/// alternate with pass-through ones, with pass-through groups inside the outermost one (whose
|
||||
/// knockouts aren't applied), and with a layer in a mode VectorCraft lacks in each (a merge of
|
||||
/// nothing, a canvas without pixels).
|
||||
#[test]
|
||||
fn groups_that_draw_nothing_are_drawn_once_however_deep_they_nest() {
|
||||
const LEVELS: usize = 48;
|
||||
let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
|
||||
let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) };
|
||||
// Which levels are pass-through groups.
|
||||
let none: fn(usize) -> bool = |_| false;
|
||||
let odd: fn(usize) -> bool = |k| k % 2 == 1;
|
||||
let all: fn(usize) -> bool = |k| k > 0;
|
||||
for (case, pass, dissolve, warned) in [
|
||||
("isolated", none, false, vec![]),
|
||||
("alternating", odd, false, vec![]),
|
||||
("pass-through", all, false, vec![format!("the knockout of {} layers wasn't applied", LEVELS - 1)]),
|
||||
("dissolved", none, true, vec![psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]),
|
||||
] {
|
||||
let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255])];
|
||||
for _ in 0..=LEVELS {
|
||||
layers.push(group_end());
|
||||
if dissolve {
|
||||
layers.push(empty("Dissolved", b"diss"));
|
||||
}
|
||||
layers.push(empty("Empty", b"norm"));
|
||||
}
|
||||
for k in (0..=LEVELS).rev() {
|
||||
let g = group("Group", if pass(k) { b"pass" } else { b"norm" });
|
||||
layers.push(if k == 0 { g } else { knockout(g, 1, 255) });
|
||||
}
|
||||
psdlayers::WALKS.set((0, layers.len()));
|
||||
let imported = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms);
|
||||
let (walked, _) = psdlayers::WALKS.replace((0, usize::MAX));
|
||||
let (doc, warnings) = imported.unwrap().unwrap();
|
||||
assert!(walked <= layers.len(), "{case}: {walked} walks for {} records", layers.len());
|
||||
assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Outside", "Group"], "{case}");
|
||||
let mut expected = warned;
|
||||
expected.push(vectorcraft_doc::depth::merged_note());
|
||||
assert_eq!(warnings, expected, "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_doesnt_come_in_is_said() {
|
||||
let mut text = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]);
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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)} (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…], 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
|
||||
),
|
||||
|
||||
@@ -202,6 +202,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
|
||||
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
|
||||
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
|
||||
// A rectangle's Rectangle Angle and an ellipse's Ellipse Angle, as `polygonAngle` turns a polygon.
|
||||
let (rectangle_angle, ellipse_angle) = (angle("rectangleAngle")?, angle("ellipseAngle")?);
|
||||
// Whether a shape at `now` already stands at `a`: a turn the rounding of an earlier one left
|
||||
// (89.999999999°, or 359.9999999999° against 0°) counts as no change.
|
||||
let at_angle = |now: Option<f64>, a: f64| {
|
||||
now.is_some_and(|n| {
|
||||
let d = (n - a).rem_euclid(360.0);
|
||||
d.min(360.0 - d) < 1e-9
|
||||
})
|
||||
};
|
||||
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
|
||||
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
|
||||
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
|
||||
@@ -249,12 +259,15 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(l @ LiveShape::Polygon { sides: now, .. })
|
||||
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
|
||||
&& (!equal || l.polygon_sides_equal())
|
||||
&& polygon_angle.is_none_or(|a| l.polygon_angle() == Some(a))
|
||||
&& polygon_angle.is_none_or(|a| at_angle(l.polygon_angle(), a))
|
||||
&& side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius).is_none_or(|r| l.polygon_radius() == Some(r))) =>
|
||||
{
|
||||
return false;
|
||||
}
|
||||
Some(LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie => return false,
|
||||
Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => {
|
||||
return false;
|
||||
}
|
||||
Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false,
|
||||
_ => {}
|
||||
}
|
||||
if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) {
|
||||
@@ -298,9 +311,18 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
*path = l.to_path();
|
||||
}
|
||||
if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut()
|
||||
&& (pie_start.is_some() || pie_end.is_some() || invert)
|
||||
if let Some(a) = rectangle_angle
|
||||
&& let Some(l @ LiveShape::Rectangle { .. }) = live.as_deref_mut()
|
||||
{
|
||||
l.set_shape_angle(a);
|
||||
*path = l.to_path();
|
||||
}
|
||||
if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut()
|
||||
&& (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some())
|
||||
{
|
||||
if let Some(a) = ellipse_angle {
|
||||
l.set_shape_angle(a);
|
||||
}
|
||||
if let LiveShape::Ellipse { pie, .. } = l {
|
||||
*pie = pie_of(*pie);
|
||||
}
|
||||
@@ -339,6 +361,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &ids {
|
||||
super::pixelgrid::resnap(d, *id);
|
||||
}
|
||||
// A shape named in `ids` and not selected is not checked after the edit: one that a turn or
|
||||
// a new radius would take past the coordinate limit is an error here, and nothing changes.
|
||||
if !crate::sanity::objects_in_range(d, &ids) {
|
||||
return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -9,12 +9,13 @@
|
||||
//! **Repeat** objects are live nodes (`NodeKind::Repeat`) holding the source art and the
|
||||
//! arrangement; `vectorcraft_doc::pattern` evaluates the instances.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::pattern::{self, Overlap, PATTERN_EDIT_LAYER, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType, pattern_paint};
|
||||
use vectorcraft_doc::swatches::PaintFn;
|
||||
use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_paints, walk_with_masks};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
@@ -37,6 +38,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
can_make_pattern,
|
||||
pattern_make
|
||||
),
|
||||
cmd!(
|
||||
"object.pattern.replaceArt",
|
||||
"Replace Pattern Art",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}",
|
||||
can_replace_pattern_art,
|
||||
pattern_replace_art
|
||||
),
|
||||
cmd!(
|
||||
"object.pattern.edit",
|
||||
"Edit Pattern",
|
||||
@@ -198,6 +208,12 @@ fn has_selection_or_ids(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)
|
||||
}
|
||||
|
||||
/// Replace Pattern Art: a document, and no pattern is being edited.
|
||||
fn can_replace_pattern_art(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if editing(s).is_some() { Err("finish editing the pattern first".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The repeats of the selection: selected ones, and those around a selected object. None while
|
||||
/// an object of a dynamic symbol instance's art is selected.
|
||||
fn selected_repeats(s: &Session) -> Vec<NodeId> {
|
||||
@@ -412,6 +428,103 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result<Strin
|
||||
Ok(pe.pattern)
|
||||
}
|
||||
|
||||
/// Give pattern `name` fresh-id copies of the selected art (or of `ids`) as its tile art, as one
|
||||
/// undo step (`object.pattern.replaceArt`). The pattern keeps its name, swatch, tile and options,
|
||||
/// and its tile fits the new art when its Size Tile to Art is on; paints refer to a pattern by
|
||||
/// name, so every fill and stroke of it draws the new tile. The art stays where it is, selected as
|
||||
/// before. Art that matches the tile art already records nothing.
|
||||
fn pattern_replace_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.pattern.replaceArt";
|
||||
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string();
|
||||
let roots = roots(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?;
|
||||
if roots.is_empty() {
|
||||
return Err(bad(C, "select the art for the pattern tile"));
|
||||
}
|
||||
let src: Vec<Arc<Node>> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect();
|
||||
if paints_pattern(d, &src, &name) {
|
||||
return Err(bad(C, format!("art painted with `{name}` can't be its tile")));
|
||||
}
|
||||
// Copies made from the same next id are equal when the art matches the tile art.
|
||||
let fresh = |art: &[Arc<Node>]| copies(&mut Document::clone(d), art);
|
||||
if fresh(&old) == fresh(&src) {
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
s.edit("Replace Pattern Art", |d, _| {
|
||||
let art: Vec<Arc<Node>> = copies(d, &src).into_iter().map(Arc::new).collect();
|
||||
if let Some(def) = d.pattern_mut(&name) {
|
||||
def.art = art;
|
||||
if def.size_tile_to_art {
|
||||
def.fit_tile_to_art();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// What a piece of art uses by name, for [`paints_pattern`].
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum Uses<'a> {
|
||||
Symbol(&'a str),
|
||||
Pattern(&'a str),
|
||||
GraphDesign(&'a str),
|
||||
Brush(&'a str),
|
||||
}
|
||||
|
||||
/// Does `art` paint pattern `name`, itself or through the symbols (of its instances and of the
|
||||
/// inline graphics in its type), patterns, graph designs and brushes it uses? A graph's stored
|
||||
/// series and label paints count, since its marks and labels take them each time it is drawn again.
|
||||
fn paints_pattern(d: &Document, art: &[Arc<Node>], name: &str) -> bool {
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
// What was already looked into, and the art left to look at.
|
||||
let mut seen: HashSet<Uses> = HashSet::new();
|
||||
let mut left: Vec<&Node> = art.iter().map(|a| &**a).collect();
|
||||
while let Some(n) = left.pop() {
|
||||
let mut used = vec![];
|
||||
walk_with_masks(n, &mut |c| {
|
||||
match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => used.push(Uses::Symbol(symbol.as_str())),
|
||||
// The symbol of every inline graphic in type counts, overset or not.
|
||||
NodeKind::Text(t) => used.extend(t.runs.iter().filter_map(|r| r.inline.as_ref()).map(|a| Uses::Symbol(a.symbol.as_str()))),
|
||||
_ => {}
|
||||
}
|
||||
for it in &c.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Stroke(sk) = it
|
||||
&& let Some(b) = &sk.brush
|
||||
{
|
||||
used.push(Uses::Brush(b.as_str()));
|
||||
}
|
||||
}
|
||||
for p in node_paints(c).chain(override_paints(c)).chain(graph_paints(c)) {
|
||||
if let Paint::Pattern { pattern, .. } = p {
|
||||
used.push(Uses::Pattern(pattern.as_str()));
|
||||
}
|
||||
}
|
||||
if let Some(g) = c.extras().graph.as_deref() {
|
||||
used.extend(g.series_markers.iter().flatten().map(|m| Uses::GraphDesign(m.as_str())));
|
||||
used.extend(g.series_columns.iter().flatten().map(|c| Uses::GraphDesign(c.design.as_str())));
|
||||
}
|
||||
});
|
||||
for u in used {
|
||||
if u == Uses::Pattern(name) {
|
||||
return true;
|
||||
}
|
||||
if !seen.insert(u) {
|
||||
continue;
|
||||
}
|
||||
match u {
|
||||
Uses::Symbol(symbol) => left.extend(d.symbols.iter().find(|x| x.name == symbol).map(|x| &*x.art)),
|
||||
Uses::Pattern(pattern) => left.extend(d.pattern(pattern).into_iter().flat_map(|x| x.art.iter().map(|a| &**a))),
|
||||
Uses::GraphDesign(design) => left.extend(d.graph_designs.iter().find(|x| x.name == design).map(|x| &*x.art)),
|
||||
Uses::Brush(brush) => left.extend(brushes.iter().filter(|x| x.name == brush).flat_map(|x| x.art())),
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Leave pattern editing mode, discarding the changes (`object.pattern.cancel`). An existing
|
||||
/// pattern gets its definition back, its name included when Pattern Options renamed it while it was
|
||||
/// edited and no other pattern, swatch or color group has taken that name since. A new pattern is
|
||||
|
||||
@@ -363,6 +363,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.pattern.done",
|
||||
"object.pattern.edit",
|
||||
"object.pattern.make",
|
||||
"object.pattern.replaceArt",
|
||||
"object.puppetWarp",
|
||||
"object.puppetWarp.pins",
|
||||
"object.rasterize",
|
||||
@@ -571,6 +572,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"shape.rectangularGrid",
|
||||
"shape.spiral",
|
||||
"shape.star",
|
||||
"shape.threePointArc",
|
||||
"shapeBuilder.merge",
|
||||
"shapeBuilder.regions",
|
||||
"shaper.expand",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent};
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, map_node_solid_paints, node_colors};
|
||||
use vectorcraft_doc::{Document, NodeId};
|
||||
use vectorcraft_doc::{Document, NodeId, Selection};
|
||||
|
||||
use super::paint::paint_from;
|
||||
use super::{
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Used Colors",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step → {added: [names], linked}",
|
||||
"{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step (none when there is no new color; the Swatches panel menu's Add Selected Colors sends selection and global; with Global Edit on, the other members keep their colors) → {added: [names], linked}",
|
||||
has_doc,
|
||||
swatch_add_used
|
||||
),
|
||||
@@ -1037,20 +1037,41 @@ fn swatch_sort(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The colors of the art `ids` that no swatch links them to and no solid swatch has, each once, in
|
||||
/// paint order: the swatches Add Used Colors makes.
|
||||
fn new_used_colors(d: &Document, ids: &[NodeId]) -> Vec<Color> {
|
||||
let (mut linked_to, mut colors) = (vec![], vec![]);
|
||||
artwork_colors(d, ids, false, &mut linked_to, &mut colors);
|
||||
// Colors a solid swatch already has are skipped.
|
||||
let have: HashSet<ColorKey> = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect();
|
||||
colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k)));
|
||||
colors
|
||||
}
|
||||
|
||||
fn swatch_add_used(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.addUsedColors";
|
||||
let global = switch_or(p, "global", false, C)?;
|
||||
let only_selection = switch_or(p, "selection", false, C)?;
|
||||
let (added, linked) = s.edit("Add Used Colors", |d, sel| {
|
||||
let used_ids = |d: &Document, sel: &Selection| -> Result<Vec<NodeId>> {
|
||||
let ids: Vec<NodeId> = if only_selection { sel.objects.clone() } else { d.layers.iter().map(|l| l.id).collect() };
|
||||
if only_selection && ids.is_empty() {
|
||||
return Err(bad(C, "select artwork to add its colours"));
|
||||
}
|
||||
let (mut linked_to, mut colors) = (vec![], vec![]);
|
||||
artwork_colors(d, &ids, false, &mut linked_to, &mut colors);
|
||||
// Colours a solid swatch already has are skipped.
|
||||
let have: HashSet<ColorKey> = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect();
|
||||
colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k)));
|
||||
Ok(ids)
|
||||
};
|
||||
// Typing in progress is its own undo step and is in the document the colors are read from.
|
||||
super::variablecmds::settle_typing(s)?;
|
||||
// With no new color there is nothing to add or link, so no edit and no undo step.
|
||||
let st = s.doc()?;
|
||||
if new_used_colors(&st.doc, &used_ids(&st.doc, &st.selection)?).is_empty() {
|
||||
return Ok(json!({"added": [], "linked": 0}));
|
||||
}
|
||||
// Linking a paint to its new swatch keeps its color, so Global Edit gives the link to no other
|
||||
// member: a member whose color differs keeps it.
|
||||
let global_edit = s.doc_mut()?.global_edit.take();
|
||||
let edited = s.edit("Add Used Colors", |d, sel| {
|
||||
let ids = used_ids(&*d, &*sel)?;
|
||||
let colors = new_used_colors(d, &ids);
|
||||
let mut free = d.free_swatch_names();
|
||||
let mut links = vec![];
|
||||
for c in colors {
|
||||
@@ -1060,7 +1081,9 @@ fn swatch_add_used(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let linked = if global { link_colors(d, &ids, &links) } else { 0 };
|
||||
Ok((links.into_iter().map(|(_, n)| n).collect::<Vec<_>>(), linked))
|
||||
})?;
|
||||
});
|
||||
s.doc_mut()?.global_edit = global_edit;
|
||||
let (added, linked) = edited?;
|
||||
Ok(json!({"added": added, "linked": linked}))
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +105,7 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[
|
||||
"symbol.selectInstances",
|
||||
"view.guides.lock",
|
||||
"view.proofSetup",
|
||||
"view.proofSetup.load",
|
||||
"view.proofColors",
|
||||
"view.overprintPreview",
|
||||
"view.separationsPreview",
|
||||
|
||||
@@ -189,6 +189,11 @@ pub struct Session {
|
||||
/// The folder of the New Document profiles `file.new` starts documents from; `None`: none,
|
||||
/// every document starts with the defaults ([`Session::attach_new_doc_profiles`]).
|
||||
new_doc_profile_dir: Option<std::path::PathBuf>,
|
||||
/// The folder of the proof setups `view.proofSetup.save` saves by name and View → Proof Setup
|
||||
/// lists; `None`: no folder ([`Session::attach_proof_setups`]).
|
||||
proof_setup_dir: Option<std::path::PathBuf>,
|
||||
/// How many proof setup files `view.proofSetup.save` wrote ([`Session::proof_setup_saves`]).
|
||||
proof_setup_saves: u64,
|
||||
/// The folder of each script's data folder (`Folder.userData`), beside which the grants file
|
||||
/// keeps the file access people allowed scripts; `None`: no folder
|
||||
/// ([`Session::attach_script_data`]).
|
||||
|
||||
@@ -168,6 +168,8 @@ pub fn refused_to_scripts(id: &str) -> bool {
|
||||
"color.removeProfile",
|
||||
"file.print",
|
||||
"view.proofSetup",
|
||||
"view.proofSetup.save",
|
||||
"view.proofSetup.load",
|
||||
"view.proofColors",
|
||||
"view.overprintPreview",
|
||||
"view.separationsPreview",
|
||||
|
||||
@@ -99,6 +99,8 @@ impl Session {
|
||||
scripts_dir: None,
|
||||
metadata_templates_dir: None,
|
||||
new_doc_profile_dir: None,
|
||||
proof_setup_dir: None,
|
||||
proof_setup_saves: 0,
|
||||
script_data_dir: None,
|
||||
plugin_output: None,
|
||||
plugin_install_approval: None,
|
||||
|
||||
@@ -208,6 +208,7 @@ mod targeting;
|
||||
mod textcombos;
|
||||
mod textedit;
|
||||
pub(super) mod textimport;
|
||||
mod three_point_arc;
|
||||
mod tileedge;
|
||||
mod tints;
|
||||
mod toolsettings;
|
||||
|
||||
@@ -112,6 +112,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"calligraphic-nibs",
|
||||
"pressure-sensitive",
|
||||
"bristle-brushes",
|
||||
"paint",
|
||||
"pattern-borders",
|
||||
"scatter-shapes",
|
||||
"stipple",
|
||||
@@ -119,6 +120,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"energy-beams",
|
||||
"dry-media",
|
||||
"tech-circuit",
|
||||
"engraving",
|
||||
"arrows",
|
||||
"image-brush",
|
||||
"artistic"
|
||||
@@ -170,6 +172,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
("calligraphic-nibs", "calligraphic"),
|
||||
("pressure-sensitive", "art"),
|
||||
("bristle-brushes", "bristle"),
|
||||
("paint", "art"),
|
||||
("pattern-borders", "pattern"),
|
||||
("scatter-shapes", "scatter"),
|
||||
("stipple", "scatter"),
|
||||
@@ -334,6 +337,30 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer {
|
||||
vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engraving_library_draws_fine_parallel_strokes_and_survives_save() {
|
||||
let mut s = session();
|
||||
let listed = run(&mut s, "brush.libraries", json!({}));
|
||||
let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "engraving").unwrap();
|
||||
assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Engraving"), Some("builtIn"), Some(4)));
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Engraving").unwrap();
|
||||
for b in &lib.brushes {
|
||||
for length in [2.0, 200.0] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
|
||||
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name);
|
||||
}
|
||||
}
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap();
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "engraving", "name": "Fine Hatching", "apply": true, "ids": [path]}));
|
||||
assert_eq!(strs(&added["added"]), ["Fine Hatching"]);
|
||||
assert_eq!(added["applied"], json!([path]));
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Fine Hatching"]}));
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let reopened = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(vectorcraft_brush::find(&reopened, "Fine Hatching").unwrap(), lib.brushes[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stipple_library_draws_dot_textures_and_survives_save() {
|
||||
let mut s = session();
|
||||
@@ -581,6 +608,37 @@ fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_librar
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_brushes_draw_distinct_marks_and_survive_a_saved_library() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Paint").unwrap();
|
||||
let names = ["Flat Sweep", "Dry Drag", "Loaded Stroke", "Fan Sweep"];
|
||||
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 curve = line_to(20.0);
|
||||
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
|
||||
for b in &lib.brushes {
|
||||
let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) };
|
||||
assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints);
|
||||
assert_eq!(art.width, 150.0);
|
||||
for line in [line_to(2.0), line_to(180.0), curve.clone()] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
|
||||
let points = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
|
||||
}
|
||||
let before = undo_len(&s);
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "paint", "name": b.name, "apply": true, "ids": [path]}));
|
||||
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
|
||||
assert_eq!(added["applied"], json!([path]));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(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);
|
||||
}
|
||||
|
||||
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
|
||||
/// translucent washes, with names of their own and a few paths of art each.
|
||||
#[test]
|
||||
|
||||
@@ -3331,6 +3331,68 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() {
|
||||
assert!(failed.is_empty(), "{failed:#?}");
|
||||
}
|
||||
|
||||
/// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient,
|
||||
/// nothing selected, or a fill edit of a Live Paint group without faces) is an error that leaves the default gradient as it was, since a gradient
|
||||
/// fitted to each object has no aspect of its own. Named objects still take the aspect.
|
||||
#[test]
|
||||
fn edit_gradient_aspect_without_objects_is_an_error() {
|
||||
let aspect = |n: &Node| match n.appearance.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom.map(|x| x.aspect),
|
||||
_ => None,
|
||||
};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0);
|
||||
s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap();
|
||||
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
|
||||
s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap();
|
||||
let (group, art, fill) = (node(&s, g), node(&s, rect), s.paint.fill.clone());
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert!(!s.gradient_edit_has_objects(false), "the bucket edits its own gradient");
|
||||
for params in [json!({"stroke": false, "aspect": 50}), json!({"stroke": false, "aspect": 50, "reverse": true})] {
|
||||
assert!(s.execute("paint.editGradient", ¶ms).is_err(), "{params}");
|
||||
assert_eq!(s.paint.fill, fill, "{params}: the bucket's gradient stays");
|
||||
}
|
||||
assert_eq!((node(&s, g), node(&s, rect)), (group, art), "the selection keeps its paint");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
|
||||
// Named objects take it.
|
||||
s.execute("paint.editGradient", &json!({"stroke": false, "kind": "radial", "aspect": 50, "ids": [rect.0]})).unwrap();
|
||||
assert_eq!(aspect(&node(&s, rect)), Some(0.5));
|
||||
// Without the bucket and with nothing selected, the default gradient has no aspect either.
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
let fill = s.paint.fill.clone();
|
||||
assert!(!s.gradient_edit_has_objects(false));
|
||||
assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
|
||||
assert_eq!(s.paint.fill, fill, "the default gradient stays");
|
||||
// An empty group has nothing to paint.
|
||||
let empty = s
|
||||
.edit("Group", |d, _| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(d.default_layer(), 0, Node::group(id, vec![]))?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
|
||||
assert!(!s.gradient_edit_has_objects(false), "an empty group");
|
||||
assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
|
||||
// A fill edit of a Live Paint group with edges and no faces edits no object; a stroke edit edits its edges.
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap());
|
||||
let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
|
||||
let (fill, group, steps) = (s.paint.fill.clone(), node(&s, edges_only), s.doc().unwrap().history.undo.len());
|
||||
assert!(!s.gradient_edit_has_objects(false), "a Live Paint group without faces");
|
||||
assert!(s.gradient_edit_has_objects(true), "its edges take a stroke edit");
|
||||
assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
|
||||
assert_eq!((&s.paint.fill, node(&s, edges_only)), (&fill, group), "the default and the group stay");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
|
||||
// A selected object takes it.
|
||||
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
|
||||
assert!(s.gradient_edit_has_objects(false) && s.gradient_edit_has_objects(true));
|
||||
s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 25})).unwrap();
|
||||
assert_eq!(aspect(&node(&s, rect)), Some(0.25));
|
||||
}
|
||||
|
||||
/// With the Live Paint Bucket active, objects named with `ids` still take a stroke, and a brush
|
||||
/// still goes to the selection.
|
||||
#[test]
|
||||
|
||||
@@ -682,6 +682,273 @@ fn proof_setup_simulates_tritanopia() {
|
||||
s.execute("view.proofSetup", &json!({"target": "workingCmyk", "proof": false})).unwrap();
|
||||
}
|
||||
|
||||
/// View › Proof Setup › Customize's settings: an RGB profile as the device, Preserve Numbers and
|
||||
/// Simulate Black Ink, kept in the proof view, read back and drawn; bad values are refused and
|
||||
/// leave the view as it was.
|
||||
#[test]
|
||||
fn proof_setup_takes_the_custom_proof_settings() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _v = DefaultView::new();
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 100.0, 100.0, json!("#000000"));
|
||||
let r = s.execute("view.proofSetup", &json!({})).unwrap();
|
||||
assert_eq!((r["preserveNumbers"].as_bool(), r["simulateBlack"].as_bool()), (Some(false), Some(false)));
|
||||
let device = format!("cmyk:{}", cms::GENERIC_CMYK);
|
||||
let r = s.execute("view.proofSetup", &json!({"target": device, "simulateBlack": true, "proof": true})).unwrap();
|
||||
assert_eq!((r["target"].as_str(), r["simulateBlack"].as_bool(), r["proofColors"].as_bool()), (Some(device.as_str()), Some(true), Some(true)));
|
||||
let setup = vectorcraft_render::proof::active_proof().unwrap();
|
||||
assert!(setup.simulate_black && !setup.preserve_numbers);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let gray = render(&doc, RenderOptions { proof: Some(setup.clone()), ..Default::default() }).pixel(50, 50);
|
||||
let black = render(&doc, RenderOptions { proof: Some(ProofSetup { simulate_black: false, ..setup }), ..Default::default() }).pixel(50, 50);
|
||||
assert!(gray[0] > black[0] + 10, "the press black shows as a gray: {gray:?} vs {black:?}");
|
||||
let rgb = format!("rgb:{}", cms::DISPLAY_P3);
|
||||
let r = s.execute("view.proofSetup", &json!({"target": rgb, "preserveNumbers": true})).unwrap();
|
||||
assert_eq!((r["target"].as_str(), r["preserveNumbers"].as_bool()), (Some(rgb.as_str()), Some(true)));
|
||||
assert_eq!(vectorcraft_render::proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()));
|
||||
// Unchanged settings leave the revision alone.
|
||||
let rev = s.doc().unwrap().revision;
|
||||
s.execute("view.proofSetup", &json!({"target": rgb, "preserveNumbers": true, "simulateBlack": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().revision, rev);
|
||||
let view = vectorcraft_render::proof::view();
|
||||
refused(&mut s, "view.proofSetup", json!({"target": "rgb:Nope"}), "unknown RGB profile `Nope`");
|
||||
refused(&mut s, "view.proofSetup", json!({"target": format!("rgb:{}", cms::GENERIC_CMYK)}), "unknown RGB profile");
|
||||
refused(&mut s, "view.proofSetup", json!({"target": "rgb:"}), "unknown RGB profile");
|
||||
refused(&mut s, "view.proofSetup", json!({"target": "workingCmyk", "preserveNumbers": "yes"}), "`preserveNumbers` must be true or false");
|
||||
refused(&mut s, "view.proofSetup", json!({"simulateBlack": 1}), "`simulateBlack` must be true or false");
|
||||
assert_eq!(vectorcraft_render::proof::view(), view, "the proof view is unchanged");
|
||||
assert_eq!(s.doc().unwrap().revision, rev, "nothing redraws");
|
||||
}
|
||||
|
||||
/// A custom proof setup saved to a file loads back as the same setup with Proof Colors on; saving
|
||||
/// leaves the proof view as it is, and `view.proofSetup.read` only reads the file.
|
||||
#[test]
|
||||
fn a_saved_proof_setup_loads_back() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _v = DefaultView::new();
|
||||
let dir = vectorcraft_testkit::TempDir::new("proof-setup-file");
|
||||
let path = dir.join("press.vcproof").to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
let device = format!("cmyk:{}", cms::GENERIC_CMYK);
|
||||
let r = s
|
||||
.execute(
|
||||
"view.proofSetup.save",
|
||||
&json!({"path": path, "target": device, "intent": "perceptual", "preserveNumbers": true, "simulateBlack": true}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((r["path"].as_str(), r["target"].as_str(), r["intent"].as_str()), (Some(path.as_str()), Some(device.as_str()), Some("perceptual")));
|
||||
assert_eq!(vectorcraft_render::proof::view(), Default::default(), "saving leaves the proof view alone");
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(text.contains("\"format\": \"vectorcraft-proof-setup\"") && text.contains("\"version\": 1"), "{text}");
|
||||
let r = s.execute("view.proofSetup.read", &json!({"path": path})).unwrap();
|
||||
assert_eq!((r["target"].as_str(), r["preserveNumbers"].as_bool(), r["simulateBlack"].as_bool()), (Some(device.as_str()), Some(true), Some(true)));
|
||||
assert_eq!(vectorcraft_render::proof::view(), Default::default(), "reading changes nothing");
|
||||
assert!(!crate::waits_for_tool_edit("view.proofSetup.read"), "reading does not finish a tool's edit");
|
||||
let rev = s.doc().unwrap().revision;
|
||||
let r = s.execute("view.proofSetup.load", &json!({"path": path})).unwrap();
|
||||
assert_eq!((r["proofColors"].as_bool(), r["path"].as_str()), (Some(true), Some(path.as_str())));
|
||||
let v = vectorcraft_render::proof::view();
|
||||
assert!(v.proof_colors);
|
||||
let want = ProofSetup {
|
||||
target: ProofTarget::Cmyk(cms::GENERIC_CMYK.into()),
|
||||
intent: Intent::Perceptual,
|
||||
simulate_paper: false,
|
||||
preserve_numbers: true,
|
||||
simulate_black: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(v.setup, want);
|
||||
assert!(s.doc().unwrap().revision > rev, "the canvas redraws");
|
||||
// Saved from the current setup, the file holds that setup: the round trip keeps every field.
|
||||
let again = dir.join("again.vcproof").to_string_lossy().to_string();
|
||||
s.execute("view.proofSetup.save", &json!({"path": again, "simulatePaper": true})).unwrap();
|
||||
s.execute("view.proofSetup", &json!({"target": "workingCmyk"})).unwrap();
|
||||
s.execute("view.proofSetup.load", &json!({"path": again})).unwrap();
|
||||
assert_eq!(vectorcraft_render::proof::view().setup, ProofSetup { simulate_paper: true, ..want });
|
||||
}
|
||||
|
||||
/// Saving refuses a target that is not a device, bad params, a bad name and a file larger than
|
||||
/// loading reads; loading refuses a file
|
||||
/// that is too large, not a proof setup, newer, or whose device is a profile that is not loaded,
|
||||
/// and the proof view stays as it was.
|
||||
#[test]
|
||||
fn proof_setup_files_refuse_what_they_cannot_use() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _v = DefaultView::new();
|
||||
let dir = vectorcraft_testkit::TempDir::new("proof-setup-refused");
|
||||
let file = |n: &str| dir.join(n).to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
let path = file("a.vcproof");
|
||||
refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "protanopia"}), "`protanopia` is not a device to simulate");
|
||||
refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "rgb:Nope"}), "unknown RGB profile `Nope`");
|
||||
refused(&mut s, "view.proofSetup.save", json!({"path": path, "simulateBlack": "yes"}), "`simulateBlack` must be true or false");
|
||||
refused(&mut s, "view.proofSetup.save", json!({}), "missing `path` or `name`");
|
||||
refused(&mut s, "view.proofSetup.save", json!({"path": path, "name": "x"}), "not both");
|
||||
refused(&mut s, "view.proofSetup.save", json!({"path": " "}), "`path` is empty");
|
||||
refused(&mut s, "view.proofSetup.save", json!({"name": "x"}), "need the preferences folder");
|
||||
assert!(!std::path::Path::new(&path).exists(), "nothing is written");
|
||||
s.attach_proof_setups(dir.join("Proof Setups"));
|
||||
for bad_name in ["", " ", "../up", "a/b", "a\\b", ".hidden", "c:d"] {
|
||||
refused(&mut s, "view.proofSetup.save", json!({"name": bad_name}), "`name`");
|
||||
}
|
||||
refused(&mut s, "view.proofSetup.save", json!({"name": "x".repeat(101)}), "longer than 100 characters");
|
||||
// A device whose name makes the file larger than load reads is refused, and nothing is written.
|
||||
let long = "Long Profile Name ".repeat(4000);
|
||||
cms::register_icc(&cms::icc_bytes(cms::DISPLAY_P3).unwrap(), Some(long.clone())).unwrap();
|
||||
let refusal = s.execute("view.proofSetup.save", &json!({"path": path, "target": format!("rgb:{long}")}));
|
||||
cms::unregister_icc(&long);
|
||||
assert!(refusal.unwrap_err().to_string().contains("larger than 65536 bytes"), "a setup load can't read is refused");
|
||||
assert!(!std::path::Path::new(&path).exists(), "nothing is written");
|
||||
let before = vectorcraft_render::proof::view();
|
||||
let write = |n: &str, text: &str| {
|
||||
let p = file(n);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p
|
||||
};
|
||||
let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#;
|
||||
let cases = [
|
||||
(write("big.vcproof", &format!("{ok}{}", " ".repeat(64 << 10))), "larger than 65536 bytes"),
|
||||
(write("junk.vcproof", "not json"), "not a proof setup file"),
|
||||
(write("other.vcproof", r#"{"format": "other", "version": 1}"#), "not a VectorCraft proof setup file"),
|
||||
(write("newer.vcproof", &ok.replace("\"version\": 1", "\"version\": 2")), "made by a newer VectorCraft"),
|
||||
(write("missing.vcproof", &ok.replace("workingCmyk", "cmyk:Not Loaded")), "the CMYK profile `Not Loaded`, which is not loaded"),
|
||||
(write("blind.vcproof", &ok.replace("workingCmyk", "deuteranopia")), "not a device to simulate"),
|
||||
(write("intent.vcproof", &ok.replace("relative", "vivid")), "unknown intent `vivid`"),
|
||||
(write("flag.vcproof", &ok.replace("}", r#", "simulatePaper": 1}"#)), "`simulatePaper` must be true or false"),
|
||||
];
|
||||
for (p, msg) in cases {
|
||||
for cmd in ["view.proofSetup.load", "view.proofSetup.read"] {
|
||||
refused(&mut s, cmd, json!({"path": p}), msg);
|
||||
}
|
||||
}
|
||||
refused(&mut s, "view.proofSetup.load", json!({"path": file("gone.vcproof")}), "gone.vcproof");
|
||||
assert_eq!(vectorcraft_render::proof::view(), before, "the proof view is unchanged");
|
||||
// A file of the limit's size is read.
|
||||
let padded = format!("{ok}{}", " ".repeat((64 << 10) - ok.len()));
|
||||
s.execute("view.proofSetup.load", &json!({"path": write("limit.vcproof", &padded)})).unwrap();
|
||||
}
|
||||
|
||||
/// Setups saved by name go in the Proof Setups folder, made on the first save, and are listed by
|
||||
/// name; other files there are left out, and a run without the folder lists none.
|
||||
#[test]
|
||||
fn proof_setups_saved_by_name_are_listed() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _v = DefaultView::new();
|
||||
let mut s = session();
|
||||
assert_eq!(s.execute("view.proofSetup.list", &json!({})).unwrap(), json!({"folder": null, "setups": [], "truncated": false}));
|
||||
let dir = vectorcraft_testkit::TempDir::new("proof-setup-list");
|
||||
let folder = dir.join("Proof Setups");
|
||||
s.attach_proof_setups(folder.clone());
|
||||
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
|
||||
assert_eq!(r["setups"], json!([]), "no folder yet: none saved");
|
||||
let r = s.execute("view.proofSetup.save", &json!({"name": " Coated Press ", "target": format!("rgb:{}", cms::DISPLAY_P3)})).unwrap();
|
||||
let saved = folder.join("Coated Press.vcproof");
|
||||
assert_eq!(r["path"].as_str(), Some(saved.to_string_lossy().as_ref()));
|
||||
s.execute("view.proofSetup.save", &json!({"name": "Bright"})).unwrap();
|
||||
std::fs::write(folder.join("notes.txt"), "x").unwrap();
|
||||
std::fs::create_dir(folder.join("Sub.vcproof")).unwrap();
|
||||
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
|
||||
let names: Vec<&str> = r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str()).collect();
|
||||
assert_eq!(names, ["Bright", "Coated Press"]);
|
||||
assert_eq!(r["truncated"], false);
|
||||
s.execute("view.proofSetup.load", &json!({"name": "Coated Press"})).unwrap();
|
||||
assert_eq!(vectorcraft_render::proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()));
|
||||
for i in 0..101 {
|
||||
std::fs::write(folder.join(format!("z{i:03}.vcproof")), "x").unwrap();
|
||||
}
|
||||
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
|
||||
assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (100, Some(true)));
|
||||
assert_eq!((r["setups"][0]["name"].as_str(), r["setups"][99]["name"].as_str()), (Some("Bright"), Some("z097")), "the first 100 by name");
|
||||
}
|
||||
|
||||
/// Other files in the Proof Setups folder, however many, do not keep its setups from the listing.
|
||||
#[test]
|
||||
fn proof_setups_are_listed_among_many_other_files() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _v = DefaultView::new();
|
||||
let mut s = session();
|
||||
let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-crowded");
|
||||
let folder = dir.join("Proof Setups");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
for i in 0..5000 {
|
||||
std::fs::write(folder.join(format!("a{i:04}.txt")), "").unwrap();
|
||||
}
|
||||
s.attach_proof_setups(folder.clone());
|
||||
s.execute("view.proofSetup.save", &json!({"name": "Press"})).unwrap();
|
||||
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
|
||||
assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (1, Some(false)));
|
||||
assert_eq!(r["setups"][0]["name"], "Press");
|
||||
}
|
||||
|
||||
/// The listing names only files that `name` loads (`<name>.vcproof`, a name `save` can give), in
|
||||
/// the order of those names, and the limit keeps the first by name; a folder that can't be read is
|
||||
/// an error, not an empty listing.
|
||||
#[test]
|
||||
fn proof_setups_are_listed_by_names_that_load_them() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _v = DefaultView::new();
|
||||
let mut s = session();
|
||||
let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-names");
|
||||
let folder = dir.join("Proof Setups");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
s.attach_proof_setups(folder.clone());
|
||||
let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#;
|
||||
for file in ["Press.vcproof", "Press Matte.vcproof", "Loud.VCPROOF", " Lead.vcproof"] {
|
||||
std::fs::write(folder.join(file), ok).unwrap();
|
||||
}
|
||||
let names = |r: &Value| r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str().map(str::to_string)).collect::<Vec<_>>();
|
||||
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
|
||||
assert_eq!((names(&r), r["truncated"].as_bool()), (vec!["Press".to_string(), "Press Matte".to_string()], Some(false)));
|
||||
for name in names(&r) {
|
||||
s.execute("view.proofSetup.read", &json!({ "name": name })).unwrap();
|
||||
}
|
||||
// `Press` and `Press Matte` compete for the last place: the first by name keeps it.
|
||||
for i in 0..99 {
|
||||
std::fs::write(folder.join(format!("A{i:02}.vcproof")), "x").unwrap();
|
||||
}
|
||||
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
|
||||
let listed = names(&r);
|
||||
assert_eq!((listed.len(), listed.last().map(String::as_str), r["truncated"].as_bool()), (100, Some("Press"), Some(true)));
|
||||
// A folder that is not one can't be listed.
|
||||
let file = dir.join("not a folder");
|
||||
std::fs::write(&file, "x").unwrap();
|
||||
s.attach_proof_setups(file);
|
||||
refused(&mut s, "view.proofSetup.list", json!({}), "not a folder");
|
||||
}
|
||||
|
||||
/// A file name that is not valid Unicode is left out of the listing, which then says it is
|
||||
/// incomplete: a path made from a lossy copy of the name would name another file.
|
||||
#[test]
|
||||
fn proof_setup_names_that_are_not_unicode_are_left_out() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _v = DefaultView::new();
|
||||
let mut s = session();
|
||||
let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-bytes");
|
||||
let folder = dir.join("Proof Setups");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
#[cfg(unix)]
|
||||
let odd = {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
std::ffi::OsString::from_vec(b"Odd\xff.vcproof".to_vec())
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let odd = {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
std::ffi::OsString::from_wide(&"Odd?.vcproof".encode_utf16().map(|u| if u == u16::from(b'?') { 0xD800 } else { u }).collect::<Vec<_>>())
|
||||
};
|
||||
// A file system that refuses such a name has nothing to leave out.
|
||||
if std::fs::write(folder.join(odd), "x").is_err() {
|
||||
return;
|
||||
}
|
||||
std::fs::write(folder.join("Press.vcproof"), "x").unwrap();
|
||||
s.attach_proof_setups(folder);
|
||||
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
(r["setups"].as_array().map(Vec::len), r["setups"][0]["name"].as_str(), r["truncated"].as_bool()),
|
||||
(Some(1), Some("Press"), Some(true))
|
||||
);
|
||||
}
|
||||
|
||||
/// Whether the content has a DeviceCMYK fill/stroke operator (`c m y k k` / `K`).
|
||||
fn has_cmyk_op(pdf: &str) -> bool {
|
||||
let toks: Vec<&str> = pdf.split_ascii_whitespace().collect();
|
||||
|
||||
@@ -585,6 +585,106 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rectangle Angle and Ellipse Angle: `rectangleAngle` and `ellipseAngle` turn each selected live
|
||||
/// rectangle or ellipse about its own center, keeping its size, corners and pie, as one undo step.
|
||||
/// The angle it already has records no step, each key leaves the other kind as it is, and a value
|
||||
/// that is not a number is an error.
|
||||
#[test]
|
||||
fn a_rectangle_and_an_ellipse_take_their_angle() {
|
||||
let (mut s, rect) = session();
|
||||
run(&mut s, json!({"radius": 8}));
|
||||
let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 120, "height": 80})).unwrap()["id"].as_u64().unwrap());
|
||||
run(&mut s, json!({"pieStart": 30, "pieEnd": 120}));
|
||||
let live = |s: &Session, id: NodeId| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
(n.live_shape().unwrap().clone(), n.geometric_bounds().unwrap())
|
||||
};
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
|
||||
let angle = |s: &Session, id: NodeId| live(s, id).0.shape_angle().unwrap();
|
||||
// The ellipse's center: the middle of its untransformed box, wherever its pie leaves the path.
|
||||
let ellipse_center = |s: &Session| match live(s, ellipse).0 {
|
||||
LiveShape::Ellipse { w, h, xf, .. } => xf * vectorcraft_geom::Point::new(w / 2.0, h / 2.0),
|
||||
l => panic!("{l:?}"),
|
||||
};
|
||||
let center = ellipse_center(&s);
|
||||
|
||||
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
|
||||
let n = steps(&s);
|
||||
run(&mut s, json!({"rectangleAngle": 90}));
|
||||
let (l, b) = live(&s, rect);
|
||||
assert!(close(angle(&s, rect), 90.0), "{l:?}");
|
||||
// 100 × 60 at (10, 10) turned about (60, 40): 60 wide, 100 tall, same center.
|
||||
assert!(close(b.width(), 60.0) && close(b.height(), 100.0) && close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}");
|
||||
let LiveShape::Rectangle { w, h, radii, .. } = &l else { panic!("{l:?}") };
|
||||
assert!(close(*w, 100.0) && close(*h, 60.0) && *radii == [8.0; 4], "{w} {h} {radii:?}");
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
for same in [json!({"rectangleAngle": 90}), json!({"rectangleAngle": 450}), json!({"rectangleAngle": -270}), json!({"ellipseAngle": 10})] {
|
||||
run(&mut s, same.clone());
|
||||
assert_eq!(steps(&s), n + 1, "{same} records no undo step");
|
||||
}
|
||||
// A turn the field gives back rounded is the angle the shape has: typing it again records no step.
|
||||
run(&mut s, json!({"rectangleAngle": 33.3}));
|
||||
let now = angle(&s, rect);
|
||||
run(&mut s, json!({"rectangleAngle": now}));
|
||||
run(&mut s, json!({"rectangleAngle": 33.3}));
|
||||
assert_eq!(steps(&s), n + 2);
|
||||
for bad in [json!({"rectangleAngle": "left"}), json!({"ellipseAngle": "up"}), json!({"rectangleAngle": true})] {
|
||||
assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}");
|
||||
assert_eq!(steps(&s), n + 2, "{bad} changes nothing");
|
||||
}
|
||||
|
||||
// The ellipse turns about its center and keeps its pie.
|
||||
s.execute("select.set", &json!({"ids": [ellipse.0]})).unwrap();
|
||||
run(&mut s, json!({"ellipseAngle": 90}));
|
||||
let (l, b) = live(&s, ellipse);
|
||||
assert!(close(angle(&s, ellipse), 90.0), "{l:?}");
|
||||
let LiveShape::Ellipse { pie, .. } = &l else { panic!("{l:?}") };
|
||||
assert_eq!(*pie, (30.0, 120.0));
|
||||
let now = ellipse_center(&s);
|
||||
assert!(close(now.x, center.x) && close(now.y, center.y), "{center:?} → {now:?}");
|
||||
assert!(b.width() < b.height(), "120 × 80 turned a quarter turn: {b:?}");
|
||||
|
||||
// Both selected: each key turns its own kind only, each about its own center.
|
||||
s.execute("select.set", &json!({"ids": [rect.0, ellipse.0]})).unwrap();
|
||||
run(&mut s, json!({"rectangleAngle": 45}));
|
||||
assert!(close(angle(&s, rect), 45.0) && close(angle(&s, ellipse), 90.0));
|
||||
let b = live(&s, rect).1;
|
||||
assert!(close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(close(angle(&s, rect), 33.3));
|
||||
|
||||
// A reflected rectangle takes the angle too, about its center.
|
||||
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
|
||||
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
|
||||
let before = live(&s, rect).1.center();
|
||||
run(&mut s, json!({"rectangleAngle": 20}));
|
||||
let after = live(&s, rect).1.center();
|
||||
assert!(close(angle(&s, rect), 20.0) && close(before.x, after.x) && close(before.y, after.y), "{before:?} → {after:?}");
|
||||
}
|
||||
|
||||
/// A shape named in `ids` that a turn would take past the coordinate limit (±4,000,000 pt) is an
|
||||
/// error that changes nothing, whether or not it is selected.
|
||||
#[test]
|
||||
fn a_turn_past_the_coordinate_limit_is_an_error() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let mut add = |cmd: &str, p: Value| s.execute(cmd, &p).unwrap()["id"].as_u64().unwrap();
|
||||
// Each reaches within 10 pt of the limit and past it when turned.
|
||||
let rect = add("shape.rectangle", json!({"x": 3_999_890, "y": 100, "width": 100, "height": 100}));
|
||||
let ellipse = add("shape.ellipse", json!({"x": 3_999_950, "y": 100, "width": 40, "height": 100}));
|
||||
let polygon = add("shape.polygon", json!({"cx": 3_999_955, "cy": 200, "radius": 50, "sides": 6}));
|
||||
for (id, key, angle) in [(rect, "rectangleAngle", 45), (ellipse, "ellipseAngle", 90), (polygon, "polygonAngle", 90)] {
|
||||
for selected in [false, true] {
|
||||
s.execute("select.set", &json!({"ids": if selected { vec![id] } else { vec![] }})).unwrap();
|
||||
let (doc, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("object.setLiveShape", &json!({"ids": [id], key: angle})).unwrap_err();
|
||||
assert!(e.to_string().contains("out of range"), "{key}, selected {selected}: {e}");
|
||||
assert!(*s.doc().unwrap().doc == *doc && s.doc().unwrap().history.undo.len() == steps, "{key}, selected {selected}: changed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees
|
||||
/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the
|
||||
/// length applies before the angle, every selected line takes them in one undo step, and a value
|
||||
|
||||
@@ -212,6 +212,153 @@ fn cancel_new_pattern_removes_it() {
|
||||
assert_eq!(doc(&s).layers.len(), 1);
|
||||
}
|
||||
|
||||
/// A 30×40 blue rectangle at (100, 100) with no stroke, selected.
|
||||
fn blue_rect(s: &mut Session) -> NodeId {
|
||||
let b = rect(s, 100.0, 100.0, 30.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#0000ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [b.0], "none": true})).unwrap();
|
||||
sel(s, &[b]);
|
||||
b
|
||||
}
|
||||
|
||||
/// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo
|
||||
/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the
|
||||
/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles.
|
||||
#[test]
|
||||
fn replace_art_gives_a_pattern_new_tile_art() {
|
||||
let mut s = session();
|
||||
let red = make_dots(&mut s);
|
||||
let filled = rect(&mut s, 200.0, 200.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Dots"})).unwrap();
|
||||
s.execute("pattern.options", &json!({"name": "Dots", "tileType": "hexByRow"})).unwrap();
|
||||
let blue = blue_rect(&mut s);
|
||||
let old = doc(&s).pattern("Dots").unwrap().clone();
|
||||
let place = |s: &Session| doc(s).swatches_iter().position(|w| w.name == "Dots");
|
||||
let (at, swatches, steps) = (place(&s), doc(&s).swatches_iter().count(), s.doc().unwrap().history.undo.len());
|
||||
let v = s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
|
||||
assert_eq!(v["name"], "Dots");
|
||||
let d = doc(&s);
|
||||
let def = d.pattern("Dots").unwrap();
|
||||
assert_eq!(def.art.len(), 1);
|
||||
assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle");
|
||||
assert_eq!(def.art[0].appearance, node(&s, blue).appearance);
|
||||
assert_ne!(def.art[0].id, blue, "a copy with an id of its own");
|
||||
assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay");
|
||||
assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch");
|
||||
assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern");
|
||||
assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays");
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![blue], "the art stays selected");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Replace Pattern Art")));
|
||||
let new = def.art.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s).pattern("Dots").unwrap(), &old, "Undo gives the old tile art back");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s).pattern("Dots").unwrap().art, new, "Redo gives the new tile art");
|
||||
}
|
||||
|
||||
/// With Size Tile to Art on, the tile fits the new art (and its spacing); `ids` names the art.
|
||||
#[test]
|
||||
fn replace_art_fits_the_tile_when_size_tile_to_art_is_on() {
|
||||
let mut s = session();
|
||||
make_dots(&mut s);
|
||||
s.execute("pattern.options", &json!({"name": "Dots", "sizeTileToArt": true, "hSpacing": 4, "vSpacing": 6})).unwrap();
|
||||
let blue = blue_rect(&mut s);
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [blue.0]})).unwrap();
|
||||
assert_eq!(doc(&s).pattern("Dots").unwrap().tile, Rect::new(98.0, 97.0, 132.0, 143.0));
|
||||
}
|
||||
|
||||
/// Art that matches the tile art already, its own ids aside, records no undo step.
|
||||
#[test]
|
||||
fn replace_art_that_matches_the_tile_art_records_nothing() {
|
||||
let mut s = session();
|
||||
make_dots(&mut s);
|
||||
blue_rect(&mut s);
|
||||
s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
|
||||
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
|
||||
s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
assert_eq!(doc(&s), &before);
|
||||
}
|
||||
|
||||
/// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art,
|
||||
/// while a pattern is edited, and for art painted with the pattern itself, directly, through
|
||||
/// another pattern, through a symbol, through the paints a graph stores, through a graph design a
|
||||
/// graph draws its columns with, through the art of a brush on a stroke and through the symbol of an
|
||||
/// inline graphic in type.
|
||||
#[test]
|
||||
fn replace_art_is_refused_without_changing_anything() {
|
||||
let mut s = session();
|
||||
make_dots(&mut s);
|
||||
// "Holds dots": a pattern whose tile is painted with Dots.
|
||||
let other = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [other.0], "swatch": "Dots"})).unwrap();
|
||||
sel(&mut s, &[other]);
|
||||
s.execute("object.pattern.make", &json!({"name": "Holds dots", "edit": false})).unwrap();
|
||||
let via = rect(&mut s, 150.0, 150.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [via.0], "swatch": "Holds dots"})).unwrap();
|
||||
let stroked = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Dots"})).unwrap();
|
||||
sel(&mut s, &[stroked]);
|
||||
let instance = id_of(&s.execute("symbol.new", &json!({"name": "Dotted"})).unwrap());
|
||||
let graph = graph_painted_with(&mut s, "Dots");
|
||||
// A graph whose stored columns name design "Dotted columns", drawn with Dots, before it is drawn
|
||||
// again.
|
||||
let design = rect(&mut s, 300.0, 300.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [design.0], "swatch": "Dots"})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "Dotted columns", "ids": [design.0]})).unwrap();
|
||||
let v = s.execute("graph.create", &json!({"type": "column", "x": 300, "y": 200, "width": 60, "height": 40, "csv": ",2024\nQ1,3"}));
|
||||
let designed = id_of(&v.unwrap());
|
||||
let mut extras = doc_mut(&mut s).node_mut(designed).unwrap().extras_mut();
|
||||
extras.graph.as_mut().unwrap().series_columns =
|
||||
vec![Some(vectorcraft_doc::ColumnDesign { design: "Dotted columns".into(), ..Default::default() })];
|
||||
drop(extras);
|
||||
// A path stroked with an art brush whose art is filled with Dots.
|
||||
let brush_art = rect(&mut s, 300.0, 350.0, 20.0, 5.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [brush_art.0], "swatch": "Dots"})).unwrap();
|
||||
s.execute("brush.new", &json!({"type": "art", "name": "Dotted brush", "ids": [brush_art.0]})).unwrap();
|
||||
let brushed = rect(&mut s, 300.0, 380.0, 40.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [brushed.0], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [brushed.0], "color": "#000000"})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "Dotted brush", "ids": [brushed.0]})).unwrap();
|
||||
// Type that shows symbol "Dotted" as an inline graphic.
|
||||
let typed = id_of(&s.execute("text.create", &json!({"x": 20, "y": 420, "text": "Hi"})).unwrap());
|
||||
s.execute("text.insertInline", &json!({"id": typed.0, "at": 0, "symbol": "Dotted"})).unwrap();
|
||||
let plain = blue_rect(&mut s);
|
||||
let unchanged = |s: &Session, before: &vectorcraft_doc::Document, steps: usize, case: &str| {
|
||||
assert_eq!(doc(s), before, "{case}: the document stays");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step");
|
||||
};
|
||||
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
|
||||
for (case, p, why) in [
|
||||
("no name", json!({}), "missing name".to_string()),
|
||||
("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`".into()),
|
||||
("no art", json!({"name": "Dots", "ids": [9999]}), "select the art for the pattern tile".into()),
|
||||
("painted with it", json!({"name": "Dots", "ids": [other.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
("through a pattern", json!({"name": "Dots", "ids": [via.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
("through a symbol", json!({"name": "Dots", "ids": [instance.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
("through a graph's paints", json!({"name": "Dots", "ids": [graph.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
("through a graph design", json!({"name": "Dots", "ids": [designed.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
("through a brush", json!({"name": "Dots", "ids": [brushed.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
("through an inline graphic", json!({"name": "Dots", "ids": [typed.0]}), "art painted with `Dots` can't be its tile".into()),
|
||||
] {
|
||||
let err = s.execute("object.pattern.replaceArt", &p).unwrap_err();
|
||||
assert!(err.to_string().contains(&why), "{case}: {err}");
|
||||
unchanged(&s, &before, steps, case);
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
|
||||
let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap_err();
|
||||
assert!(err.to_string().contains("select the art for the pattern tile"), "nothing selected: {err}");
|
||||
unchanged(&s, &before, steps, "nothing selected");
|
||||
s.execute("object.pattern.edit", &json!({"name": "Holds dots"})).unwrap();
|
||||
let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
|
||||
let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [plain.0]})).unwrap_err();
|
||||
assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}");
|
||||
unchanged(&s, &before, steps, "while editing");
|
||||
}
|
||||
|
||||
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc)
|
||||
}
|
||||
|
||||
@@ -836,6 +836,21 @@ fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_p
|
||||
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link");
|
||||
}
|
||||
|
||||
/// "keep" in `groupColors` leaves the group's swatch at its place as it is, without Global Adjust,
|
||||
/// and past the group's swatches it adds none.
|
||||
#[test]
|
||||
fn keep_in_group_colors_leaves_that_swatch_as_it_is() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#2878f0", "#ff0000"]}));
|
||||
let p = json!({"map": [], "group": "Brand", "groupColors": ["keep", "#00ff00", "keep"], "globalAdjust": {"brightness": -50}});
|
||||
run(&mut s, "recolor.apply", p);
|
||||
let g = &s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches;
|
||||
let g: Vec<String> = g.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
|
||||
assert_eq!(g.len(), 2, "{g:?}");
|
||||
assert_eq!(g[0], "#2878f0", "the kept swatch takes no Global Adjust");
|
||||
assert_ne!(g[1], "#00ff00", "the other new color takes it");
|
||||
}
|
||||
|
||||
/// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply`
|
||||
/// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color
|
||||
/// swatches in order.
|
||||
|
||||
@@ -12,12 +12,14 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real
|
||||
/// path: kept grants hold real paths, and a path named through a link (macOS's `/var` is
|
||||
/// `/private/var`) is refused by its names alone.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
base
|
||||
std::fs::canonicalize(&base).unwrap()
|
||||
}
|
||||
|
||||
fn write(path: &Path, bytes: &[u8]) {
|
||||
|
||||
@@ -125,6 +125,69 @@ fn add_used_colors_skips_colours_that_have_swatches() {
|
||||
assert!(doc(&s).swatch("R=171 G=205 B=239").unwrap().global);
|
||||
}
|
||||
|
||||
/// A run that finds no new color, over all the art or the selection, records no undo step.
|
||||
#[test]
|
||||
fn add_used_colors_with_no_new_color_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
let a = rect_filled(&mut s, json!({"color": "#123456"}));
|
||||
run(&mut s, "swatch.addUsedColors", json!({}));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let before = doc(&s).clone();
|
||||
let undo = undo_len(&s);
|
||||
for p in [json!({}), json!({"selection": true, "global": true})] {
|
||||
assert_eq!(run(&mut s, "swatch.addUsedColors", p), json!({"added": [], "linked": 0}));
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
assert_eq!(*doc(&s), before);
|
||||
}
|
||||
// An empty selection is still an error, with nothing changed.
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
let undo = undo_len(&s);
|
||||
assert!(s.execute("swatch.addUsedColors", &json!({"selection": true})).is_err());
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// A run that finds no new color, while the Type tool is typing, still ends the typing session: the
|
||||
/// typing is its own undo step.
|
||||
#[test]
|
||||
fn add_used_colors_with_no_new_color_ends_the_typing() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 10, "text": "Hello"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "swatch.addUsedColors", json!({}));
|
||||
s.select_tool("type", v).unwrap();
|
||||
let b = doc(&s).bounds_of(&[t], false).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap();
|
||||
}
|
||||
s.tool_text("!", v).unwrap();
|
||||
assert!(crate::cmd::typing_in_progress(&s));
|
||||
let steps = undo_len(&s);
|
||||
assert_eq!(run(&mut s, "swatch.addUsedColors", json!({})), json!({"added": [], "linked": 0}));
|
||||
assert!(!crate::cmd::typing_in_progress(&s));
|
||||
let labels: Vec<String> = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect();
|
||||
assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing")));
|
||||
}
|
||||
|
||||
/// Add Selected Colors while Global Edit is on links only the selected art: a member of the same
|
||||
/// shape with another color keeps its color and stays unlinked, and Global Edit stays on.
|
||||
#[test]
|
||||
fn add_selected_colors_in_global_edit_keeps_the_other_members_colors() {
|
||||
let mut s = session();
|
||||
let a = rect_filled(&mut s, json!({"color": "#123456"}));
|
||||
let b = rect_filled(&mut s, json!({"color": "#654321"}));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let r = run(&mut s, "select.globalEdit", json!({}));
|
||||
assert_eq!((r["active"].clone(), r["ids"].clone()), (json!(true), json!([a.0, b.0])), "the other rectangle is a member");
|
||||
let other = fill(&s, b);
|
||||
let undo = undo_len(&s);
|
||||
run(&mut s, "swatch.addUsedColors", json!({"selection": true, "global": true}));
|
||||
assert!(matches!(fill(&s, a), Paint::Solid { swatch: Some(_), .. }), "{:?}", fill(&s, a));
|
||||
assert_eq!(fill(&s, b), other, "the unselected member keeps its color");
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert!(s.doc().unwrap().global_edit.is_some(), "Global Edit stays on");
|
||||
}
|
||||
|
||||
/// Give `id` the fill `p` exactly as written (a command would round or convert some colors).
|
||||
fn set_fill(s: &mut Session, id: NodeId, p: Paint) {
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.set_fill(p);
|
||||
|
||||
@@ -160,6 +160,37 @@ fn save_and_load_round_trip_keeps_cmyk_spot_and_groups() {
|
||||
assert!(s.execute("swatch.library.save", &json!({"user": true})).is_err(), "no user folder in a headless session");
|
||||
}
|
||||
|
||||
/// A library color group that holds a gradient comes into the document whole, the gradient at its
|
||||
/// place in the group, as a `.ai` library's pattern swatch comes in its color group.
|
||||
#[test]
|
||||
fn add_brings_a_library_color_group_holding_a_gradient_whole() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#123456", "#abcdef"]}));
|
||||
let r = run(&mut s, "swatch.library.save", json!({"names": ["Brand", "Sunset"], "name": "Mixed"}));
|
||||
// Move the Sunset gradient into the library's Brand group, as a hand-edited file can.
|
||||
let mut lib: Value = serde_json::from_str(r["data"].as_str().unwrap()).unwrap();
|
||||
let swatches = lib["swatches"].as_array_mut().unwrap();
|
||||
let at = swatches.iter().position(|w| w["name"] == "Sunset").unwrap();
|
||||
let sunset = swatches.remove(at);
|
||||
lib["groups"][0]["swatches"].as_array_mut().unwrap().insert(1, sunset);
|
||||
let r = run(&mut s, "swatch.library.load", json!({"data": lib.to_string(), "name": "mixed.vcswatches"}));
|
||||
let id = r["library"].as_str().unwrap().to_string();
|
||||
let (_, loaded) = cmd::swatchlib::library(&s, &id).unwrap();
|
||||
assert!(matches!(loaded.groups[0].swatches[1].paint, Paint::Gradient(_)), "the reader keeps the gradient in the group");
|
||||
run(&mut s, "swatch.delete", json!({"names": ["Brand", "Sunset"]}));
|
||||
for p in [json!({"library": id}), json!({"library": id, "names": ["Brand"]})] {
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, "swatch.library.add", p.clone());
|
||||
assert!(r["added"].as_array().unwrap().iter().any(|n| n == "Sunset"), "{p}: {r}");
|
||||
let brand = doc(&s).swatch_groups.iter().find(|g| g.name == "Brand").map(|g| g.swatches.clone()).unwrap_or_default();
|
||||
let kinds: Vec<(&str, bool)> = brand.iter().map(|w| (w.name.as_str(), matches!(w.paint, Paint::Gradient(_)))).collect();
|
||||
assert_eq!(kinds.len(), 3, "{p}: {kinds:?}");
|
||||
assert_eq!(kinds[1], ("Sunset", true), "{p}: the gradient keeps its place in the group");
|
||||
assert_eq!(undo_len(&s), undo + 1, "{p}: one undo step");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The swatch library commands, and the graphic style library save and load that share their file
|
||||
/// handling, refuse a parameter of the wrong form, such as `user: "true"` or `names: "Grays"`, with
|
||||
/// an error that names it; the document keeps its swatches and no undo step is recorded. A null
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
//! `shape.threePointArc`: an open circular arc between two ends, through a third point or
|
||||
//! leaving an end toward it, and the Three-Point Arc tool's clicks that run it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const C: &str = "shape.threePointArc";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn object_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// The largest distance of `points` from the path of `id`.
|
||||
fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 {
|
||||
let n = node(s, id);
|
||||
let path = n.path_data().unwrap();
|
||||
points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// The arc from (0, 0) to (80, 0) through (40, -40) is the upper half of the circle about
|
||||
/// (40, 0) with radius 40: an open path from one end to the other, through the third point, with
|
||||
/// no fill and a stroke, selected, and one undo step.
|
||||
#[test]
|
||||
fn the_arc_through_a_third_point_is_an_open_path_and_one_undo_step() {
|
||||
let mut s = session();
|
||||
let undo = undo_len(&s);
|
||||
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "through": [40, -40]})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}");
|
||||
// From (0, 0) over the top to (80, 0): clockwise on the page.
|
||||
assert!((out["sweep"].as_f64().unwrap() - 180.0).abs() < 1e-9, "{out}");
|
||||
let id = id_of(&out);
|
||||
let n = node(&s, id);
|
||||
let NodeKind::Path { path, live: None, .. } = &n.kind else { panic!("not a plain path: {:?}", n.kind) };
|
||||
let sp = &path.subpaths[0];
|
||||
assert!(!sp.closed && path.subpaths.len() == 1);
|
||||
assert_eq!((sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)), (Some(Point::ORIGIN), Some(Point::new(80.0, 0.0))));
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(40.0, -40.0)]) < 1e-9);
|
||||
assert!(n.appearance.fill_paint().is_none(), "no fill");
|
||||
assert!(!n.appearance.stroke_paint().is_none(), "a stroke");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [id]);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
// A third point between the quarter turns is an anchor too, so the path meets it exactly.
|
||||
let via = Point::new(1000.0 * 20f64.to_radians().cos(), 1000.0 * 20f64.to_radians().sin());
|
||||
let out = s.execute(C, &json!({"start": [1000, 0], "end": [0, 1000], "through": [via.x, via.y]})).unwrap();
|
||||
let id = id_of(&out);
|
||||
assert!(node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().any(|a| a.p == via));
|
||||
assert!(farthest_from_path(&s, id, &[via]) < 1e-9);
|
||||
}
|
||||
|
||||
/// With `toward`, the arc leaves `start` heading at the point (its first handle points there),
|
||||
/// or with `at: "end"` arrives at `end` along the line from the point to `end` (run backward, the
|
||||
/// arc leaves `end` heading at the point).
|
||||
#[test]
|
||||
fn the_arc_toward_a_point_has_that_tangent_at_its_end() {
|
||||
let mut s = session();
|
||||
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [30, -30]})).unwrap();
|
||||
let n = node(&s, id_of(&out));
|
||||
let first = n.path_data().unwrap().subpaths[0].anchors[0];
|
||||
let d = (first.h_out - first.p).normalize();
|
||||
assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, -1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}");
|
||||
// A quarter turn's tangent: the center is at (40, 40) and the radius √3200.
|
||||
assert!((out["radius"].as_f64().unwrap() - 3200f64.sqrt()).abs() < 1e-9, "{out}");
|
||||
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [50, -30], "at": "end"})).unwrap();
|
||||
let n = node(&s, id_of(&out));
|
||||
let last = *n.path_data().unwrap().subpaths[0].anchors.last().unwrap();
|
||||
let d = (last.p - last.h_in).normalize();
|
||||
assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, 1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}");
|
||||
// The direction from the start and from the end mirror each other.
|
||||
assert!((out["cx"].as_f64().unwrap() - 40.0).abs() < 1e-9 && (out["cy"].as_f64().unwrap() - 40.0).abs() < 1e-9, "{out}");
|
||||
}
|
||||
|
||||
/// Points that are the same, a third point on the line through the ends, and an arc reaching past
|
||||
/// the canvas are refused with a message; nothing is drawn and no undo step is added.
|
||||
#[test]
|
||||
fn points_with_no_arc_are_refused() {
|
||||
let mut s = session();
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
for p in [
|
||||
json!({"start": [0, 0], "end": [0, 0], "through": [10, 10]}),
|
||||
json!({"start": [0, 0], "end": [80, 0], "through": [40, 0]}),
|
||||
json!({"start": [0, 0], "end": [80, 0], "through": [120, 0]}),
|
||||
json!({"start": [0, 0], "end": [80, 0], "through": [80, 0]}),
|
||||
json!({"start": [0, 0], "end": [80, 0], "toward": [0, 0]}),
|
||||
json!({"start": [0, 0], "end": [80, 0], "toward": [-50, 0]}),
|
||||
json!({"start": [0, 0], "end": [80, 0], "toward": [40, 0], "at": "end"}),
|
||||
json!({"start": [0, 0], "end": [0, 0], "toward": [10, 10]}),
|
||||
] {
|
||||
let e = s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("no arc fits these points"), "{p}: {e}");
|
||||
}
|
||||
// Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt down the page, and the
|
||||
// arc goes round the far side of it.
|
||||
let far = json!({"start": [0, 0], "end": [80, 0], "through": [200, 0.001]});
|
||||
let e = s.execute(C, &far).unwrap_err().to_string();
|
||||
assert!(e.contains("result would exceed the canvas"), "{e}");
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
|
||||
}
|
||||
|
||||
/// Missing or malformed points, both or neither of `through` and `toward`, an `at` that is not
|
||||
/// "start" or "end", and an `at` with `through` are errors; nothing is drawn.
|
||||
#[test]
|
||||
fn malformed_params_are_refused() {
|
||||
let mut s = session();
|
||||
let count = object_count(&s);
|
||||
for (p, want) in [
|
||||
(json!({"end": [80, 0], "through": [40, 40]}), "`start` must be [x, y]"),
|
||||
(json!({"start": [0, 0], "end": [80], "through": [40, 40]}), "`end` must be [x, y]"),
|
||||
(json!({"start": [0, 0], "end": [80, 0], "through": [40, "a"]}), "`through` must be [x, y]"),
|
||||
(json!({"start": [0, 0], "end": [80, 0], "through": null}), "`through` must be [x, y]"),
|
||||
(json!({"start": [0, 0], "end": [80, 0], "toward": [10, 0, 0]}), "`toward` must be [x, y]"),
|
||||
(json!({"start": [0, 0], "end": [80, 0]}), "give exactly one of `through` and `toward`"),
|
||||
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "toward": [0, 40]}), "give exactly one of `through` and `toward`"),
|
||||
(json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": "middle"}), "`at` must be \"start\" or \"end\""),
|
||||
(json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": null}), "`at` must be \"start\" or \"end\""),
|
||||
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "end"}), "give `at` only with `toward`"),
|
||||
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "start"}), "give `at` only with `toward`"),
|
||||
] {
|
||||
let e = s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(object_count(&s), count);
|
||||
}
|
||||
|
||||
/// With Align New Objects to Pixel Grid on, the ends stay on the given points.
|
||||
#[test]
|
||||
fn the_arc_is_not_moved_onto_the_pixel_grid() {
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
let id = id_of(&s.execute(C, &json!({"start": [0.3, 0.2], "end": [80.6, 0.1], "through": [40.4, -39.7]})).unwrap());
|
||||
let n = node(&s, id);
|
||||
let sp = &n.path_data().unwrap().subpaths[0];
|
||||
assert_eq!(sp.anchors.first().map(|a| a.p), Some(Point::new(0.3, 0.2)));
|
||||
assert_eq!(sp.anchors.last().map(|a| a.p), Some(Point::new(80.6, 0.1)));
|
||||
assert!(!n.extras().pixel_aligned);
|
||||
}
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..ViewInfo::default() }
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, x: f64, y: f64) {
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, x, y).with_mods(Mods::default()), view()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Three-Point Arc tool, three clicks draw the arc in one undo step; `]` before the third
|
||||
/// click makes the third point give the direction instead. Escape drops the ends.
|
||||
#[test]
|
||||
fn three_clicks_with_the_tool_draw_the_arc() {
|
||||
let mut s = session();
|
||||
s.select_tool("threePointArc", view()).unwrap();
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
click(&mut s, 100.0, 200.0);
|
||||
click(&mut s, 180.0, 200.0);
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two ends draw nothing yet");
|
||||
click(&mut s, 140.0, 160.0);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(100.0, 200.0), Point::new(140.0, 160.0), Point::new(180.0, 200.0)]) < 1e-9);
|
||||
// Escape after the ends: the next clicks start afresh.
|
||||
click(&mut s, 0.0, 0.0);
|
||||
click(&mut s, 10.0, 300.0);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
click(&mut s, 100.0, 300.0);
|
||||
click(&mut s, 180.0, 300.0);
|
||||
s.tool_key(ToolKey::BracketRight, Mods::default(), view()).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
// Straight up from the first end: the upper half circle about (140, 300).
|
||||
click(&mut s, 100.0, 250.0);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9);
|
||||
}
|
||||
|
||||
/// `tool.setOption` (the Tool Options dialog's Save) sets the tool's `direction` option, and
|
||||
/// refuses a value that is not true or false, or an option the tool doesn't have.
|
||||
#[test]
|
||||
fn set_option_sets_the_direction_and_refuses_bad_values() {
|
||||
let mut s = session();
|
||||
for on in [true, false] {
|
||||
let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"direction": on}})).unwrap();
|
||||
assert_eq!(set["direction"], json!(on));
|
||||
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(on));
|
||||
}
|
||||
let cases = [
|
||||
(json!({"tool": "threePointArc", "key": "direction", "value": "yes"}), "tool `threePointArc`: `direction` must be true or false"),
|
||||
(json!({"tool": "threePointArc", "key": "bogus", "value": true}), "tool `threePointArc`: unknown option `bogus`"),
|
||||
];
|
||||
for (p, want) in cases {
|
||||
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
|
||||
}
|
||||
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false));
|
||||
}
|
||||
Reference in New Issue
Block a user