mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-18 11:14:13 +00:00
Merge main into feat/brushes-dry-media-library
This commit is contained in:
@@ -126,6 +126,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! Differences from the desktop app:
|
||||
//! - no TCP control server (browsers can't listen on sockets);
|
||||
//! - File → Open uses the browser file picker; bytes arrive asynchronously through
|
||||
//! `Services::inbox`;
|
||||
//! `Services::picked_inbox`;
|
||||
//! - Save / Export trigger a browser download;
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
|
||||
//! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and
|
||||
|
||||
@@ -17,7 +17,7 @@ use vectorcraft_ui_egui::i18n;
|
||||
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
|
||||
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
use vectorcraft_ui_egui::stylus::StylusFeed;
|
||||
use vectorcraft_ui_egui::{Services, VectorcraftApp};
|
||||
use vectorcraft_ui_egui::{PickedInbox, Services, VectorcraftApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
use crate::locks::WebLocks;
|
||||
@@ -25,6 +25,18 @@ use crate::pencil::SharedPointers;
|
||||
|
||||
pub(crate) type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
|
||||
|
||||
/// The files waiting to open, by where they came from (`Services::inbox`, `picked_inbox` and
|
||||
/// `page_inbox`).
|
||||
#[derive(Clone, Default)]
|
||||
struct OpenInboxes {
|
||||
/// Dropped on the page.
|
||||
dropped: Inbox,
|
||||
/// The open picker's answers.
|
||||
picked: PickedInbox,
|
||||
/// Handed over by the page's script (`window.vectorcraft.openFile`).
|
||||
page: Inbox,
|
||||
}
|
||||
|
||||
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
|
||||
/// whether Shift was held: where dropped files land.
|
||||
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
|
||||
@@ -48,7 +60,7 @@ const MAX_RESTARTS: u32 = 3;
|
||||
#[derive(Clone)]
|
||||
struct Host {
|
||||
runner: eframe::WebRunner,
|
||||
inbox: Inbox,
|
||||
inbox: OpenInboxes,
|
||||
place_inbox: PlaceInbox,
|
||||
script_inbox: ScriptInbox,
|
||||
drag: DragPos,
|
||||
@@ -77,7 +89,7 @@ pub fn start() {
|
||||
crate::fonts::load_startup_fonts().await;
|
||||
let host = Host {
|
||||
runner: eframe::WebRunner::new(),
|
||||
inbox: Arc::default(),
|
||||
inbox: OpenInboxes::default(),
|
||||
place_inbox: Arc::default(),
|
||||
script_inbox: Arc::default(),
|
||||
drag: DragPos::default(),
|
||||
@@ -132,13 +144,13 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
// The old services asked the old context for frames.
|
||||
app.services = services;
|
||||
app.status("The graphics were lost and have been restarted");
|
||||
crate::api::connect(None, host.inbox.clone(), ctx.clone());
|
||||
crate::api::connect(None, host.inbox.page.clone(), ctx.clone());
|
||||
app
|
||||
}
|
||||
None => {
|
||||
// `window.vectorcraft`: the page's control channel (crate::api).
|
||||
let (control_tx, control_rx) = std::sync::mpsc::channel();
|
||||
crate::api::connect(Some(control_tx), host.inbox.clone(), ctx.clone());
|
||||
crate::api::connect(Some(control_tx), host.inbox.page.clone(), ctx.clone());
|
||||
if let Err(e) = crate::api::install() {
|
||||
log::error!("vectorcraft-web: couldn't install window.vectorcraft: {}", js_err(e));
|
||||
}
|
||||
@@ -409,7 +421,7 @@ impl eframe::App for WebShell {
|
||||
for f in dropped {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
let target = app.drop_target(&name, pos, shift);
|
||||
let (inbox, place_inbox, repaint) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
@@ -432,14 +444,14 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
|
||||
fn services(
|
||||
inbox: Inbox,
|
||||
inbox: OpenInboxes,
|
||||
place_inbox: PlaceInbox,
|
||||
script_inbox: ScriptInbox,
|
||||
ctx: egui::Context,
|
||||
locks: Option<WebLocks>,
|
||||
stylus: StylusFeed,
|
||||
) -> Services {
|
||||
let open_inbox = inbox.clone();
|
||||
let open_inbox = inbox.picked.clone();
|
||||
let picked = place_inbox.clone();
|
||||
let place_ctx = ctx.clone();
|
||||
let screen_color = eye_dropper(ctx.clone());
|
||||
@@ -488,11 +500,12 @@ fn services(
|
||||
let dialog = fileio::open_filters().fold(rfd::AsyncFileDialog::new(), |d, (name, exts)| {
|
||||
d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)
|
||||
});
|
||||
let Some(file) = dialog.pick_file().await else {
|
||||
return;
|
||||
// A canceled pick answers `None`.
|
||||
let answer = match dialog.pick_file().await {
|
||||
Some(file) => Some((file.file_name(), file.read().await)),
|
||||
None => None,
|
||||
};
|
||||
let bytes = file.read().await;
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(answer);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
})),
|
||||
@@ -500,7 +513,9 @@ fn services(
|
||||
screen_color,
|
||||
// A download that couldn't be started fails the save or export it is for (#1693).
|
||||
download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))),
|
||||
inbox: Some(inbox),
|
||||
inbox: Some(inbox.dropped),
|
||||
picked_inbox: Some(inbox.picked),
|
||||
page_inbox: Some(inbox.page),
|
||||
recovery_store: Some(Arc::new(BrowserStore { locks })),
|
||||
// File → Print: the browser's print dialog.
|
||||
print: Some(Box::new(BrowserPrint)),
|
||||
|
||||
+12
-1
@@ -281,6 +281,10 @@ pub struct DxfOptions {
|
||||
pub scale_lineweights: bool,
|
||||
pub colors: ColorDepth,
|
||||
pub raster: RasterFormat,
|
||||
/// Placed images are written as IMAGE entities with their files (else left out, undecoded).
|
||||
pub include_images: bool,
|
||||
/// Filled areas get a solid HATCH after their outlines (else the outlines alone).
|
||||
pub include_hatches: bool,
|
||||
pub preserve: Preserve,
|
||||
/// Alter Paths for Appearance: a stroke a CAD line can't draw (one [`Preserve::Appearance`]
|
||||
/// outlines, one wider than the widest lineweight, or any stroke in R13 and R14, which have
|
||||
@@ -303,6 +307,8 @@ impl Default for DxfOptions {
|
||||
scale_lineweights: false,
|
||||
colors: ColorDepth::default(),
|
||||
raster: RasterFormat::default(),
|
||||
include_images: true,
|
||||
include_hatches: true,
|
||||
preserve: Preserve::default(),
|
||||
alter_paths: false,
|
||||
outline_text: false,
|
||||
@@ -322,7 +328,8 @@ pub enum DxfPreset {
|
||||
/// For CNC and CAM cutting software: version 2000 (the oldest version that has both lightweight
|
||||
/// polylines and lineweights), 1 mm = 1 unit, 256 indexed colors (all version 2000 holds), Maximize
|
||||
/// Editability with Alter Paths off (every stroke a center line), Outline Text (type as paths),
|
||||
/// and placed images as PNG.
|
||||
/// and placed images and fill hatches left out (fills are their outlines), with PNG as the
|
||||
/// format images take when they are put back in.
|
||||
Cnc,
|
||||
}
|
||||
|
||||
@@ -360,6 +367,8 @@ impl DxfPreset {
|
||||
scale_lineweights: false,
|
||||
colors: ColorDepth::Aci256,
|
||||
raster: RasterFormat::Png,
|
||||
include_images: false,
|
||||
include_hatches: false,
|
||||
preserve: Preserve::Editability,
|
||||
alter_paths: false,
|
||||
outline_text: true,
|
||||
@@ -377,6 +386,8 @@ impl DxfPreset {
|
||||
&& o.scale_lineweights == c.scale_lineweights
|
||||
&& o.colors == c.colors
|
||||
&& o.raster == c.raster
|
||||
&& o.include_images == c.include_images
|
||||
&& o.include_hatches == c.include_hatches
|
||||
&& o.preserve == c.preserve
|
||||
&& o.alter_paths == c.alter_paths
|
||||
&& o.outline_text == c.outline_text;
|
||||
|
||||
+44
-5
@@ -1,5 +1,6 @@
|
||||
//! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint
|
||||
//! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes
|
||||
//! order. Fills are their outlines then solid hatches (the outlines alone in R12 or with
|
||||
//! hatches left out), placed images are linked image files unless left out, strokes
|
||||
//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or
|
||||
//! filled outlines where the look needs them.
|
||||
|
||||
@@ -28,6 +29,8 @@ const NO_TRUE_COLOR: &str = "true colour needs DXF 2004 or later: colours are wr
|
||||
const NO_TRANSPARENCY: &str = "transparency needs DXF 2004 or later: transparent objects are written opaque";
|
||||
const NO_FILLS: &str = "DXF R12 has no fills: filled areas are written as their outlines";
|
||||
const NO_IMAGES: &str = "DXF R12 has no images: placed images are left out";
|
||||
const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)";
|
||||
const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)";
|
||||
const WIDE_LINES: &str =
|
||||
"lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width";
|
||||
const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)";
|
||||
@@ -339,6 +342,32 @@ fn subpaths(bp: &BezPath) -> Vec<Sub> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `bp` with each open subpath that can enclose an area closed, as a fill closes it: two or more
|
||||
/// segments, or one curve. A single straight segment stays open.
|
||||
fn closed_fill(bp: &BezPath) -> BezPath {
|
||||
let mut out = BezPath::new();
|
||||
let (mut segs, mut curved) = (0usize, false);
|
||||
let close = |out: &mut BezPath, segs: usize, curved: bool| {
|
||||
if segs >= 2 || (segs == 1 && curved) {
|
||||
out.close_path();
|
||||
}
|
||||
};
|
||||
for el in bp.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(_) => {
|
||||
close(&mut out, segs, curved);
|
||||
(segs, curved) = (0, false);
|
||||
}
|
||||
PathEl::ClosePath => (segs, curved) = (0, false),
|
||||
PathEl::LineTo(_) => segs += 1,
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => (segs, curved) = (segs + 1, true),
|
||||
}
|
||||
out.push(*el);
|
||||
}
|
||||
close(&mut out, segs, curved);
|
||||
out
|
||||
}
|
||||
|
||||
/// The most pixels of an image written (it is held decoded, as RGBA and encoded at once).
|
||||
const MAX_IMAGE_PIXELS: u64 = 64 << 20;
|
||||
|
||||
@@ -878,13 +907,13 @@ impl<'a> Scene<'a> {
|
||||
Some(vectorcraft_brush::stroke_pieces(doc, b, bp, st))
|
||||
}
|
||||
|
||||
/// A filled area as its outlines followed by a solid hatch (R12: the outlines alone). Laser
|
||||
/// and cutter software reads the outlines and skips hatches. `clean`: the path has no
|
||||
/// A filled area as its outlines followed by a solid hatch (R12, or with hatches left out: the
|
||||
/// outlines alone). Laser and cutter software reads the outlines and skips hatches. `clean`: the path has no
|
||||
/// overlaps, so the hatch's even-odd rule reads it as it is.
|
||||
fn area(&mut self, bp: &BezPath, rule: FillRule, style: &EntityStyle, clean: bool) {
|
||||
if !self.o.version.handles() {
|
||||
self.warn(NO_FILLS);
|
||||
self.lines(bp, style, 0.0);
|
||||
self.lines(&closed_fill(bp), style, 0.0);
|
||||
return;
|
||||
}
|
||||
let several = bp.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count() > 1;
|
||||
@@ -893,11 +922,17 @@ impl<'a> Scene<'a> {
|
||||
.flatten()
|
||||
.map(|p| p.to_bezpath());
|
||||
let outline = normalized.as_ref().unwrap_or(bp);
|
||||
// A fill with no loop of three points or more encloses no area: no outline and no hatch.
|
||||
let loops: Vec<Vec<Point>> = polygons(outline).into_iter().filter(|p| p.len() >= 3).collect();
|
||||
if loops.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.lines(outline, style, 0.0);
|
||||
// The outlines close as the fill does, so an open path's fill keeps its closing edge.
|
||||
self.lines(&closed_fill(outline), style, 0.0);
|
||||
if !self.o.include_hatches {
|
||||
self.warn(HATCHES_OFF);
|
||||
return;
|
||||
}
|
||||
let h = self.handle();
|
||||
let layer = self.layer.clone();
|
||||
self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch");
|
||||
@@ -1285,6 +1320,10 @@ impl<'a> Scene<'a> {
|
||||
self.warn(NO_IMAGES);
|
||||
return;
|
||||
}
|
||||
if !self.o.include_images {
|
||||
self.warn(IMAGES_OFF);
|
||||
return;
|
||||
}
|
||||
let Some(i) = self.image_def(im) else { return };
|
||||
let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return };
|
||||
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
|
||||
|
||||
@@ -843,10 +843,151 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro
|
||||
assert!(out.images.is_empty());
|
||||
assert_eq!(DxfPreset::of(&o), DxfPreset::Cnc);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { colors: ColorDepth::True, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { include_images: true, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { include_hatches: true, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc));
|
||||
}
|
||||
|
||||
/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order
|
||||
/// `fill`'s rectangle.
|
||||
fn image_and_fill_doc(fill: Paint) -> Document {
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut d = doc_with(|d| {
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
width: 4,
|
||||
height: 2,
|
||||
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
vec![
|
||||
path(d, shapes::rectangle(Rect::new(50.0, 10.0, 150.0, 60.0)), fill, Paint::None, 0.0),
|
||||
Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))),
|
||||
]
|
||||
});
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
|
||||
d
|
||||
}
|
||||
|
||||
const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)";
|
||||
const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)";
|
||||
|
||||
#[test]
|
||||
fn fills_without_hatches_keep_their_outlines() {
|
||||
let d = shapes_doc();
|
||||
let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap();
|
||||
assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle");
|
||||
assert_eq!(out.warnings, [HATCHES_OFF]);
|
||||
let e = entities(&out);
|
||||
assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight");
|
||||
// Hatches stay by default, with no note.
|
||||
let on = export(&d, &opts(&d)).unwrap();
|
||||
assert!(kinds(&on).iter().any(|k| k == "HATCH") && !on.warnings.iter().any(|w| w == HATCHES_OFF));
|
||||
// The outlines are the ones written beside hatches, also for overlapping subpaths, which are
|
||||
// merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way.
|
||||
let compound = doc_with(|d| {
|
||||
let mut bp = shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 60.0)).to_bezpath();
|
||||
bp.extend(shapes::rectangle(Rect::new(40.0, 40.0, 90.0, 90.0)).to_bezpath().elements().iter().copied());
|
||||
let p = PathData::from_bezpath(&bp);
|
||||
vec![
|
||||
path(d, p, Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
path(d, shapes::rectangle(Rect::new(10.0, 70.0, 90.0, 70.0)), Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
path(d, shapes::line(Point::new(100.0, 10.0), Point::new(150.0, 60.0)), Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
]
|
||||
});
|
||||
let without_hatches = |o: &DxfOutput| {
|
||||
let mut e = entities(o);
|
||||
e.retain(|x| kind(x) != "HATCH");
|
||||
e.into_iter().map(|x| x.into_iter().filter(|p| p.0 != 5).collect::<Pairs>()).collect::<Vec<_>>()
|
||||
};
|
||||
let (c_on, c_off) =
|
||||
(export(&compound, &opts(&compound)).unwrap(), export(&compound, &DxfOptions { include_hatches: false, ..opts(&compound) }).unwrap());
|
||||
assert_eq!(kinds(&c_on), ["LWPOLYLINE", "HATCH"], "one merged outline");
|
||||
assert_eq!(without_hatches(&c_off), without_hatches(&c_on));
|
||||
assert_eq!(without_hatches(&out), without_hatches(&on));
|
||||
// Strokes outlined for their look are areas too: their outlines stay.
|
||||
let altered =
|
||||
export(&d, &DxfOptions { include_hatches: false, alter_paths: true, preserve: Preserve::Editability, version: DxfVersion::R14, ..opts(&d) })
|
||||
.unwrap();
|
||||
assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered));
|
||||
// Nothing filled: no note.
|
||||
let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
assert!(export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap().warnings.is_empty());
|
||||
// R12 has no hatches anyway: the same outlines, and its own note alone.
|
||||
let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap();
|
||||
let (off, on) = (r12(false), r12(true));
|
||||
assert_eq!(off.bytes, on.bytes);
|
||||
assert_eq!(off.warnings, on.warnings);
|
||||
assert!(!off.warnings.iter().any(|w| w == HATCHES_OFF));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_s_fill_outline_keeps_its_closing_edge() {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
bp.move_to((10.0, 10.0));
|
||||
bp.line_to((90.0, 10.0));
|
||||
bp.line_to((50.0, 80.0));
|
||||
let open = PathData::from_bezpath(&bp);
|
||||
let d = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0)]);
|
||||
let closed = |e: &Pairs| get(e, 70).and_then(|v| v.trim().parse::<i64>().ok()).is_some_and(|v| v & 1 == 1);
|
||||
for include_hatches in [false, true] {
|
||||
let out = export(&d, &DxfOptions { include_hatches, ..opts(&d) }).unwrap();
|
||||
let e: Vec<Pairs> = entities(&out).into_iter().filter(|x| kind(x) == "LWPOLYLINE").collect();
|
||||
assert_eq!(e.len(), 2, "the fill's outline and the stroke: {:?}", kinds(&out));
|
||||
assert!(closed(&e[0]), "the fill's outline closes as the fill does (hatches {include_hatches})");
|
||||
assert!(!closed(&e[1]), "the stroke stays open (hatches {include_hatches})");
|
||||
}
|
||||
// R12 writes the outline alone, closed too.
|
||||
let fill_only = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::None, 0.0)]);
|
||||
let r12 = export(&fill_only, &DxfOptions { version: DxfVersion::R12, ..opts(&fill_only) }).unwrap();
|
||||
let e = entities(&r12);
|
||||
assert_eq!(kind(&e[0]), "POLYLINE", "{:?}", kinds(&r12));
|
||||
assert!(closed(&e[0]), "R12's outline closes as the fill does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_can_be_left_out_with_their_files() {
|
||||
let d = image_and_fill_doc(Paint::None);
|
||||
let out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap();
|
||||
assert!(entities(&out).is_empty() && out.images.is_empty(), "{:?}", kinds(&out));
|
||||
let p = pairs(&out.bytes);
|
||||
assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES")));
|
||||
assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE")));
|
||||
assert_eq!(out.warnings, [IMAGES_OFF]);
|
||||
// An image that can't be decoded is not read when images are left out.
|
||||
let mut broken = d.clone();
|
||||
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
|
||||
assert_eq!(export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap().warnings, [IMAGES_OFF]);
|
||||
assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded")));
|
||||
// R12 has no images anyway: its own note alone.
|
||||
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap();
|
||||
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && !r12.warnings.iter().any(|w| w == IMAGES_OFF));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() {
|
||||
let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let run = |o: DxfOptions| export(&d, &DxfOptions { region: d.artboards[0].rect, ..o }).unwrap();
|
||||
let both = run(DxfOptions::default());
|
||||
assert_eq!(kinds(&both), ["LWPOLYLINE", "HATCH", "IMAGE"]);
|
||||
assert_eq!(both.images.len(), 1);
|
||||
let no_images = run(DxfOptions { include_images: false, ..DxfOptions::default() });
|
||||
assert_eq!((kinds(&no_images), no_images.images.len()), (vec!["LWPOLYLINE".to_string(), "HATCH".into()], 0));
|
||||
let no_hatches = run(DxfOptions { include_hatches: false, ..DxfOptions::default() });
|
||||
assert_eq!((kinds(&no_hatches), no_hatches.images.len()), (vec!["LWPOLYLINE".to_string(), "IMAGE".into()], 1));
|
||||
// CNC / CAM: the cutting path alone, with no image file and both notes.
|
||||
let cnc = run(DxfPreset::Cnc.options());
|
||||
assert_eq!(kinds(&cnc), ["LWPOLYLINE"]);
|
||||
assert!(cnc.images.is_empty());
|
||||
assert!(cnc.warnings.iter().any(|w| w == IMAGES_OFF) && cnc.warnings.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.warnings);
|
||||
let custom = DxfPreset::Custom.options();
|
||||
assert!(custom.include_images && custom.include_hatches, "Custom keeps both");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_become_dxf_layers() {
|
||||
let mut d = shapes_doc();
|
||||
|
||||
+24
-6
@@ -1052,11 +1052,27 @@ fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option<Vec<usize>> {
|
||||
/// its handles) moved onto the key's centre, so moving a key moves its end of the spine;
|
||||
/// - a spine from Replace Spine: its first subpath, `None` for the anchors (the keys spread
|
||||
/// evenly along it by arc length).
|
||||
///
|
||||
/// `None` for a blend made without a spine ([`BlendSpec::no_spine`]).
|
||||
pub fn blend_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Option<Vec<usize>>)> {
|
||||
if spec.no_spine {
|
||||
return None;
|
||||
}
|
||||
layout_spine(keys, spec)
|
||||
}
|
||||
|
||||
/// The spine `spec` stores, unless the blend was made without one.
|
||||
fn stored_spine(spec: &BlendSpec) -> Option<&PathData> {
|
||||
spec.spine.as_ref().filter(|_| !spec.no_spine)
|
||||
}
|
||||
|
||||
/// [`blend_spine`] for placing the steps: a blend made without a spine still places them on the
|
||||
/// straight lines between its key centers.
|
||||
fn layout_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Option<Vec<usize>>)> {
|
||||
if keys.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let Some(stored) = &spec.spine else {
|
||||
let Some(stored) = stored_spine(spec) else {
|
||||
let centers: Vec<Point> = keys.iter().map(|k| center_of(k)).collect();
|
||||
return Some((PathData::single(SubPath::polyline(¢ers, false)), Some((0..keys.len()).collect())));
|
||||
};
|
||||
@@ -1127,10 +1143,10 @@ impl Rail {
|
||||
/// `None` when nothing moves: no stored spine and the steps keep the page's orientation.
|
||||
fn new(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<Self> {
|
||||
let rotate = spec.orientation == BlendOrientation::AlignToPath;
|
||||
if spec.spine.is_none() && !rotate {
|
||||
if stored_spine(spec).is_none() && !rotate {
|
||||
return None;
|
||||
}
|
||||
let (path, anchors) = blend_spine(keys, spec)?;
|
||||
let (path, anchors) = layout_spine(keys, spec)?;
|
||||
let spine = Spine::new(&path)?;
|
||||
let total = spine.length();
|
||||
let k = keys.len();
|
||||
@@ -1192,10 +1208,10 @@ impl Rail {
|
||||
/// spine it is moved to, and so does its own centre, which it turns about. `None` when nothing
|
||||
/// moves.
|
||||
pub(crate) fn rail_reach(keys: &[Arc<Node>], spec: &BlendSpec, symbols: Option<&crate::SymbolBoxes>) -> Option<Rect> {
|
||||
if spec.spine.is_none() && spec.orientation != BlendOrientation::AlignToPath {
|
||||
if stored_spine(spec).is_none() && spec.orientation != BlendOrientation::AlignToPath {
|
||||
return None;
|
||||
}
|
||||
let spine = blend_spine(keys, spec)?.0.bounds()?;
|
||||
let spine = layout_spine(keys, spec)?.0.bounds()?;
|
||||
let radius = keys
|
||||
.iter()
|
||||
.filter_map(|k| {
|
||||
@@ -1404,7 +1420,9 @@ pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
|
||||
for j in 1..=n {
|
||||
// Even position of the step, then where the easing puts its shape and its colours.
|
||||
let u = j as f64 / (n + 1) as f64;
|
||||
let (t, tc) = (if rail.is_some() { spec.ease.apply(u) } else { u }, spec.color_position(u));
|
||||
// Easing needs a spine: a blend made without one keeps its steps evenly spaced.
|
||||
let eased = rail.is_some() && !spec.no_spine;
|
||||
let (t, tc) = (if eased { spec.ease.apply(u) } else { u }, spec.color_position(u));
|
||||
let mut s = lerp.at_eased(t, tc);
|
||||
if let Some(r) = &rail {
|
||||
r.place(&mut s, i, t);
|
||||
|
||||
@@ -49,7 +49,7 @@ mod expand;
|
||||
mod mesh;
|
||||
mod warp;
|
||||
|
||||
pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec};
|
||||
pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec, BlendSpineMode};
|
||||
#[cfg(test)]
|
||||
use blend_spec::{blend_color_shift, blend_ramp};
|
||||
pub use envelope::{
|
||||
|
||||
@@ -107,6 +107,11 @@ pub struct BlendSpec {
|
||||
/// on anchor points); `None`: chosen so closed shapes don't twist.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub starts: Vec<Option<u32>>,
|
||||
/// The blend was made without a spine (Create Spine › Never): it has no spine to show, edit,
|
||||
/// reverse or release, and no easing. Its steps still sit on the straight lines between the
|
||||
/// key centers. Replace Spine gives it one.
|
||||
#[serde(default, rename = "noSpine", skip_serializing_if = "is_false", deserialize_with = "lenient_bool")]
|
||||
pub no_spine: bool,
|
||||
}
|
||||
|
||||
impl BlendSpec {
|
||||
@@ -116,6 +121,41 @@ impl BlendSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Blend panel's Create Spine setting: whether a new blend gets a spine.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BlendSpineMode {
|
||||
/// The usual rule: every new blend gets a spine, the straight lines between its key centers.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Every new blend gets a spine, whatever its key objects are.
|
||||
Always,
|
||||
/// New blends get no spine.
|
||||
Never,
|
||||
}
|
||||
|
||||
impl BlendSpineMode {
|
||||
/// Every mode, in the order the Blend panel lists them.
|
||||
pub const ALL: [Self; 3] = [Self::Auto, Self::Always, Self::Never];
|
||||
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Auto => "auto",
|
||||
Self::Always => "always",
|
||||
Self::Never => "never",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|m| m.id() == id)
|
||||
}
|
||||
|
||||
/// Whether a new blend made with this mode gets a spine.
|
||||
pub fn creates_spine(self) -> bool {
|
||||
self != Self::Never
|
||||
}
|
||||
}
|
||||
|
||||
/// Blend Options set with no blend selected: what new blends start with.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct BlendDefaults {
|
||||
@@ -123,6 +163,29 @@ pub struct BlendDefaults {
|
||||
pub spacing: BlendSpacing,
|
||||
#[serde(default)]
|
||||
pub orientation: BlendOrientation,
|
||||
/// Create Spine (`object.blend.createSpine`).
|
||||
#[serde(default, rename = "createSpine", skip_serializing_if = "is_auto", deserialize_with = "spine_mode")]
|
||||
pub create_spine: BlendSpineMode,
|
||||
}
|
||||
|
||||
fn is_false(v: &bool) -> bool {
|
||||
!*v
|
||||
}
|
||||
|
||||
fn is_auto(v: &BlendSpineMode) -> bool {
|
||||
*v == BlendSpineMode::Auto
|
||||
}
|
||||
|
||||
/// Reading a native file never fails over a `noSpine` that is not a boolean: the blend keeps its
|
||||
/// spine.
|
||||
fn lenient_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
|
||||
Ok(serde_json::Value::deserialize(d)?.as_bool().unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Reading the preferences never fails over an unknown Create Spine value: it becomes Auto.
|
||||
fn spine_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BlendSpineMode, D::Error> {
|
||||
let v = serde_json::Value::deserialize(d)?;
|
||||
Ok(v.as_str().and_then(BlendSpineMode::from_id).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Reading a native file never fails over one bad blend number: out-of-range values clamp,
|
||||
|
||||
@@ -156,6 +156,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
|
||||
BuiltinStyleLibrary { id: "outlines-rules", name: "Outlines and Rules", make: outlines_rules },
|
||||
BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn },
|
||||
BuiltinStyleLibrary { id: "textures", name: "Textures", make: textures },
|
||||
BuiltinStyleLibrary { id: "painted-sketched", name: "Painted and Sketched", make: painted_sketched },
|
||||
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
|
||||
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
|
||||
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
|
||||
@@ -323,6 +324,59 @@ fn hand_drawn() -> Vec<GraphicStyle> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Painted and Sketched: one catalog paint or sketch effect over the whole appearance, so it
|
||||
/// repaints the fill and the stroke together (watercolor, dry brush, pastels, charcoal and ink).
|
||||
fn painted_sketched() -> Vec<GraphicStyle> {
|
||||
vec![
|
||||
style(
|
||||
"Washed Blue",
|
||||
vec![F(fill("#8ab9c9"))],
|
||||
vec![fx("artistic.watercolor", json!({"brushDetail": 8.0, "shadowIntensity": 2.0, "texture": 2.0}))],
|
||||
),
|
||||
style(
|
||||
"Bristle Ochre",
|
||||
vec![F(fill("#c4975a")), S(stroke("#76533d", 1.0))],
|
||||
vec![fx("artistic.dryBrush", json!({"brushSize": 4.0, "brushDetail": 7.0, "texture": 2.0}))],
|
||||
),
|
||||
style(
|
||||
"Pastel Heather",
|
||||
vec![F(fill("#a78ca5"))],
|
||||
vec![fx(
|
||||
"artistic.roughPastels",
|
||||
json!({
|
||||
"strokeLength": 8.0,
|
||||
"strokeDetail": 9.0,
|
||||
"texture": "canvas",
|
||||
"scaling": 100.0,
|
||||
"relief": 5.0,
|
||||
"lightDirection": "topLeft",
|
||||
"invert": false
|
||||
}),
|
||||
)],
|
||||
),
|
||||
style(
|
||||
"Charcoal Shade",
|
||||
vec![F(fill("#666666"))],
|
||||
vec![fx("sketch.charcoal", json!({"thickness": 3.0, "detail": 3.0, "lightDarkBalance": 55.0}))],
|
||||
),
|
||||
style(
|
||||
"Ink Contour",
|
||||
vec![F(fill("#d9e2df")), S(stroke("#26323b", 1.0))],
|
||||
vec![fx("brushStrokes.inkOutlines", json!({"strokeLength": 6.0, "darkIntensity": 24.0, "lightIntensity": 8.0}))],
|
||||
),
|
||||
style(
|
||||
"Wet Ink",
|
||||
vec![F(fill("#637b85"))],
|
||||
vec![fx("brushStrokes.sumiE", json!({"strokeWidth": 7.0, "strokePressure": 5.0, "contrast": 20.0}))],
|
||||
),
|
||||
style(
|
||||
"Fine Pen",
|
||||
vec![F(fill("#d8d4c6"))],
|
||||
vec![fx("sketch.graphicPen", json!({"strokeLength": 6.0, "lightDarkBalance": 55.0, "strokeDirection": "rightDiagonal"}))],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Textures: fills and strokes painted with the catalog's texture effects (grain, canvas and
|
||||
/// burlap surfaces, craquelure, tiles, patchwork, stained glass and water paper).
|
||||
fn textures() -> Vec<GraphicStyle> {
|
||||
@@ -603,6 +657,36 @@ mod tests {
|
||||
assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painted_and_sketched_follows_textures_with_one_effect_per_style() {
|
||||
let ids: Vec<&str> = STYLE_LIBRARIES.iter().map(|b| b.id).collect();
|
||||
let at = ids.iter().position(|&id| id == "painted-sketched").expect("listed");
|
||||
assert_eq!(ids[at - 1], "textures");
|
||||
let lib = builtin_style_library("painted-sketched").unwrap();
|
||||
assert_eq!(lib.name, "Painted and Sketched");
|
||||
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(names, ["Washed Blue", "Bristle Ochre", "Pastel Heather", "Charcoal Shade", "Ink Contour", "Wet Ink", "Fine Pen"]);
|
||||
let effects: Vec<&str> = lib.styles.iter().flat_map(|g| g.appearance.effects.iter().map(|e| e.id.as_str())).collect();
|
||||
assert_eq!(
|
||||
effects,
|
||||
[
|
||||
"artistic.watercolor",
|
||||
"artistic.dryBrush",
|
||||
"artistic.roughPastels",
|
||||
"sketch.charcoal",
|
||||
"brushStrokes.inkOutlines",
|
||||
"brushStrokes.sumiE",
|
||||
"sketch.graphicPen"
|
||||
]
|
||||
);
|
||||
assert!(lib.styles.iter().all(|g| g.appearance.items.iter().all(|i| i.effects().is_empty())), "no effects on a fill or stroke");
|
||||
// No other built-in library holds a style of the same name.
|
||||
for b in STYLE_LIBRARIES.iter().filter(|b| b.id != "painted-sketched") {
|
||||
let other = builtin_style_library(b.id).unwrap();
|
||||
assert!(other.styles.iter().all(|g| !names.contains(&g.name.as_str())), "{}", b.id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vcstyles_round_trip() {
|
||||
let mut lib = (*builtin_style_library("gradient-finishes").unwrap()).clone();
|
||||
|
||||
@@ -28,6 +28,15 @@ pub struct TabStop {
|
||||
pub align_on: char,
|
||||
}
|
||||
|
||||
impl TabStop {
|
||||
/// The largest stop position `text.tabs.set` and a paragraph style take, in points.
|
||||
pub const MAX_POSITION: f64 = 100_000.0;
|
||||
/// The most leader characters a stop repeats.
|
||||
pub const MAX_LEADER: usize = 8;
|
||||
/// The most stops `text.tabs.set` and a paragraph style take in one list.
|
||||
pub const MAX_STOPS: usize = 256;
|
||||
}
|
||||
|
||||
fn default_align_on() -> char {
|
||||
'.'
|
||||
}
|
||||
|
||||
@@ -507,6 +507,23 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt
|
||||
Some(v) => Ok(Some(vec![checked_id(s, v, command)?])),
|
||||
}
|
||||
}
|
||||
/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form:
|
||||
/// for a command that looks its objects up itself, outside the document's layers too.
|
||||
pub(crate) fn given_object_ids(p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> {
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
return ids_param(p, "ids", command);
|
||||
}
|
||||
match p.get("id").filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(Value::String(r)) if r.starts_with('$') => {
|
||||
Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
|
||||
}
|
||||
Some(v) => {
|
||||
let id = v.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {v}: expected a non-negative integer")))?;
|
||||
Ok(Some(vec![id]))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `v` as an index, a count or a byte offset: past `usize::MAX` reads as `usize::MAX`, past the end of any list.
|
||||
pub(crate) fn index(v: u64) -> usize {
|
||||
usize::try_from(v).unwrap_or(usize::MAX)
|
||||
|
||||
@@ -33,8 +33,8 @@ mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove,
|
||||
brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art,
|
||||
brush_remove, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
pub(crate) use dynamic::{edit_part, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
@@ -67,6 +67,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
brush_selection_art
|
||||
),
|
||||
cmd!(
|
||||
"brush.placeArt",
|
||||
"Place Brush Art",
|
||||
[],
|
||||
None,
|
||||
"{name, x?, y?} place a copy of the art a scatter, art or pattern brush is made of, centered on (x, y) (default: the center of the first artboard), and select it, as dragging the brush from the Brushes panel onto an empty part of the canvas does; a pattern brush places its tiles left to right (side, outer corner, inner corner, start, end; the ones it has art for) 10 pt apart, each in a group named Side Tile, Outer Corner Tile, Inner Corner Tile, Start Tile or End Tile, with an unpainted rectangle at the back of a tile that has a repeat frame marking that frame; a calligraphic or bristle brush is refused → {id}",
|
||||
has_doc,
|
||||
brush_place_art
|
||||
),
|
||||
cmd!(
|
||||
"brush.apply",
|
||||
"Apply Brush",
|
||||
|
||||
@@ -483,6 +483,93 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": out }))
|
||||
}
|
||||
|
||||
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
|
||||
/// places them.
|
||||
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
|
||||
|
||||
/// The space between the pattern brush tiles `brush.placeArt` places, in points.
|
||||
const TILE_GAP: f64 = 10.0;
|
||||
|
||||
/// The message for a brush that is not made of art.
|
||||
fn no_art(name: &str) -> String {
|
||||
format!("`{name}` has no art (only scatter, art and pattern brushes do)")
|
||||
}
|
||||
|
||||
/// Tile `i` of `p` ([`TILE_NAMES`] order): its art and its repeat frame, when it has art.
|
||||
fn tile(p: &brush::PatternBrush, i: usize) -> Option<(&Node, Option<vectorcraft_geom::Rect>)> {
|
||||
match i {
|
||||
0 => Some((&p.side, p.side_frame)),
|
||||
1 => p.outer_corner.as_ref().map(|n| (n, p.outer_corner_frame)),
|
||||
2 => p.inner_corner.as_ref().map(|n| (n, p.inner_corner_frame)),
|
||||
3 => p.start.as_ref().map(|n| (n, p.start_frame)),
|
||||
_ => p.end.as_ref().map(|n| (n, p.end_frame)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The art `brush.placeArt` places for brush `b`, in the brush's own coordinates: a scatter or art
|
||||
/// brush's art, or a pattern brush's tiles in a row, each in a group named for its tile
|
||||
/// ([`TILE_NAMES`]), with an unpainted rectangle at the back of a tile that has a repeat frame
|
||||
/// marking that frame. `None` for a brush that is not made of art. Symbol instances in the art are
|
||||
/// measured by their symbols' art in `symbols`.
|
||||
fn placed_art(b: &Brush, symbols: &vectorcraft_doc::SymbolBoxes) -> Option<Node> {
|
||||
match &b.kind {
|
||||
BrushKind::Scatter(sc) => Some(sc.art.clone()),
|
||||
BrushKind::Art(a) => Some(a.art.clone()),
|
||||
BrushKind::Pattern(pb) => {
|
||||
let mut tiles = vec![];
|
||||
let mut x = 0.0;
|
||||
for (i, tile_name) in TILE_NAMES.iter().enumerate() {
|
||||
let Some((art, frame)) = tile(pb, i) else { continue };
|
||||
let mut children = vec![];
|
||||
if let Some(f) = frame {
|
||||
let marker = Node::path(
|
||||
NodeId(0),
|
||||
vectorcraft_geom::shapes::rectangle(f),
|
||||
vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0),
|
||||
);
|
||||
children.push(Arc::new(marker));
|
||||
}
|
||||
children.push(Arc::new(art.clone()));
|
||||
let mut g = Node::group(NodeId(0), children);
|
||||
g.name = Some((*tile_name).to_string());
|
||||
let Some(r) = g.geometric_bounds_with(symbols) else { continue };
|
||||
// Each tile sits right of the one before it, centered on the line y = 0.
|
||||
g.transform(vectorcraft_geom::Affine::translate((x - r.x0, -r.center().y)), false);
|
||||
x += r.width() + TILE_GAP;
|
||||
tiles.push(Arc::new(g));
|
||||
}
|
||||
Some(Node::group(NodeId(0), tiles))
|
||||
}
|
||||
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `brush.placeArt`: a copy of the art brush `name` is made of, centered on (`x`, `y`) (default: the
|
||||
/// center of the first artboard) in the layer new art goes into, and selected, as one undo step.
|
||||
/// Scatter and art brushes place their art; pattern brushes place their tiles ([`placed_art`]).
|
||||
pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.placeArt";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
let d = &s.doc()?.doc;
|
||||
let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(super::Point::ZERO);
|
||||
let at = super::Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?);
|
||||
let b = brush::find(d, &name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
|
||||
let symbols = d.symbol_boxes();
|
||||
let mut art = placed_art(&b, &symbols).ok_or_else(|| bad(C, no_art(&name)))?;
|
||||
if let Some(r) = art.geometric_bounds_with(&symbols) {
|
||||
art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false);
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Place Brush Art", |d, sel| {
|
||||
let art = d.reid(&art);
|
||||
let id = art.id;
|
||||
d.insert(parent, usize::MAX, art)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Document Info panel data, its categories and the text report (Document Info › Save…, File →
|
||||
//! Package), and Object → Make Pixel Perfect.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -358,6 +358,16 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut fonts = BTreeSet::new();
|
||||
let mut images: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let mut image_rows: Vec<ImageRow> = vec![];
|
||||
// Whether the request being served may read each linked file (a relative path read from the
|
||||
// document's folder), checked once per file.
|
||||
let mut readable: HashMap<String, bool> = HashMap::new();
|
||||
let link_doc = super::links::LinkBase::of(st).doc;
|
||||
let mut may_read = |stored: &str| {
|
||||
*readable.entry(stored.to_string()).or_insert_with(|| {
|
||||
let resolved = super::fileio::document_path(stored, link_doc).ok();
|
||||
crate::file_access::check_read(resolved.as_deref().unwrap_or(stored)).is_ok()
|
||||
})
|
||||
};
|
||||
let mut patterns = BTreeSet::new();
|
||||
let mut symbols = BTreeSet::new();
|
||||
let mut spot = BTreeSet::new();
|
||||
@@ -411,12 +421,15 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some("textObjects")
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
// A linked file outside a confined request's read roots: `link` is null, and the row
|
||||
// names the file alone.
|
||||
let link = im.link.as_ref().map(|l| (l, may_read(&l.path)));
|
||||
images.insert(
|
||||
im.key.clone(),
|
||||
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": im.link.as_ref().map(|l| &l.path) }),
|
||||
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }),
|
||||
);
|
||||
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
|
||||
image_rows.push((name, im.width, im.height, im.link.as_ref().map(|l| l.path.clone())));
|
||||
image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() })));
|
||||
Some("images")
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
|
||||
@@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Refresh Deferred Effects",
|
||||
["Effect"],
|
||||
None,
|
||||
"{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
|
||||
"{ids?|id?: [object id] (objects of the document, also in the art of a symbol, pattern, brush or opacity mask; an object without a deferred stage adds nothing; an id of no object is an error; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
|
||||
has_deferred,
|
||||
refresh_deferred
|
||||
),
|
||||
@@ -150,16 +150,27 @@ fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) ->
|
||||
None => rest.push(object),
|
||||
}
|
||||
}
|
||||
if rest.is_empty() {
|
||||
for (id, n) in definition_objects(d, &rest) {
|
||||
out.entry(id).or_insert((n, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The objects of `ids` found in the art `d` draws from outside its layers: the art of its
|
||||
/// symbols, patterns and brushes, and opacity masks (in that art or in the layers).
|
||||
fn definition_objects(d: &Document, ids: &[u64]) -> std::collections::HashMap<u64, Arc<Node>> {
|
||||
let mut out = std::collections::HashMap::new();
|
||||
if ids.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let ids: std::collections::HashSet<u64> = ids.iter().copied().collect();
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let symbols = d.symbols.iter().map(|s| &*s.art);
|
||||
let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a));
|
||||
let layers = d.layers.iter().map(|a| &**a);
|
||||
let mut look = |n: &Node| {
|
||||
if rest.contains(&n.id.0) {
|
||||
out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false));
|
||||
if ids.contains(&n.id.0) {
|
||||
out.entry(n.id.0).or_insert_with(|| Arc::new(n.clone()));
|
||||
}
|
||||
};
|
||||
for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) {
|
||||
@@ -231,10 +242,19 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone());
|
||||
let ids = super::named_ids(p)?;
|
||||
let objects = prune(&doc, &fx);
|
||||
if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
// An object of the art drawn outside the layers is valid whether or not it has a stage.
|
||||
let elsewhere: Vec<u64> = ids.iter().flatten().filter(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)).map(|id| id.0).collect();
|
||||
let found = definition_objects(&doc, &elsewhere);
|
||||
if let Some(id) = elsewhere.iter().find(|id| !found.contains_key(id)) {
|
||||
return Err(EngineError::NoNode(NodeId(*id)));
|
||||
}
|
||||
let ids: Option<Vec<u64>> = ids.map(|ids| ids.iter().map(|id| id.0).collect());
|
||||
// Only the objects with a stage have anything to refresh.
|
||||
let ids: Option<Vec<u64>> = ids.map(|ids| {
|
||||
let mut ids: Vec<u64> = ids.iter().map(|id| id.0).filter(|id| objects.contains_key(id)).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
ids
|
||||
});
|
||||
let counts = fx.refresh(ids.as_deref(), |targets| {
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let mut whole = Vec::new();
|
||||
|
||||
@@ -90,9 +90,9 @@ pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
pub use save::{
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option,
|
||||
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
|
||||
templates_folder,
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, leave_out_unreadable_save_paths,
|
||||
reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates,
|
||||
template_filters, templates_dialog_folder, templates_folder,
|
||||
};
|
||||
pub(crate) use screens::{
|
||||
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
|
||||
@@ -124,7 +124,9 @@ pub(crate) use access::list_dir;
|
||||
pub use access::write_file_with;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::{Placed, copy_new, file_metadata};
|
||||
pub(crate) use access::{absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, write_file, write_new_file};
|
||||
pub(crate) use access::{
|
||||
absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, shown_link, shown_path, write_file, write_new_file,
|
||||
};
|
||||
#[cfg(all(test, windows))]
|
||||
pub(crate) use access::{document_path_on, document_path_with};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -42,6 +42,29 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
(out, seen)
|
||||
}
|
||||
|
||||
/// May a reply to the request being served name `path`, a file or folder the client did not give?
|
||||
/// Always without roots in force; with them, only inside the read roots ([`crate::file_access::check_read`]).
|
||||
pub(crate) fn shown(path: &str) -> bool {
|
||||
crate::file_access::check_read(path).is_ok()
|
||||
}
|
||||
|
||||
/// `path` as a reply to the request being served names it: whole when [`shown`], else its file name,
|
||||
/// after the last `/` or `\` whichever platform wrote it (empty for a path that ends in no name, such
|
||||
/// as `..` or a folder ending in a separator).
|
||||
pub(crate) fn shown_path(path: &str) -> std::borrow::Cow<'_, str> {
|
||||
shown_link(path, None)
|
||||
}
|
||||
|
||||
/// A link's `stored` path as a reply to the request being served names it: whole when the file it
|
||||
/// names (`resolved`, else `stored` itself) is [`shown`], else its file name as [`shown_path`] gives it.
|
||||
pub(crate) fn shown_link<'a>(stored: &'a str, resolved: Option<&str>) -> std::borrow::Cow<'a, str> {
|
||||
if shown(resolved.unwrap_or(stored)) {
|
||||
return std::borrow::Cow::Borrowed(stored);
|
||||
}
|
||||
let name = stored.rsplit(vectorcraft_doc::links::path_separators(stored)).next().unwrap_or_default();
|
||||
std::borrow::Cow::Borrowed(if matches!(name, "." | "..") { "" } else { name })
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Presets",
|
||||
[],
|
||||
None,
|
||||
"{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones; any name works as document.exportForScreens' exportPreset",
|
||||
"{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones (a folder outside the automation read roots is left out of settings); any name works as document.exportForScreens' exportPreset",
|
||||
always,
|
||||
screens::presets_list
|
||||
),
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Export Presets",
|
||||
[],
|
||||
None,
|
||||
"{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}",
|
||||
"{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON; a folder outside the automation read roots is left out); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}",
|
||||
always,
|
||||
screens::presets_export
|
||||
),
|
||||
@@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens Settings",
|
||||
[],
|
||||
None,
|
||||
"{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them)",
|
||||
"{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them; a folder outside the automation read roots is left out)",
|
||||
has_doc,
|
||||
screens::export_settings
|
||||
),
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export DXF",
|
||||
[],
|
||||
None,
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
|
||||
has_doc,
|
||||
export_dxf
|
||||
)]
|
||||
@@ -37,7 +37,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
name: "dxfPreset",
|
||||
ty: "string",
|
||||
default: "\"custom\"",
|
||||
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, PNG images); the options given override it",
|
||||
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, no images, no fill hatches); the options given override it",
|
||||
},
|
||||
FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018" },
|
||||
FormatOption {
|
||||
@@ -60,6 +60,18 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
default: "\"png\"",
|
||||
description: "png or jpeg: the files placed images are written to, next to the drawing",
|
||||
},
|
||||
FormatOption {
|
||||
name: "includeImages",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "placed images are written, linked to their files; false leaves them and their files out",
|
||||
},
|
||||
FormatOption {
|
||||
name: "includeHatches",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "filled areas get a solid hatch after their outlines; false writes the outlines alone",
|
||||
},
|
||||
FormatOption {
|
||||
name: "preserve",
|
||||
ty: "string",
|
||||
@@ -133,6 +145,8 @@ struct Params {
|
||||
scale_lineweights: Option<bool>,
|
||||
colors: Option<Value>,
|
||||
raster_format: Option<String>,
|
||||
include_images: Option<bool>,
|
||||
include_hatches: Option<bool>,
|
||||
preserve: Option<String>,
|
||||
alter_paths: Option<bool>,
|
||||
outline_text: Option<bool>,
|
||||
@@ -176,6 +190,8 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights),
|
||||
colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?,
|
||||
raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?,
|
||||
include_images: q.include_images.unwrap_or(d.include_images),
|
||||
include_hatches: q.include_hatches.unwrap_or(d.include_hatches),
|
||||
preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
|
||||
alter_paths: q.alter_paths.unwrap_or(d.alter_paths),
|
||||
outline_text: q.outline_text.unwrap_or(d.outline_text),
|
||||
|
||||
@@ -1034,11 +1034,47 @@ pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value>
|
||||
let plan = save_plan(s, mode, p)?;
|
||||
let job = save_job(s, plan)?;
|
||||
let uid = s.doc()?.uid;
|
||||
let out = job.write_streamed(&mut super::write_file_with)?;
|
||||
let mut out = job.write_streamed(&mut super::write_file_with)?;
|
||||
job.complete(s, uid);
|
||||
leave_out_unreadable_save_paths(&mut out, str_param(p, "path"));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The reply `out` of a save with the `path` param `given`, as the request being served may see it
|
||||
/// ([`super::access::shown`]). A save without a path writes the document's own file: its `path` is
|
||||
/// left out, and the `files` and `linked` written beside it are named by their file names, when they
|
||||
/// are outside the read roots. The suggested `folder` of a reply without a path is left out when it
|
||||
/// is outside them. Without roots in force `out` is unchanged.
|
||||
pub fn leave_out_unreadable_save_paths(out: &mut Value, given: Option<&str>) {
|
||||
use super::access::{shown, shown_path};
|
||||
|
||||
if crate::file_access::current().is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(o) = out.as_object_mut() else { return };
|
||||
if o.get("folder").and_then(Value::as_str).is_some_and(|f| !shown(f)) {
|
||||
o.remove("folder");
|
||||
}
|
||||
// Every path the reply names then is the one the client gave, or beside it.
|
||||
if given.is_some_and(|g| !g.is_empty()) {
|
||||
return;
|
||||
}
|
||||
if o.get("path").and_then(Value::as_str).is_some_and(|p| !shown(p)) {
|
||||
o.remove("path");
|
||||
}
|
||||
for key in ["files", "linked"] {
|
||||
if let Some(Value::Array(rows)) = o.get_mut(key) {
|
||||
for row in rows {
|
||||
if let Value::String(p) = row
|
||||
&& !shown(p)
|
||||
{
|
||||
*row = json!(shown_path(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn can_revert(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
match (&st.path, st.is_dirty()) {
|
||||
@@ -1125,7 +1161,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -644,12 +644,86 @@ impl Output {
|
||||
/// File → Export for Screens: [`export`] (over the settings of `exportPreset`, when given), with
|
||||
/// the params remembered in the document (`document.exportSettings`).
|
||||
pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A folder the client gave, as against the one its `exportPreset` keeps.
|
||||
let given = p.get("folder").is_some();
|
||||
let p = with_preset(s, p)?;
|
||||
let r = export(s, &p)?;
|
||||
let hidden = if given { None } else { str_param(&p, "folder").filter(|f| !f.is_empty() && !super::access::shown(f)) };
|
||||
let mut r = export(s, &p).map_err(|e| match hidden {
|
||||
Some(folder) => leave_out_folder_from_error(e, folder),
|
||||
None => e,
|
||||
})?;
|
||||
remember(s, &p);
|
||||
if !given && let Some(folder) = str_param(&p, "folder").filter(|f| !f.is_empty()) {
|
||||
leave_out_unreadable_folder(&mut r, folder);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// An error of an export into `folder`, a folder outside the read roots that the client did not
|
||||
/// give: `folder` as the path the error is about names it by its own name
|
||||
/// ([`super::access::shown_path`]), and the rest of the message stays.
|
||||
fn leave_out_folder_from_error(e: EngineError, folder: &str) -> EngineError {
|
||||
let name = super::access::shown_path(folder);
|
||||
match e {
|
||||
EngineError::Other(msg) => EngineError::Other(leave_out_folder_from_message(&msg, folder, &name)),
|
||||
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: leave_out_folder_from_message(&msg, folder, &name) },
|
||||
e => e,
|
||||
}
|
||||
}
|
||||
|
||||
/// `msg` with `folder` given as `name` where it begins a path the message is about: at the start
|
||||
/// of `msg` (`<path>: <reason>`), after a `: ` (`... outside the write root <root>: <path>`) or
|
||||
/// after `cannot resolve `, followed by the end, a separator, a `:` or a space. A root the message
|
||||
/// names stays whole, even one inside `folder`.
|
||||
fn leave_out_folder_from_message(msg: &str, folder: &str, name: &str) -> String {
|
||||
const BEFORE: [&str; 2] = [": ", "cannot resolve "];
|
||||
let mut out = String::with_capacity(msg.len());
|
||||
let mut rest = msg;
|
||||
loop {
|
||||
if let Some(after) = rest.strip_prefix(folder)
|
||||
&& after.chars().next().is_none_or(|c| matches!(c, '/' | '\\' | ':' | ' '))
|
||||
{
|
||||
out.push_str(name);
|
||||
rest = after;
|
||||
}
|
||||
let Some((i, len)) = BEFORE.iter().filter_map(|b| rest.find(b).map(|i| (i, b.len()))).min() else { break };
|
||||
out.push_str(&rest[..i + len]);
|
||||
rest = &rest[i + len..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The reply `r` of an export into `folder`, a folder the client did not give, as the request being
|
||||
/// served may see it: when `folder` is outside the read roots ([`super::access::shown`]), the ZIP's
|
||||
/// `path` is left out and `files` names each file written relative to `folder` (`2x/Logo@2x.png`),
|
||||
/// as the reply of an export to a ZIP names them.
|
||||
fn leave_out_unreadable_folder(r: &mut Value, folder: &str) {
|
||||
if super::access::shown(folder) {
|
||||
return;
|
||||
}
|
||||
let Some(o) = r.as_object_mut() else { return };
|
||||
o.remove("path");
|
||||
let inside = format!("{folder}/");
|
||||
if let Some(Value::Array(files)) = o.get_mut("files") {
|
||||
for file in files {
|
||||
// A ZIP's files are named relative to it already.
|
||||
if let Some(name) = file.as_str().and_then(|path| path.strip_prefix(&inside)) {
|
||||
*file = json!(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Export settings kept in the document or a preset, as the request being served may see them: a
|
||||
/// `folder` outside the read roots ([`super::access::shown`]) is left out.
|
||||
fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
|
||||
if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) {
|
||||
settings.remove("folder");
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
// ---------- export presets ----------
|
||||
|
||||
/// A saved batch export: what to write and how to name and sort it, to use again
|
||||
@@ -727,7 +801,13 @@ pub fn preset_list(saved: &[ScreenExportPreset]) -> Value {
|
||||
}
|
||||
|
||||
pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "presets": preset_list(&s.prefs.screen_export_presets) }))
|
||||
let saved: Vec<ScreenExportPreset> = s
|
||||
.prefs
|
||||
.screen_export_presets
|
||||
.iter()
|
||||
.map(|p| ScreenExportPreset { name: p.name.clone(), settings: leave_out_unreadable_settings_folder(p.settings.clone()) })
|
||||
.collect();
|
||||
Ok(json!({ "presets": preset_list(&saved) }))
|
||||
}
|
||||
|
||||
/// The [`PRESET_KEYS`] of `given`, refused as an error of command `cmd` when an export would
|
||||
@@ -831,6 +911,8 @@ pub(super) fn presets_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(too_many());
|
||||
}
|
||||
let count = presets.len();
|
||||
let presets: Vec<ScreenExportPreset> =
|
||||
presets.into_iter().map(|p| ScreenExportPreset { settings: leave_out_unreadable_settings_folder(p.settings), ..p }).collect();
|
||||
let text = serde_json::to_string_pretty(&PresetFile { format: PRESET_FILE_FORMAT.into(), presets }).map_err(|e| bad(EXPORT, e.to_string()))?;
|
||||
if text.len() > MAX_PRESET_FILE_BYTES {
|
||||
return Err(bad(EXPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes")));
|
||||
@@ -1388,12 +1470,31 @@ pub(crate) fn store_settings(s: &mut Session, mut settings: Map<String, Value>)
|
||||
|
||||
/// `document.exportSettings`: the Export for Screens settings the document last exported with.
|
||||
pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "settings": s.doc()?.doc.export_settings }))
|
||||
Ok(json!({ "settings": leave_out_unreadable_settings_folder(s.doc()?.doc.export_settings.clone()) }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Output, ScreenSize, safe_file_name};
|
||||
use super::{Output, ScreenSize, leave_out_folder_from_message, safe_file_name};
|
||||
|
||||
/// A hidden export folder is named by its name where a message is about it, and a root that
|
||||
/// starts with the same text, or a longer path, stays whole.
|
||||
#[test]
|
||||
fn a_hidden_folder_is_named_by_its_name_in_a_message() {
|
||||
let f = "/work/out";
|
||||
let cases = [
|
||||
(
|
||||
"automation path rejected: outside the write root /work/out/in: /work/out",
|
||||
"automation path rejected: outside the write root /work/out/in: out",
|
||||
),
|
||||
("automation path rejected: cannot resolve /work/out: denied", "automation path rejected: cannot resolve out: denied"),
|
||||
("/work/out/2x/a.png: disk full", "out/2x/a.png: disk full"),
|
||||
("automation path rejected: outside the write root /a: /work/outer", "automation path rejected: outside the write root /a: /work/outer"),
|
||||
];
|
||||
for (msg, want) in cases {
|
||||
assert_eq!(leave_out_folder_from_message(msg, f, "out"), want, "{msg}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Files given one name are numbered in turn, each numbering going on from the last one (so
|
||||
/// thousands of them don't each try every number used before), and a file asking again for
|
||||
|
||||
@@ -48,6 +48,19 @@ fn image_of(s: &Session) -> vectorcraft_doc::ImageObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path outside a confined request's read roots shows as its file name, after the last `/` or `\`
|
||||
/// on every platform; one that ends in no name shows as nothing. Without roots it shows whole.
|
||||
#[test]
|
||||
fn a_hidden_path_shows_as_its_file_name_on_every_platform() {
|
||||
let windows = "C:\\Users\\someone\\art\\red.png";
|
||||
crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || {
|
||||
for (path, name) in [("/home/someone/art/red.png", "red.png"), (windows, "red.png"), ("/home/someone/..", ""), ("C:\\Users\\someone\\", "")] {
|
||||
assert_eq!(shown_path(path), name, "{path}");
|
||||
}
|
||||
});
|
||||
assert_eq!(shown_path(windows), windows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_every_readable_format() {
|
||||
let mut s = session(200.0, 100.0, 1);
|
||||
|
||||
@@ -84,6 +84,11 @@ fn the_cnc_preset_sets_the_options_that_are_not_given() {
|
||||
true
|
||||
)
|
||||
);
|
||||
assert_eq!((o.include_images, o.include_hatches), (false, false), "CNC / CAM leaves out images and fill hatches");
|
||||
let given = dxf::options(&json!({"dxfPreset": "cnc", "includeImages": true, "includeHatches": true})).unwrap();
|
||||
assert_eq!((given.include_images, given.include_hatches), (true, true), "the options given override it");
|
||||
let custom = dxf::options(&json!({})).unwrap();
|
||||
assert_eq!((custom.include_images, custom.include_hatches), (true, true), "Custom keeps both");
|
||||
assert_eq!(dxf::options(&json!({})).unwrap().version, vectorcraft_cad::DxfVersion::R2018, "custom by default");
|
||||
let e = s.execute("document.exportDxf", &json!({"dxfPreset": "laser"})).unwrap_err().to_string();
|
||||
assert!(e.contains("custom or cnc"), "{e}");
|
||||
@@ -151,6 +156,44 @@ fn placed_images_come_back_as_linked_files() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// `includeImages` and `includeHatches` leave out placed images (with their files) and fill
|
||||
/// hatches, each on its own, through both commands, with and without a path; CNC / CAM leaves
|
||||
/// out both, and the options given override it.
|
||||
#[test]
|
||||
fn placed_images_and_fill_hatches_can_be_left_out() {
|
||||
let mut s = super::tests_svg::image_session();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
|
||||
let counts = |r: &Value| {
|
||||
let e = entities(&text(r));
|
||||
let n = |k: &str| e.iter().filter(|x| *x == k).count();
|
||||
(n("LWPOLYLINE"), n("HATCH"), n("IMAGE"), r.get("linked").and_then(Value::as_array).map_or(0, Vec::len))
|
||||
};
|
||||
let warned = |r: &Value, w: &str| r["warnings"].as_array().unwrap().iter().any(|x| x.as_str().is_some_and(|x| x.starts_with(w)));
|
||||
let all = s.execute("document.export", &json!({"format": "dxf"})).unwrap();
|
||||
assert_eq!(counts(&all), (1, 1, 1, 1));
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "includeImages": false})).unwrap();
|
||||
assert_eq!(counts(&r), (1, 1, 0, 0));
|
||||
assert!(warned(&r, "placed images are left out") && !warned(&r, "fill hatches"), "{r}");
|
||||
let r = s.execute("document.exportDxf", &json!({"includeHatches": false})).unwrap();
|
||||
assert_eq!(counts(&r), (1, 0, 1, 1));
|
||||
assert!(warned(&r, "fill hatches are left out") && !warned(&r, "placed images"), "{r}");
|
||||
let r = s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap();
|
||||
assert_eq!(counts(&r), (1, 0, 0, 0));
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "dxfPreset": "cnc", "includeImages": true})).unwrap();
|
||||
assert_eq!(counts(&r), (1, 0, 1, 1));
|
||||
// With a path, no image file is written next to the drawing.
|
||||
let dir = std::env::temp_dir().join(format!("vc-dxf-out-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("cut.dxf").to_string_lossy().to_string();
|
||||
let r = s.execute("document.exportDxf", &json!({"path": path, "dxfPreset": "cnc"})).unwrap();
|
||||
assert!(r.get("linked").is_none(), "{r}");
|
||||
let files: Vec<String> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().to_string()).collect();
|
||||
assert_eq!(files, ["cut.dxf"]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Two placed images whose pixel data can't be decoded are left out of the drawing and get no
|
||||
/// linked file, and `warnings` holds the note raster exports give, once, without naming either
|
||||
/// image's key.
|
||||
@@ -181,6 +224,8 @@ fn bad_dxf_options_are_refused() {
|
||||
json!({"rasterFormat": "gif"}),
|
||||
json!({"preserve": "both"}),
|
||||
json!({"alterPaths": "yes"}),
|
||||
json!({"includeImages": "no"}),
|
||||
json!({"includeHatches": 0}),
|
||||
] {
|
||||
let e = s.execute("document.exportDxf", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("DXF"), "{p}: {e}");
|
||||
@@ -203,6 +248,8 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
"scaleLineweights",
|
||||
"colors",
|
||||
"rasterFormat",
|
||||
"includeImages",
|
||||
"includeHatches",
|
||||
"preserve",
|
||||
"alterPaths",
|
||||
"outlineText",
|
||||
|
||||
@@ -667,6 +667,118 @@ fn a_numbered_file_is_written_into_the_first_rows_folder() {
|
||||
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder");
|
||||
}
|
||||
|
||||
/// An export into the folder an export preset keeps, for a client whose read roots don't hold that
|
||||
/// folder: the reply leaves out the ZIP's path and names the files relative to the folder. A folder
|
||||
/// inside the read roots, and one the client gives, stay whole.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_presets_folder_outside_the_read_root_is_left_out_of_the_reply() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let mut s = session(1);
|
||||
let tmp = Folder::new("preset-roots");
|
||||
let (inside, out) = (tmp.0.join("in"), tmp.0.join("out"));
|
||||
for f in [&inside, &out] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let folder = out.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "png", "folder": "1x"}], "subfolders": true, "folder": folder});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
|
||||
let write_only = AutomationRoots::new(&[inside.as_path()], &[out.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[out.as_path()]).unwrap();
|
||||
let run = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, p: Value| confine(roots.as_ref(), || export(s, p));
|
||||
|
||||
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept"}));
|
||||
assert_eq!(r["files"], json!(["1x/Artboard-1.png"]), "{r}");
|
||||
assert!(out.join("1x/Artboard-1.png").is_file());
|
||||
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "zip": true}));
|
||||
assert_eq!((r.get("path"), &r["files"]), (None, &json!(["1x/Artboard-1.png"])), "{r}");
|
||||
assert!(!r.to_string().contains(&folder), "{r}");
|
||||
// Inside the read roots, or given by the client: whole.
|
||||
assert_eq!(run(&mut s, &both, json!({"exportPreset": "Kept"}))["files"], json!([format!("{folder}/1x/Artboard-1.png")]));
|
||||
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder, "zip": true}));
|
||||
assert!(r["path"].as_str().is_some_and(|p| p.starts_with(&format!("{folder}/")) && p.ends_with(".zip")), "{r}");
|
||||
}
|
||||
|
||||
/// An export into the folder an export preset keeps, refused because that folder is outside the
|
||||
/// client's read and write roots: the error names the folder by its name only. A folder the client
|
||||
/// gives stays whole in the error.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_refused_export_into_a_presets_folder_outside_the_read_root_names_it_by_its_name() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let mut s = session(1);
|
||||
let tmp = Folder::new("preset-refused");
|
||||
let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out"));
|
||||
for f in [&inside, &out] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let folder = out.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "png"}], "folder": folder});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
|
||||
let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
|
||||
let mut run = |p: Value| confine(confined.as_ref(), || s.execute("document.exportForScreens", &p)).unwrap_err().to_string();
|
||||
|
||||
let e = run(json!({"exportPreset": "Kept"}));
|
||||
assert!(e.contains("outside the write root") && e.contains("kept-out") && !e.contains(&folder), "{e}");
|
||||
let e = run(json!({"exportPreset": "Kept", "folder": folder}));
|
||||
assert!(e.contains(&folder), "{e}");
|
||||
assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "nothing written");
|
||||
// A preset folder that holds the write root: the root stays whole in the error.
|
||||
let parent = tmp.0.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "png"}], "folder": parent});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Parent", "settings": settings})).unwrap();
|
||||
let e = confine(confined.as_ref(), || s.execute("document.exportForScreens", &json!({"exportPreset": "Parent"}))).unwrap_err().to_string();
|
||||
let root = inside.display().to_string();
|
||||
let name = tmp.0.file_name().unwrap().to_string_lossy().into_owned();
|
||||
assert!(e.contains(&format!("root {root}: {name}")), "{e}");
|
||||
}
|
||||
|
||||
/// The export settings the document keeps and the saved presets, read by a client whose read roots
|
||||
/// don't hold their folder: `document.exportSettings`, `document.exportPresets.list` and
|
||||
/// `document.exportPresets.export` (as data and as a file) leave out that folder and keep the rest.
|
||||
/// Inside the read roots the folder stays.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn kept_settings_leave_out_a_folder_outside_the_read_root() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let mut s = session(1);
|
||||
let tmp = Folder::new("settings-roots");
|
||||
let (inside, out) = (tmp.0.join("in"), tmp.0.join("out"));
|
||||
for f in [&inside, &out] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let folder = out.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "svg"}], "folder": folder});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
|
||||
export(&mut s, json!({"exportPreset": "Kept"}));
|
||||
let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[inside.as_path()]).unwrap();
|
||||
let ask = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, cmd: &str, p: Value| {
|
||||
confine(roots.as_ref(), || s.execute(cmd, &p).unwrap())
|
||||
};
|
||||
let saved = |list: &Value| list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Kept").unwrap()["settings"].clone();
|
||||
|
||||
let r = ask(&mut s, &confined, "document.exportSettings", json!({}));
|
||||
assert_eq!((r["settings"].get("folder"), &r["settings"]["formats"]), (None, &json!([{"format": "svg"}])), "{r}");
|
||||
let r = ask(&mut s, &confined, "document.exportPresets.list", json!({}));
|
||||
assert_eq!(saved(&r), json!({"formats": [{"format": "svg"}]}), "{r}");
|
||||
let r = ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"]}));
|
||||
let data = r["data"].as_str().unwrap();
|
||||
assert!(!data.contains(&folder) && data.contains("svg"), "{data}");
|
||||
let file = inside.join("kept.vcexportpresets");
|
||||
let path = file.to_string_lossy().replace('\\', "/");
|
||||
ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"], "path": path}));
|
||||
assert!(!std::fs::read_to_string(&file).unwrap().contains(&folder));
|
||||
|
||||
// Inside the read roots: whole.
|
||||
assert_eq!(ask(&mut s, &both, "document.exportSettings", json!({}))["settings"]["folder"], json!(folder));
|
||||
assert_eq!(saved(&ask(&mut s, &both, "document.exportPresets.list", json!({})))["folder"], json!(folder));
|
||||
assert!(ask(&mut s, &both, "document.exportPresets.export", json!({"names": ["Kept"]}))["data"].as_str().unwrap().contains(&folder));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_settings_apply_to_their_rows_and_rows_win() {
|
||||
let mut s = session(1);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use vectorcraft_doc::live::BlendSpineMode;
|
||||
|
||||
use super::common::{
|
||||
DEFAULT_DISTANCE, DEFAULT_STEPS, ease_param, fix_ids, ids_json, is_blend, orientation_param, percent_param, roots_param, selected_of,
|
||||
spacing_param, starts_param, wrap,
|
||||
@@ -61,6 +63,19 @@ fn extend_spine(spec: &mut BlendSpec, old: &[Arc<Node>], old_spec: &BlendSpec, k
|
||||
spec.spine = Some(path);
|
||||
}
|
||||
|
||||
/// Does `p` set easing (`easingType` or `ramp`)? Easing needs a spine.
|
||||
fn gives_easing(p: &Value) -> bool {
|
||||
["easingType", "ramp"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null()))
|
||||
}
|
||||
|
||||
/// The Create Spine mode `p` gives as `key`, or `current` when it is omitted or null.
|
||||
fn spine_mode_param(p: &Value, cmd: &str, key: &str, current: BlendSpineMode) -> Result<BlendSpineMode> {
|
||||
match p.get(key).filter(|v| !v.is_null()) {
|
||||
None => Ok(current),
|
||||
Some(v) => v.as_str().and_then(BlendSpineMode::from_id).ok_or_else(|| bad(cmd, format!("`{key}` must be one of auto, always, never"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.make";
|
||||
let roots = roots_param(s, p)?;
|
||||
@@ -69,16 +84,22 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let starts = starts_param(p, &roots)?;
|
||||
let base = first_blend(&s.doc()?.doc, &roots);
|
||||
let defaults = s.prefs.blend_options.unwrap_or_default();
|
||||
// Create Spine applies to a new blend; one taking more keys keeps whether it has a spine.
|
||||
let create_spine = spine_mode_param(p, C, "createSpine", defaults.create_spine)?;
|
||||
let cur = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation },
|
||||
_ => s.prefs.blend_options.unwrap_or_default(),
|
||||
Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation, ..defaults },
|
||||
_ => defaults,
|
||||
};
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let (ease0, color0) = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift),
|
||||
_ => Default::default(),
|
||||
let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine),
|
||||
_ => (Default::default(), 0.0, !create_spine.creates_spine()),
|
||||
};
|
||||
if no_spine && gives_easing(p) {
|
||||
return Err(bad(C, "the blend has no spine"));
|
||||
}
|
||||
let ease = ease_param(p, C, ease0)?;
|
||||
let color_shift = percent_param(p, C, "colorShift", color0, -100.0)?;
|
||||
let id = s.edit("Make Blend", |d, sel| {
|
||||
@@ -91,7 +112,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.knockout = vectorcraft_doc::Knockout::On;
|
||||
n
|
||||
});
|
||||
let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, ..Default::default() };
|
||||
let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, no_spine, ..Default::default() };
|
||||
if let NodeKind::Blend { children: old, spec: old_spec } = &n.kind {
|
||||
extend_spine(&mut spec, old, old_spec, &children);
|
||||
}
|
||||
@@ -346,9 +367,12 @@ pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Nothing to set them on: the options new blends start with (easing is per blend).
|
||||
let d = s.prefs.blend_options.unwrap_or_default();
|
||||
let spacing = spacing_param(p, C, d.spacing)?;
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation) });
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d });
|
||||
return Ok(json!({ "defaults": true }));
|
||||
};
|
||||
if gives_easing(p) && any_without_spine(s) {
|
||||
return Err(bad(C, "the blend has no spine"));
|
||||
}
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let ease = ease_param(p, C, cur.ease)?;
|
||||
@@ -384,6 +408,7 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
v["colorShift"] = json!(spec.color_shift);
|
||||
v["starts"] = json!((0..keys.len()).map(|i| spec.start(i)).collect::<Vec<_>>());
|
||||
v["keys"] = json!(keys.iter().map(|k| k.0).collect::<Vec<_>>());
|
||||
v["hasSpine"] = json!(!spec.no_spine);
|
||||
if let Some(NodeKind::Blend { children, .. }) = s.doc()?.doc.node(id).map(|n| &n.kind)
|
||||
&& let Some((path, anchors)) = live::blend_spine(children, &spec)
|
||||
&& let Some(sp) = path.subpaths.first()
|
||||
@@ -403,6 +428,19 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The Blend panel's Create Spine: with `mode`, sets whether new blends get a spine; without, reads
|
||||
/// it. A tool setting kept with the preferences, not an undo step; blends already made keep theirs.
|
||||
pub(super) fn blend_create_spine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.createSpine";
|
||||
let mut d = s.prefs.blend_options.unwrap_or_default();
|
||||
let mode = spine_mode_param(p, C, "mode", d.create_spine)?;
|
||||
if mode != d.create_spine {
|
||||
d.create_spine = mode;
|
||||
s.prefs.blend_options = Some(d);
|
||||
}
|
||||
Ok(json!({ "mode": mode.id() }))
|
||||
}
|
||||
|
||||
pub(super) fn blend_expand(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let blends = selected_of(s, is_blend);
|
||||
let ids = s.edit("Expand Blend", |d, sel| {
|
||||
@@ -507,6 +545,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let spine = d.node(path).and_then(|n| n.path_data().cloned()).ok_or(EngineError::NoNode(path))?;
|
||||
d.remove(path)?;
|
||||
if let Some(NodeKind::Blend { children, spec }) = d.node_mut(b).map(|n| &mut n.kind) {
|
||||
// A blend made without a spine gets this one.
|
||||
spec.no_spine = false;
|
||||
spec.spine = Some(spine);
|
||||
spec.key_anchors.clear();
|
||||
keys_to_spine(children, spec);
|
||||
@@ -517,7 +557,16 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Is any selected blend one made without a spine?
|
||||
fn any_without_spine(s: &Session) -> bool {
|
||||
let Ok(st) = s.doc() else { return false };
|
||||
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
|
||||
}
|
||||
|
||||
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if any_without_spine(s) {
|
||||
return Err(bad("object.blend.reverseSpine", "the blend has no spine"));
|
||||
}
|
||||
edit_blends(s, "Reverse Spine", |children, spec| {
|
||||
if spec.spine.is_some() && pin(children, spec) {
|
||||
// The keys keep their anchors, which now count from the other end.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::blend::{
|
||||
blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, blend_reverse_stack,
|
||||
spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment,
|
||||
blend_create_spine, blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine,
|
||||
blend_reverse_stack, spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment,
|
||||
};
|
||||
use super::common::{has_blend, has_envelope, has_mesh};
|
||||
use super::envelope::{
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Blend"],
|
||||
Some("Cmd+Alt+B"),
|
||||
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name and transparency) instead of nesting → {id}",
|
||||
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
|
||||
has_doc,
|
||||
blend_make
|
||||
),
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Release",
|
||||
["Object", "Blend"],
|
||||
Some("Cmd+Alt+Shift+B"),
|
||||
"{} release the selected blends: the key objects come back and the spine stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}",
|
||||
"{} release the selected blends: the key objects come back and the spine (if the blend has one) stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}",
|
||||
has_blend,
|
||||
blend_release
|
||||
),
|
||||
@@ -40,6 +40,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
blend_options
|
||||
),
|
||||
cmd!(
|
||||
"object.blend.createSpine",
|
||||
"Create Spine",
|
||||
[],
|
||||
None,
|
||||
"{mode?: auto|always|never} the Blend panel's Create Spine: whether new blends get a spine (auto and always: the straight lines between the key centers, as before; never: no spine to show, edit, reverse or release, and no easing, until Replace Spine gives one); with no `mode`, reads it; blends already made keep theirs (a tool setting kept with the preferences, not an undo step) → {mode}",
|
||||
always,
|
||||
blend_create_spine
|
||||
),
|
||||
cmd!(
|
||||
"object.blend.expand",
|
||||
"Expand",
|
||||
@@ -54,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Spine",
|
||||
["Object", "Blend"],
|
||||
None,
|
||||
"{} use the selected path as the spine of the selected blend (the path is consumed)",
|
||||
"{} use the selected path as the spine of the selected blend (the path is consumed); a blend made without a spine gets this one",
|
||||
has_blend,
|
||||
blend_replace_spine
|
||||
),
|
||||
@@ -63,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reverse Spine",
|
||||
["Object", "Blend"],
|
||||
None,
|
||||
"{} reverse the order of the key objects along the spine",
|
||||
"{} reverse the order of the key objects along the spine; an error when a selected blend has no spine",
|
||||
has_blend,
|
||||
blend_reverse_spine
|
||||
),
|
||||
@@ -72,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blend Info",
|
||||
[],
|
||||
None,
|
||||
"{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}",
|
||||
"{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], hasSpine?: false for a blend made without a spine (no `spine` then), spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}",
|
||||
always,
|
||||
blend_info
|
||||
),
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reflect…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg, origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
reflect
|
||||
),
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_doc::{Document, LinkInfo};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::fileio::{create_dir, write_file};
|
||||
use super::fileio::{create_dir, document_path, shown_link, shown_path, write_file};
|
||||
use super::links::LinkBase;
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param, unique_name};
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Package",
|
||||
[],
|
||||
None,
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder",
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name",
|
||||
has_doc,
|
||||
package
|
||||
)]
|
||||
@@ -178,8 +178,10 @@ impl<'a> Collector<'a> {
|
||||
|
||||
/// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the
|
||||
/// copy of `source` finds it only by its name, beside it.
|
||||
/// `path` is the link's path as the warning names it.
|
||||
fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) {
|
||||
if Path::new(copy).file_name().and_then(std::ffi::OsStr::to_str) != Some(name) {
|
||||
let source = shown_path(source);
|
||||
let message = format!(
|
||||
"{path}: copied as {copy}; the copy of {source} looks for it as {name} and shows the file of that name, if any, else its preview"
|
||||
);
|
||||
@@ -207,11 +209,13 @@ impl<'a> Collector<'a> {
|
||||
let section = self.sections.len();
|
||||
self.sections.push(vec![]);
|
||||
let mut lines = vec![];
|
||||
// The packaged document's sections read as before; a placed document's name its file.
|
||||
// The packaged document's sections read as before; a placed document's name its file. The
|
||||
// report and the warnings name a file outside a confined request's read roots by its name.
|
||||
let shown_source = shown_path(source);
|
||||
let heading = |lines: &mut Vec<String>, title: &str| {
|
||||
lines.push(title.into());
|
||||
if depth > 0 {
|
||||
lines.push(format!("Document: {source}"));
|
||||
lines.push(format!("Document: {shown_source}"));
|
||||
}
|
||||
};
|
||||
// A file's saved path is only meaningful inside its own document.
|
||||
@@ -243,17 +247,21 @@ impl<'a> Collector<'a> {
|
||||
heading(&mut lines, "LINKED FILES");
|
||||
for file in linked_files(doc) {
|
||||
let found_path = file.found_path.as_deref().unwrap_or(&file.path);
|
||||
// The stored path, whole when the place it names (read from this document's folder) is
|
||||
// inside the read roots. A file found elsewhere does not show a stored path outside them.
|
||||
let resolved = document_path(&file.path, Some(source)).ok();
|
||||
let shown = shown_link(&file.path, resolved.as_deref()).into_owned();
|
||||
if let Some(ancestor) = self.visiting.get(found_path).cloned() {
|
||||
// The ancestor is already included (possibly the root document). A
|
||||
// cyclic reference cannot have a final content hash until both files
|
||||
// have been written, so leave its size/hash unspecified, not stale.
|
||||
self.warn(&mut lines, format!("{}: circular placed-document link to {ancestor}; stopped following the cycle", file.path));
|
||||
self.warn(&mut lines, format!("{shown}: circular placed-document link to {ancestor}; stopped following the cycle"));
|
||||
local.insert(file.path.clone(), Copied { name: ancestor, size: None, hash: None });
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = self.copies.get(found_path).cloned() {
|
||||
if by_name {
|
||||
self.renamed(&mut lines, source, &file.path, &file.name, &existing.name);
|
||||
self.renamed(&mut lines, source, &shown, &file.name, &existing.name);
|
||||
}
|
||||
// Another document may place other pages of a PDF copied already.
|
||||
if self.opts.copy_fonts
|
||||
@@ -265,8 +273,8 @@ impl<'a> Collector<'a> {
|
||||
continue;
|
||||
}
|
||||
let Some(mut bytes) = file.bytes else {
|
||||
lines.push(format!("{}: not found ({}), not copied", file.name, file.path));
|
||||
self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({source})", file.name) });
|
||||
lines.push(format!("{}: not found ({shown}), not copied", file.name));
|
||||
self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({shown_source})", file.name) });
|
||||
continue;
|
||||
};
|
||||
if self.copies.len() >= 10_000 {
|
||||
@@ -277,7 +285,7 @@ impl<'a> Collector<'a> {
|
||||
let unique = free_name(&name, if self.opts.links_folder { &mut self.link_names } else { &mut self.taken });
|
||||
let destination_file = format!("{dir}{unique}");
|
||||
if by_name {
|
||||
self.renamed(&mut lines, source, &file.path, &file.name, &destination_file);
|
||||
self.renamed(&mut lines, source, &shown, &file.name, &destination_file);
|
||||
}
|
||||
// A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file
|
||||
// read from its editing data links are copied beside it.
|
||||
@@ -285,7 +293,7 @@ impl<'a> Collector<'a> {
|
||||
let placed_file = pages.is_some();
|
||||
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path));
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
} else {
|
||||
self.collect(&mut art, found_path, &destination_file, depth + 1, true, None)?;
|
||||
}
|
||||
@@ -296,7 +304,7 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
if placed_file && super::place::document::is_native(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path));
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
} else {
|
||||
match vectorcraft_format::load_file(&bytes) {
|
||||
Ok(saved) => {
|
||||
@@ -320,8 +328,7 @@ impl<'a> Collector<'a> {
|
||||
Err(e) => self.warn(
|
||||
&mut lines,
|
||||
format!(
|
||||
"{}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked",
|
||||
file.path
|
||||
"{shown}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked"
|
||||
),
|
||||
),
|
||||
}
|
||||
@@ -329,7 +336,7 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
Err(e) => self.warn(
|
||||
&mut lines,
|
||||
format!("{}: unreadable linked document ({e}); copied unchanged, its own links were not collected", file.path),
|
||||
format!("{shown}: unreadable linked document ({e}); copied unchanged, its own links were not collected"),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -337,7 +344,7 @@ impl<'a> Collector<'a> {
|
||||
let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
|
||||
self.copies.insert(found_path.to_string(), copy.clone());
|
||||
local.insert(file.path.clone(), copy);
|
||||
lines.push(format!("{} → {destination_file}", file.path));
|
||||
lines.push(format!("{shown} → {destination_file}"));
|
||||
self.entries.push((destination_file, bytes));
|
||||
}
|
||||
lines.push(String::new());
|
||||
@@ -518,7 +525,7 @@ fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Res
|
||||
// The report.
|
||||
if let Some(info) = info {
|
||||
let report_name = free_name(&format!("{stem} Report.txt"), &mut taken);
|
||||
let mut text = format!("Package: {doc_name}\nFrom: {doc_path}\n\n");
|
||||
let mut text = format!("Package: {doc_name}\nFrom: {}\n\n", shown_path(&doc_path));
|
||||
lines.iter().for_each(|l| text.push_str(&format!("{l}\n")));
|
||||
text.push_str(&info);
|
||||
entries.push((report_name, text.into_bytes()));
|
||||
|
||||
@@ -23,8 +23,10 @@ pub struct BuiltinPatternLibrary {
|
||||
}
|
||||
|
||||
/// The built-in pattern libraries (Window → Swatch Libraries → Patterns), in menu order.
|
||||
pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] =
|
||||
&[BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns }];
|
||||
pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] = &[
|
||||
BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns },
|
||||
BuiltinPatternLibrary { id: "grit-textures", name: "Grit Textures", make: grit_textures },
|
||||
];
|
||||
|
||||
/// The library category of the built-in pattern libraries.
|
||||
pub const CATEGORY: &str = "patterns";
|
||||
@@ -154,6 +156,106 @@ fn geometric_patterns(d: &mut Document) {
|
||||
add(d, "Zigzag", 10.0, 8.0, TileType::Grid, vec![polygon(&[(0.0, 5.0), (5.0, 1.0), (10.0, 5.0), (10.0, 7.0), (5.0, 3.0), (0.0, 7.0)])]);
|
||||
}
|
||||
|
||||
/// SplitMix64, a small generator with a fixed seed per pattern, so a grit pattern draws the same
|
||||
/// marks every time it is made.
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// A number from `lo` up to, but not including, `hi`.
|
||||
fn range(&mut self, lo: f64, hi: f64) -> f64 {
|
||||
lo + (self.next() >> 11) as f64 / (1u64 << 53) as f64 * (hi - lo)
|
||||
}
|
||||
}
|
||||
|
||||
/// A round dot of radius `r` at (`x`, `y`).
|
||||
fn dot(x: f64, y: f64, r: f64) -> PathData {
|
||||
shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r))
|
||||
}
|
||||
|
||||
/// An irregular fleck of four to seven corners about (`x`, `y`), at most `r` from it.
|
||||
fn fleck(rng: &mut SplitMix64, x: f64, y: f64, r: f64) -> PathData {
|
||||
use std::f64::consts::TAU;
|
||||
let n = 4 + (rng.next() % 4) as usize;
|
||||
let turn = rng.range(0.0, TAU);
|
||||
let points: Vec<(f64, f64)> = (0..n)
|
||||
.map(|k| {
|
||||
let a = turn + TAU * (k as f64 + rng.range(-0.3, 0.3)) / n as f64;
|
||||
let reach = r * rng.range(0.55, 1.0);
|
||||
(x + reach * a.cos(), y + reach * a.sin())
|
||||
})
|
||||
.collect();
|
||||
polygon(&points)
|
||||
}
|
||||
|
||||
/// A thin straight scratch `len` long and `width` wide, centered on (`x`, `y`) at a random angle.
|
||||
fn scratch(rng: &mut SplitMix64, x: f64, y: f64, len: f64, width: f64) -> PathData {
|
||||
let (s, c) = rng.range(0.0, std::f64::consts::PI).sin_cos();
|
||||
let (hx, hy, wx, wy) = (c * len / 2.0, s * len / 2.0, -s * width / 2.0, c * width / 2.0);
|
||||
polygon(&[(x - hx - wx, y - hy - wy), (x + hx - wx, y + hy - wy), (x + hx + wx, y + hy + wy), (x - hx + wx, y - hy + wy)])
|
||||
}
|
||||
|
||||
/// A grit pattern of `count` marks scattered over a square grid tile of side `size`, drawn from
|
||||
/// `seed` (`mark` draws one at a point). A mark that reaches past an edge is kept whole: the tiling
|
||||
/// draws the part outside the tile on the next tile, so the tiles join without a seam.
|
||||
fn grit(d: &mut Document, name: &str, size: f64, seed: u64, count: usize, mark: impl Fn(&mut SplitMix64, f64, f64) -> PathData) {
|
||||
let mut rng = SplitMix64(seed);
|
||||
let marks = (0..count)
|
||||
.map(|_| {
|
||||
let (x, y) = (rng.range(0.0, size), rng.range(0.0, size));
|
||||
mark(&mut rng, x, y)
|
||||
})
|
||||
.collect();
|
||||
add(d, name, size, size, TileType::Grid, marks);
|
||||
}
|
||||
|
||||
/// Grit Textures: seamless black grain, grit, sand, speckle, stipple, scratch and fleck textures on
|
||||
/// a clear background, each drawn from its own fixed seed.
|
||||
fn grit_textures(d: &mut Document) {
|
||||
grit(d, "Fine Grain", 24.0, 1, 320, |rng, x, y| dot(x, y, rng.range(0.15, 0.35)));
|
||||
grit(d, "Coarse Grit", 30.0, 2, 150, |rng, x, y| {
|
||||
let r = rng.range(0.45, 1.1);
|
||||
fleck(rng, x, y, r)
|
||||
});
|
||||
grit(d, "Sand", 24.0, 3, 280, |rng, x, y| {
|
||||
let r = rng.range(0.2, 0.45);
|
||||
fleck(rng, x, y, r)
|
||||
});
|
||||
grit(d, "Speckle", 30.0, 4, 90, |rng, x, y| dot(x, y, rng.range(0.3, 0.9)));
|
||||
// Stipple: one dot in each cell of a 12 × 12 grid, moved a little off the cell's center.
|
||||
let mut rng = SplitMix64(5);
|
||||
let (size, cells) = (24.0, 12);
|
||||
let step = size / f64::from(cells);
|
||||
let dots = (0..cells)
|
||||
.flat_map(|row| (0..cells).map(move |col| (col, row)))
|
||||
.map(|(col, row)| {
|
||||
let x = (f64::from(col) + 0.5) * step + rng.range(-0.3, 0.3) * step;
|
||||
let y = (f64::from(row) + 0.5) * step + rng.range(-0.3, 0.3) * step;
|
||||
dot(x, y, rng.range(0.3, 0.45))
|
||||
})
|
||||
.collect();
|
||||
add(d, "Stipple", size, size, TileType::Grid, dots);
|
||||
grit(d, "Scratches", 36.0, 6, 45, |rng, x, y| {
|
||||
let (len, width) = (rng.range(2.0, 7.0), rng.range(0.15, 0.35));
|
||||
scratch(rng, x, y, len, width)
|
||||
});
|
||||
grit(d, "Sparse Flecks", 36.0, 7, 32, |rng, x, y| {
|
||||
let r = rng.range(0.35, 0.8);
|
||||
fleck(rng, x, y, r)
|
||||
});
|
||||
grit(d, "Dense Flecks", 18.0, 8, 220, |rng, x, y| {
|
||||
let r = rng.range(0.2, 0.5);
|
||||
fleck(rng, x, y, r)
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -168,4 +270,60 @@ mod tests {
|
||||
assert_eq!(existing_pattern(&d, &lib, "Dots").as_deref(), expected, "{other}");
|
||||
}
|
||||
}
|
||||
|
||||
fn grit_doc() -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
grit_textures(&mut d);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grit_textures_draw_the_same_marks_every_time() {
|
||||
let (a, b) = (grit_doc(), grit_doc());
|
||||
assert_eq!(a.patterns.len(), 8);
|
||||
assert_eq!(a.patterns, b.patterns);
|
||||
}
|
||||
|
||||
/// Every grit tile is 18 to 36 pt with at most 600 marks, each with an area, touching the tile
|
||||
/// and near it. Marks reach past the edges, and the tiling draws a tile's art on the next tile
|
||||
/// across each edge a mark crosses. No mark is another mark moved by a whole tile, which the tiling would draw
|
||||
/// twice in one place.
|
||||
#[test]
|
||||
fn grit_tiles_join_without_a_seam() {
|
||||
let mut crossing = 0;
|
||||
for p in &grit_doc().patterns {
|
||||
let (w, h) = (p.width(), p.height());
|
||||
assert!((18.0..=36.0).contains(&w) && w == h && p.tile.x0 == 0.0 && p.tile.y0 == 0.0, "{}", p.name);
|
||||
assert!(!p.art.is_empty() && p.art.len() <= 600, "{}: {} marks", p.name, p.art.len());
|
||||
let bounds: Vec<Rect> = p
|
||||
.art
|
||||
.iter()
|
||||
.map(|n| match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Path { path, .. } => path.bounds().unwrap_or_else(|| panic!("{}: an empty mark", p.name)),
|
||||
_ => panic!("{}: a mark that is not a path", p.name),
|
||||
})
|
||||
.collect();
|
||||
let near = |a: &Rect, b: Rect| {
|
||||
(a.x0 - b.x0).abs() < 1e-9 && (a.y0 - b.y0).abs() < 1e-9 && (a.x1 - b.x1).abs() < 1e-9 && (a.y1 - b.y1).abs() < 1e-9
|
||||
};
|
||||
let band = p.tile.inflate(w / 4.0, h / 4.0);
|
||||
for b in &bounds {
|
||||
assert!(b.width() > 0.0 && b.height() > 0.0, "{}: {b:?}", p.name);
|
||||
assert!(b.x1 > 0.0 && b.y1 > 0.0 && b.x0 < w && b.y0 < h, "{}: {b:?} does not touch the tile", p.name);
|
||||
assert!(b.x0 >= band.x0 && b.y0 >= band.y0 && b.x1 <= band.x1 && b.y1 <= band.y1, "{}: {b:?} is too far out", p.name);
|
||||
// The tile past each edge the mark crosses draws this tile's art.
|
||||
let (dx, dy) = (f64::from(i8::from(b.x1 > w) - i8::from(b.x0 < 0.0)), f64::from(i8::from(b.y1 > h) - i8::from(b.y0 < 0.0)));
|
||||
for (x, y) in [(dx, 0.0), (0.0, dy), (dx, dy)] {
|
||||
let next = p.tile + kurbo::Vec2::new(x * w, y * h);
|
||||
assert!(p.offsets_covering(next).contains(&kurbo::Vec2::ZERO), "{}: {b:?} is cut off at {next:?}", p.name);
|
||||
}
|
||||
crossing += usize::from(dx != 0.0 || dy != 0.0);
|
||||
for (dx, dy) in [(w, 0.0), (-w, 0.0), (0.0, h), (0.0, -h), (w, h), (w, -h), (-w, h), (-w, -h)] {
|
||||
let moved = *b + kurbo::Vec2::new(dx, dy);
|
||||
assert!(!bounds.iter().any(|o| near(o, moved)), "{}: {b:?} is drawn twice by the tiling", p.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(crossing > 0, "no mark reaches past an edge");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -760,14 +760,16 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
// was none, no module goes with the grant, and the grant stops counting for this session. A
|
||||
// grants file that is too large or doesn't hold a list approves nothing, and the new module
|
||||
// stays; one that can't be opened or read may approve the old bytes once it reads again.
|
||||
// was none, no module goes with the grant, and the grant stops counting for every session in
|
||||
// the process attached to the folder. A grants file that is too large or doesn't hold a list
|
||||
// approves nothing, and the new module stays; one that can't be opened or read may approve
|
||||
// the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&m.id);
|
||||
s.ignore_stored_grant(&m.id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +108,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"brush.move",
|
||||
"brush.new",
|
||||
"brush.options",
|
||||
"brush.placeArt",
|
||||
"brush.remove",
|
||||
"brush.selectionArt",
|
||||
"brush.setCurrent",
|
||||
@@ -676,6 +677,7 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"addon.pen.nextSegment",
|
||||
"effect.refreshDeferred",
|
||||
"graphicStyle.setOptions",
|
||||
"object.blend.createSpine",
|
||||
"object.blend.options",
|
||||
"object.liquify",
|
||||
"object.pathfinder.options",
|
||||
|
||||
@@ -769,7 +769,7 @@ impl Session {
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}", always, get),
|
||||
cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}; under automation read roots a folder preference outside them is null, and an export preset's folder outside them is left out", always, get),
|
||||
cmd!(
|
||||
query "prefs.set",
|
||||
"Set Preference",
|
||||
@@ -780,7 +780,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
set
|
||||
),
|
||||
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
|
||||
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference", always, list),
|
||||
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list),
|
||||
cmd!(
|
||||
query "prefs.export",
|
||||
"Export Preferences",
|
||||
@@ -886,8 +886,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "imported": values.len() }))
|
||||
}
|
||||
|
||||
/// The preferences that name a folder: the [`FOLDER_PREFS`] and the scratch disks.
|
||||
const PATH_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
|
||||
|
||||
/// The scratch disk choices that are not folders.
|
||||
const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
|
||||
|
||||
/// The preferences as `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show them to the
|
||||
/// request being served. Under automation read roots, a folder preference ([`PATH_PREFS`]) outside
|
||||
/// them is `null`, as `ui.inspect` leaves it out, and an export preset's `folder` outside them is
|
||||
/// left out. An empty value (the default folder) and a scratch
|
||||
/// disk choice ([`SCRATCH_CHOICES`]) are shown. Without roots the preferences are shown as they are.
|
||||
fn shown_prefs(prefs: &Prefs) -> Value {
|
||||
let mut all = prefs.to_json();
|
||||
if crate::file_access::current().is_none() {
|
||||
return all;
|
||||
}
|
||||
// The app trims a folder before it uses it.
|
||||
let hidden = |path: &str| !path.trim().is_empty() && crate::file_access::check_read(path.trim()).is_err();
|
||||
for key in PATH_PREFS {
|
||||
let Some(path) = all[key].as_str() else { continue };
|
||||
if hidden(path) && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path.trim())) {
|
||||
all[key] = Value::Null;
|
||||
}
|
||||
}
|
||||
if let Some(presets) = all.get_mut("screenExportPresets").and_then(Value::as_array_mut) {
|
||||
for settings in presets.iter_mut().filter_map(|p| p.get_mut("settings").and_then(Value::as_object_mut)) {
|
||||
if settings.get("folder").and_then(Value::as_str).is_some_and(hidden) {
|
||||
settings.remove("folder");
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let all = s.prefs.to_json();
|
||||
let all = shown_prefs(&s.prefs);
|
||||
match str_param(p, "key") {
|
||||
Some(k) if spec(k).is_some() || PREF_GROUPS.contains(&k) => Ok(all[k].clone()),
|
||||
Some(k) => Err(bad("prefs.get", format!("unknown preference `{k}`"))),
|
||||
@@ -915,7 +949,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if document_units && values.contains_key("unitsGeneral") && s.active().is_some() {
|
||||
s.set_document_units(s.default_units())?;
|
||||
}
|
||||
let all = s.prefs.to_json();
|
||||
let all = shown_prefs(&s.prefs);
|
||||
Ok(Value::Object(values.keys().map(|k| (k.clone(), all[k.as_str()].clone())).collect()))
|
||||
}
|
||||
|
||||
@@ -929,11 +963,11 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut next = s.prefs.clone();
|
||||
next.reset(cat);
|
||||
s.apply_prefs(next);
|
||||
Ok(json!({ "prefs": s.prefs.to_json() }))
|
||||
Ok(json!({ "prefs": shown_prefs(&s.prefs) }))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let all = s.prefs.to_json();
|
||||
let all = shown_prefs(&s.prefs);
|
||||
Ok(Value::Array(
|
||||
PREF_SPECS
|
||||
.iter()
|
||||
|
||||
@@ -274,7 +274,60 @@ impl FolderStore {
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||
builder.create(dir).map_err(|e| format!("{}: {e}", dir.display()))
|
||||
builder.create(dir).map_err(|e| Self::folder_error(dir, &e, true))
|
||||
}
|
||||
|
||||
/// The first folder on the way to `dir` (`dir` included), from the top down, that is not a
|
||||
/// folder (`true`) or is missing (`false`). None when every one of them is a folder or one of
|
||||
/// them can't be checked.
|
||||
fn in_the_way(dir: &std::path::Path) -> Option<(&std::path::Path, bool)> {
|
||||
let mut way: Vec<&std::path::Path> = dir.ancestors().filter(|p| !p.as_os_str().is_empty()).collect();
|
||||
way.reverse();
|
||||
for p in way {
|
||||
match std::fs::metadata(p) {
|
||||
Ok(m) if m.is_dir() => {}
|
||||
Ok(_) => return Some((p, true)),
|
||||
Err(m) if m.kind() == std::io::ErrorKind::NotFound => return Some((p, false)),
|
||||
Err(_) => return None,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The message for error `e` on folder `dir`, which was being made (`making`) or read. It
|
||||
/// names the first folder on the way to `dir` that is not a folder, or is missing (when
|
||||
/// `making`, the one that couldn't be made), and otherwise `dir`.
|
||||
fn folder_error(dir: &std::path::Path, e: &std::io::Error, making: bool) -> String {
|
||||
match Self::in_the_way(dir) {
|
||||
Some((p, true)) => format!("{} is not a folder: {e}", p.display()),
|
||||
Some((p, false)) if making => format!("couldn't make {}: {e}", p.display()),
|
||||
Some((p, false)) if p != dir => format!("{} is missing", p.display()),
|
||||
_ => format!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The message for error `e` on file `f`. It names the first folder on the way to `f` that is
|
||||
/// not a folder or is missing, and otherwise `f`.
|
||||
fn file_error(f: &std::path::Path, e: &std::io::Error) -> String {
|
||||
match f.parent().and_then(Self::in_the_way) {
|
||||
Some((p, true)) => format!("{} is not a folder: {e}", p.display()),
|
||||
Some((p, false)) => format!("{} is missing", p.display()),
|
||||
None => format!("{}: {e}", f.display()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome `r` of removing file `f`. A file that is not there counts as removed, unless a
|
||||
/// file is on the way to it: Windows reports that as a missing file, and it is named as for a
|
||||
/// listing.
|
||||
pub(crate) fn removed(f: &std::path::Path, r: std::io::Result<()>) -> std::result::Result<(), String> {
|
||||
match r {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => match f.parent().and_then(Self::in_the_way) {
|
||||
Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())),
|
||||
_ => Ok(()),
|
||||
},
|
||||
Err(e) => Err(Self::file_error(f, &e)),
|
||||
Ok(()) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse area folder `dir` unless it is a folder itself, not a link to one, and (on Unix)
|
||||
@@ -282,7 +335,7 @@ impl FolderStore {
|
||||
/// linked to a folder of its own in a shared recovery folder looked free, and claiming it
|
||||
/// wrote the copies through the link.
|
||||
fn own_area(dir: &std::path::Path) -> std::result::Result<(), String> {
|
||||
let m = std::fs::symlink_metadata(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let m = std::fs::symlink_metadata(dir).map_err(|e| Self::folder_error(dir, &e, false))?;
|
||||
if !m.file_type().is_dir() {
|
||||
return Err(format!("{}: not a folder of its own", dir.display()));
|
||||
}
|
||||
@@ -294,11 +347,17 @@ impl FolderStore {
|
||||
}
|
||||
|
||||
/// The plain names of the files (or, `dirs`, folders) in `dir`; none when it doesn't exist.
|
||||
/// A file on the way to `dir` is an error: Windows reports such a folder as missing.
|
||||
fn names(dir: &std::path::Path, dirs: bool) -> std::result::Result<Vec<String>, String> {
|
||||
let entries = match std::fs::read_dir(dir) {
|
||||
Ok(e) => e,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
|
||||
Err(e) => return Err(format!("{}: {e}", dir.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
return match Self::in_the_way(dir) {
|
||||
Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())),
|
||||
_ => Ok(vec![]),
|
||||
};
|
||||
}
|
||||
Err(e) => return Err(Self::folder_error(dir, &e, false)),
|
||||
};
|
||||
Ok(entries
|
||||
.filter_map(|e| e.ok())
|
||||
@@ -333,7 +392,7 @@ impl FolderStore {
|
||||
match e.kind() {
|
||||
std::io::ErrorKind::NotFound => Ok(Lock::Busy),
|
||||
std::io::ErrorKind::PermissionDenied if std::fs::symlink_metadata(path).is_ok() => Ok(Lock::Busy),
|
||||
_ => Err(format!("{}: {e}", path.display())),
|
||||
_ => Err(Self::file_error(path, &e)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,7 +404,7 @@ impl FolderStore {
|
||||
Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy),
|
||||
// The lock file was removed meanwhile, and locking it failed instead.
|
||||
Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(Self::file_error(path, &e)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,10 +452,10 @@ impl RecoveryStore for FolderStore {
|
||||
if let Some(dir) = f.parent() {
|
||||
Self::own_area(dir)?;
|
||||
}
|
||||
if !std::fs::symlink_metadata(&f).map_err(|e| format!("{}: {e}", f.display()))?.file_type().is_file() {
|
||||
if !std::fs::symlink_metadata(&f).map_err(|e| Self::file_error(&f, &e))?.file_type().is_file() {
|
||||
return Err(format!("{}: not a plain file", f.display()));
|
||||
}
|
||||
std::fs::read(&f).map_err(|e| format!("{}: {e}", f.display()))
|
||||
std::fs::read(&f).map_err(|e| Self::file_error(&f, &e))
|
||||
}
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> {
|
||||
let f = self.file(name)?;
|
||||
@@ -404,14 +463,11 @@ impl RecoveryStore for FolderStore {
|
||||
Self::create_area(dir)?;
|
||||
Self::own_area(dir)?;
|
||||
}
|
||||
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| format!("{}: {e}", f.display()))
|
||||
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e))
|
||||
}
|
||||
fn remove(&self, name: &str) -> std::result::Result<(), String> {
|
||||
let f = self.file(name)?;
|
||||
match std::fs::remove_file(&f) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("{}: {e}", f.display())),
|
||||
_ => Ok(()),
|
||||
}
|
||||
Self::removed(&f, std::fs::remove_file(&f))
|
||||
}
|
||||
fn location(&self) -> String {
|
||||
self.0.to_string_lossy().into_owned()
|
||||
|
||||
@@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Tab Stops",
|
||||
["Window", "Tabs"],
|
||||
None,
|
||||
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); supplied align, leader and alignOn must be strings, and alignOn cannot be empty",
|
||||
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); at most 256 stops, positions 0..=100000 pt; supplied align, leader and alignOn must be strings, a leader has at most 8 characters and alignOn exactly one; stops are sorted by position, and of stops at one position the first given is kept",
|
||||
has_selection,
|
||||
set
|
||||
),
|
||||
@@ -38,10 +38,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
|
||||
const C: &str = "text.tabs.set";
|
||||
let arr = p.get("stops").and_then(Value::as_array).ok_or_else(|| bad(C, "missing stops"))?;
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if arr.len() > max {
|
||||
return Err(bad(C, format!("at most {max} tab stops")));
|
||||
}
|
||||
let mut stops = vec![];
|
||||
for s in arr {
|
||||
let position = s.get("position").and_then(Value::as_f64).ok_or_else(|| bad(C, "each stop needs a position"))?;
|
||||
if !(0.0..=100_000.0).contains(&position) {
|
||||
if !(0.0..=TabStop::MAX_POSITION).contains(&position) {
|
||||
return Err(bad(C, "positions must be between 0 and 100000 pt"));
|
||||
}
|
||||
let align = match s.get("align") {
|
||||
@@ -60,16 +64,25 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
|
||||
None | Some(Value::Null) => "",
|
||||
Some(Value::String(value)) => value.as_str(),
|
||||
Some(_) => return Err(bad(C, "`leader` must be a string")),
|
||||
};
|
||||
let (label, max) = ("`leader`", TabStop::MAX_LEADER);
|
||||
if leader.chars().count() > max {
|
||||
return Err(bad(C, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
.chars()
|
||||
.take(8)
|
||||
.collect();
|
||||
let align_on = match s.get("alignOn") {
|
||||
None | Some(Value::Null) => '.',
|
||||
Some(Value::String(value)) => value.chars().next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?,
|
||||
Some(Value::String(value)) => {
|
||||
let mut chars = value.chars();
|
||||
let c = chars.next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?;
|
||||
if chars.next().is_some() {
|
||||
let label = "`alignOn`";
|
||||
return Err(bad(C, format!("{label} must be one character")));
|
||||
}
|
||||
c
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`alignOn` must be a string")),
|
||||
};
|
||||
stops.push(TabStop { position, align, leader, align_on });
|
||||
stops.push(TabStop { position, align, leader: leader.to_string(), align_on });
|
||||
}
|
||||
stops.sort_by(|a, b| a.position.total_cmp(&b.position));
|
||||
stops.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
|
||||
@@ -128,7 +141,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -139,6 +152,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A leader of more than eight characters, an `alignOn` of more than one character and a list
|
||||
/// of more than 256 stops are errors, not cut short.
|
||||
#[test]
|
||||
fn long_leaders_long_align_on_and_too_many_stops_are_errors() {
|
||||
let err = |stops: Value| super::parse_stops(&json!({ "stops": stops })).unwrap_err().to_string();
|
||||
assert!(err(json!([{"position": 40, "leader": "123456789"}])).contains("`leader` must be at most 8 characters"));
|
||||
assert!(err(json!([{"position": 40, "alignOn": ",."}])).contains("`alignOn` must be one character"));
|
||||
let many: Vec<Value> = (0..257).map(|i| json!({"position": i})).collect();
|
||||
assert!(err(Value::from(many.clone())).contains("at most 256 tab stops"));
|
||||
let ok = super::parse_stops(&json!({ "stops": &many[..256] })).unwrap();
|
||||
assert_eq!(ok.len(), 256);
|
||||
let ok = super::parse_stops(&json!({"stops": [{"position": 0, "leader": "12345678", "alignOn": "€"}]})).unwrap();
|
||||
assert_eq!((ok[0].leader.as_str(), ok[0].align_on), ("12345678", '€'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_get_clear_tabs() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef};
|
||||
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TabStop, TextStyleDef};
|
||||
|
||||
use super::clipboard::resources::import_text_styles;
|
||||
use super::typecmd::{refresh_bounds, text_targets};
|
||||
@@ -125,7 +125,7 @@ macro_rules! style_cmds {
|
||||
}
|
||||
|
||||
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = style_cmds!(
|
||||
@@ -148,13 +148,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"paraStyle",
|
||||
"Paragraph Styles",
|
||||
"Paragraph",
|
||||
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt"
|
||||
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position"
|
||||
));
|
||||
v.push(spec(
|
||||
"paraStyle.edit",
|
||||
"Edit Paragraph Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt",
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position",
|
||||
|s, p| edit_style(s, p, Kind::Para),
|
||||
true,
|
||||
));
|
||||
@@ -569,8 +569,9 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
char_attrs(&st)
|
||||
}
|
||||
Kind::Para => {
|
||||
let st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
let mut st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
para_ranges(&st, m, kept, &c)?;
|
||||
sort_tabs(&mut st, m, kept);
|
||||
para_attrs(&st)
|
||||
}
|
||||
};
|
||||
@@ -587,7 +588,8 @@ const PARA_DISTANCE: f64 = 1296.0;
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them) and the position of each tab stop. A value `kept` has is not checked.
|
||||
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
|
||||
/// `kept` does not hold. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
@@ -644,18 +646,37 @@ fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<Str
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs: Vec<f64> = kept
|
||||
.and_then(|k| k.get("tabs"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|stops| stops.iter().filter_map(|s| s.get("position").and_then(Value::as_f64)).collect())
|
||||
.unwrap_or_default();
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(&stop.position)) {
|
||||
within("tabs.position", stop.position, 0.0, 100_000.0)?;
|
||||
let kept_tabs = kept_tab_stops(kept);
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if st.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(bad(c, format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(bad(c, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
|
||||
fn kept_tab_stops(kept: Option<&Map<String, Value>>) -> Vec<TabStop> {
|
||||
let stops = kept.and_then(|k| k.get("tabs")).and_then(Value::as_array);
|
||||
stops.into_iter().flatten().filter_map(|s| serde_json::from_value(s.clone()).ok()).collect()
|
||||
}
|
||||
|
||||
/// `st`'s tab stops sorted by position, keeping the first of stops within 1e-6 pt of each other,
|
||||
/// as `text.tabs.set` keeps them, when `attrs` changes them from `kept`.
|
||||
fn sort_tabs(st: &mut ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>) {
|
||||
if attrs.contains_key("tabs") && kept.and_then(|k| k.get("tabs")) != attrs.get("tabs") {
|
||||
st.tabs.sort_by(|a, b| a.position.total_cmp(&b.position));
|
||||
st.tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a
|
||||
/// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes.
|
||||
fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> {
|
||||
@@ -1011,10 +1032,29 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, or whose name
|
||||
/// is empty, which are skipped. → (the styles, the names in `src` of those skipped)
|
||||
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
const RANGED: [&str; 8] = ["size", "h_scale", "v_scale", "leading", "baseline_shift", "tcyUpDown", "tcyLeftRight", "stroke_width"];
|
||||
const RANGED: [&str; 16] = [
|
||||
"size",
|
||||
"h_scale",
|
||||
"v_scale",
|
||||
"leading",
|
||||
"baseline_shift",
|
||||
"tcyUpDown",
|
||||
"tcyLeftRight",
|
||||
"stroke_width",
|
||||
"left_indent",
|
||||
"right_indent",
|
||||
"first_line_indent",
|
||||
"space_before",
|
||||
"space_after",
|
||||
"hyphenation",
|
||||
"justification",
|
||||
"tabs",
|
||||
];
|
||||
let (mut defs, mut skipped) = (vec![], vec![]);
|
||||
for def in kind.defs(src) {
|
||||
let name = def.name.as_str();
|
||||
|
||||
@@ -1729,3 +1729,77 @@ fn paragraph_style_attributes_are_checked_before_a_definition_changes() {
|
||||
assert!(error.contains(&format!("`{key}`")), "{attrs}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph style's changed tab stops are checked stop by stop: a stop the style holds is kept
|
||||
/// as it is, and a stop at a held position with another alignment is a changed stop. A changed
|
||||
/// stop's leader has at most eight characters and its Align On one character, a changed list has
|
||||
/// at most 256 stops (or as many as the style holds, here 300), and the stops are stored sorted by position,
|
||||
/// keeping the first of stops at one position.
|
||||
#[test]
|
||||
fn paragraph_style_tab_stops_are_checked_by_stop_and_sorted() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap();
|
||||
let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone();
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let held: Vec<Value> =
|
||||
(0..300).map(|i| json!({"position": 200000.0 + f64::from(i), "align": "left", "leader": "123456789", "alignOn": "."})).collect();
|
||||
doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("tabs".into(), Value::from(held.clone()));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let mut moved = held.clone();
|
||||
moved[0]["align"] = json!("right");
|
||||
for (stops, why) in [
|
||||
(Value::from(moved), "`tabs.position`"),
|
||||
(json!([{"position": 36.0, "leader": "123456789"}]), "`tabs.leader` must be at most 8 characters"),
|
||||
(Value::from((0..301).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>()), "at most 256 tab stops"),
|
||||
(json!([{"position": 36.0, "alignOn": ",."}]), "expected a character"),
|
||||
] {
|
||||
for cmd in ["paraStyle.edit", "paraStyle.setAttrs"] {
|
||||
let params = match cmd {
|
||||
"paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": {"tabs": stops}}),
|
||||
_ => json!({"name": "Body", "attrs": {"tabs": stops}}),
|
||||
};
|
||||
let error = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains(why), "{cmd}: {error}");
|
||||
}
|
||||
}
|
||||
let many = Value::from((0..257).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>());
|
||||
let error = s.execute("paraStyle.new", &json!({"name": "Other", "attrs": {"tabs": many}})).unwrap_err().to_string();
|
||||
assert!(error.contains("at most 256 tab stops"), "{error}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
// The held stops stay while one is dropped and another attribute changes.
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": &held[1..], "left_indent": 4.0}})).unwrap();
|
||||
assert_eq!(def(&s)["tabs"].as_array().map(Vec::len), Some(299));
|
||||
let stops = json!([{"position": 72.0, "align": "right"}, {"position": 36.0}, {"position": 36.0000001, "align": "center"}, {"position": 0.0, "leader": "12345678"}]);
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap();
|
||||
assert_eq!(
|
||||
def(&s)["tabs"],
|
||||
json!([{"position": 0.0, "align": "left", "leader": "12345678", "alignOn": "."}, {"position": 36.0, "align": "left", "alignOn": "."},
|
||||
{"position": 72.0, "align": "right", "alignOn": "."}])
|
||||
);
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": []}})).unwrap();
|
||||
assert_eq!(def(&s)["tabs"], json!([]), "an empty list stays set");
|
||||
}
|
||||
|
||||
/// Load Paragraph Styles and Load All Styles skip a paragraph style whose indents, spacing,
|
||||
/// Hyphenation or Justification options or tab stops are out of the range `paraStyle.new` takes,
|
||||
/// and load the others with their stops.
|
||||
#[test]
|
||||
fn loading_skips_paragraph_styles_out_of_range() {
|
||||
let file = [
|
||||
("Good", json!({"left_indent": 6.0, "tabs": [{"position": 36.0, "align": "decimal", "alignOn": ","}]})),
|
||||
("Indent", json!({"left_indent": 2000.0})),
|
||||
("Space", json!({"space_after": -1300.0})),
|
||||
("Hyphens", json!({"hyphenation": {"words_longer_than": 40}})),
|
||||
("Spacing", json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}})),
|
||||
("Leader", json!({"tabs": [{"position": 10.0, "leader": "123456789"}]})),
|
||||
];
|
||||
let data = styles_file(&[], &file);
|
||||
for cmd in ["paraStyle.load", "textStyle.loadAll"] {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
let r = s.execute(cmd, &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
|
||||
let r = if cmd == "textStyle.loadAll" { r["paraStyles"].clone() } else { r };
|
||||
assert_eq!(r, json!({"added": ["Good"], "existing": [], "skipped": ["Indent", "Space", "Hyphens", "Spacing", "Leader"]}), "{cmd}");
|
||||
let good = super::style_attrs(&s.doc().unwrap().doc, true, "Good").unwrap();
|
||||
assert_eq!(good["tabs"], json!([{"position": 36.0, "align": "decimal", "alignOn": ","}]), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,6 +140,35 @@ fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes()
|
||||
assert_eq!(undo_len(&s), n + 2, "already off: no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_point_type_turns_block_off_keeping_its_sizes() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let sizes = |t: &TextObject| t.runs.iter().map(|r| (r.text.clone(), r.style.size, r.style.leading)).collect::<Vec<_>>();
|
||||
let fitted = sizes(&text(&s, id));
|
||||
let n = undo_len(&s);
|
||||
s.execute("type.convertToPointType", &json!({})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1, "one undo step");
|
||||
let t = text(&s, id);
|
||||
assert!(matches!(t.kind, TextKind::Point));
|
||||
assert!(!t.dynamic_text, "point type has Dynamic Text off");
|
||||
assert_eq!(sizes(&t), fitted, "point type keeps the sizes Block set");
|
||||
assert!(serde_json::to_value(&t).unwrap().get("dynamicText").is_none(), "saved without dynamicText");
|
||||
// Back to area type, the frame is not refitted: Block stays off.
|
||||
s.execute("type.convertToAreaType", &json!({})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(matches!(t.kind, TextKind::Area { .. }));
|
||||
assert!(!t.dynamic_text, "Block does not come on again");
|
||||
assert_eq!(sizes(&t), fitted);
|
||||
// Undo gives the Block frame back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }));
|
||||
assert_eq!(sizes(&t), fitted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_and_other_type_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert To Point Type",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?} area type → point type; soft line wraps become line breaks, and a frame of threaded text leaves its thread with the text it holds → {ids}",
|
||||
"{ids?|id?} area type → point type; soft line wraps become line breaks, a frame of threaded text leaves its thread with the text it holds, and Dynamic Text (Block) is turned off, keeping the sizes it set → {ids}",
|
||||
has_selection,
|
||||
to_point
|
||||
),
|
||||
@@ -410,6 +410,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => x1,
|
||||
_ => x0,
|
||||
};
|
||||
// Point type has no Dynamic Text: Block is turned off, keeping the sizes it set, so
|
||||
// converting back to area type does not turn it on again.
|
||||
t.dynamic_text = false;
|
||||
t.kind = TextKind::Point;
|
||||
t.xf *= Affine::translate((ox, baseline));
|
||||
refresh_bounds(t);
|
||||
|
||||
@@ -171,10 +171,6 @@ pub struct Session {
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
/// The plug-in ids whose grant in the plug-in store should be gone but could not be removed:
|
||||
/// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful
|
||||
/// [`Session::store_grant`] for the id takes it out.
|
||||
ignored_plugin_grants: std::sync::Mutex<std::collections::BTreeSet<String>>,
|
||||
/// A filter's output that a run made in the background handed in for `plugin.run` to apply
|
||||
/// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it.
|
||||
plugin_output: Option<cmd::plugin::HandedIn>,
|
||||
@@ -306,6 +302,8 @@ pub struct Session {
|
||||
pub(crate) press_point: Option<Option<(usize, cmd::gradient::StopOwner)>>,
|
||||
/// A guide being dragged out of a ruler ([`Session::ruler_guide`]).
|
||||
pub(crate) ruler_guide: Option<vectorcraft_tools::rulerguide::NewGuide>,
|
||||
/// The rulers' origin being dragged out of their corner ([`Session::ruler_origin_drag`]).
|
||||
pub(crate) ruler_origin: Option<vectorcraft_tools::rulerguide::OriginDrag>,
|
||||
/// Which selected type overflows its frame, for the ports every tool but the Type tools shows.
|
||||
pub(crate) port_marks: vectorcraft_tools::text::PortMarks,
|
||||
/// The last search for the files of missing fonts (`text.findFontFiles`), until another
|
||||
|
||||
@@ -87,7 +87,6 @@ impl Session {
|
||||
color_settings_file: None,
|
||||
plugin_dir: None,
|
||||
scripts_dir: None,
|
||||
ignored_plugin_grants: Default::default(),
|
||||
plugin_output: None,
|
||||
plugin_install_approval: None,
|
||||
plugin_grants_from_requests: false,
|
||||
@@ -124,6 +123,7 @@ impl Session {
|
||||
press_type_selection: None,
|
||||
press_point: None,
|
||||
ruler_guide: None,
|
||||
ruler_origin: None,
|
||||
port_marks: Default::default(),
|
||||
font_search: None,
|
||||
link_search: None,
|
||||
|
||||
@@ -82,7 +82,13 @@ impl Session {
|
||||
&& params.get("ids").is_none_or(Value::is_null)
|
||||
&& params.get("id").and_then(Value::as_str).is_some_and(|e| !e.starts_with('$'));
|
||||
if cmd::params::id_stands_for_ids(spec.params) && !effect_named && self.active().is_some() {
|
||||
cmd::given_objects(self, params, id)?;
|
||||
// `effect.refreshDeferred` looks its objects up itself: they can also be in the art of
|
||||
// a symbol, pattern, brush or opacity mask.
|
||||
if id == "effect.refreshDeferred" {
|
||||
cmd::given_object_ids(params, id)?;
|
||||
} else {
|
||||
cmd::given_objects(self, params, id)?;
|
||||
}
|
||||
}
|
||||
if SELECTS_GIVEN_IDS.contains(&id) {
|
||||
self.check_given_ids(id, params)?;
|
||||
|
||||
+105
-18
@@ -89,6 +89,24 @@ static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(());
|
||||
/// The state of each plug-in folder's storage, shared by every storage made for the folder until
|
||||
/// the plug-in is removed, which closes it and drops it.
|
||||
static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<PluginData>>> = Mutex::new(BTreeMap::new());
|
||||
/// The grants of plug-in stores that the sessions of the process don't count, and when each was
|
||||
/// last written ([`IgnoredGrants`]). Another process reads `grants.json` as it is.
|
||||
static IGNORED_PLUGIN_GRANTS: Mutex<IgnoredGrants> = Mutex::new(IgnoredGrants { ignored: BTreeSet::new(), written: BTreeMap::new(), writes: 0 });
|
||||
/// How many of the latest grant writes [`IgnoredGrants`] keeps.
|
||||
const MAX_GRANT_WRITES_KEPT: usize = 256;
|
||||
|
||||
/// Grants of plug-in stores, by the store's folder ([`plugin_store_key`]) and the plug-in id.
|
||||
struct IgnoredGrants {
|
||||
/// The grants that should be gone but could not be removed: no session in the process counts
|
||||
/// them ([`Session::ignore_stored_grant`]) until one writes the store's grants for the id
|
||||
/// ([`Session::store_grant`]).
|
||||
ignored: BTreeSet<(PathBuf, String)>,
|
||||
/// The latest grant writes of the process, at most [`MAX_GRANT_WRITES_KEPT`], each with the
|
||||
/// count of writes it made ([`IgnoredGrants::writes`]).
|
||||
written: BTreeMap<(PathBuf, String), u64>,
|
||||
/// How many grant writes the sessions of the process have made ([`Session::grant_writes`]).
|
||||
writes: u64,
|
||||
}
|
||||
|
||||
/// The file name (without extension) a stored item called `name` gets: its name made safe for any
|
||||
/// file system, then a hash of the name, so that names that differ only in characters a file name
|
||||
@@ -100,6 +118,37 @@ pub(crate) fn file_stem(name: &str) -> String {
|
||||
format!("{}-{hash:016x}", safe.trim())
|
||||
}
|
||||
|
||||
/// The folder `dir` spelled one way for every path to it, so that sessions attached to it by
|
||||
/// different paths share [`IGNORED_PLUGIN_GRANTS`]: the canonical path when the folder exists, else
|
||||
/// the canonical path of its nearest folder that exists followed by the rest of the path, with `.`
|
||||
/// and `..` taken out by name. The path as given when it has no absolute form (the current folder
|
||||
/// can't be read).
|
||||
pub(crate) fn plugin_store_key(dir: &Path) -> PathBuf {
|
||||
if let Ok(path) = std::fs::canonicalize(dir) {
|
||||
return path;
|
||||
}
|
||||
let Ok(absolute) = std::path::absolute(dir) else { return dir.to_path_buf() };
|
||||
let mut parts: Vec<std::path::Component> = Vec::new();
|
||||
for part in absolute.components() {
|
||||
match part {
|
||||
std::path::Component::CurDir => {}
|
||||
std::path::Component::ParentDir => {
|
||||
if matches!(parts.last(), Some(std::path::Component::Normal(_))) {
|
||||
parts.pop();
|
||||
}
|
||||
}
|
||||
_ => parts.push(part),
|
||||
}
|
||||
}
|
||||
for kept in (1..=parts.len()).rev() {
|
||||
let base: PathBuf = parts[..kept].iter().collect();
|
||||
if let Ok(found) = std::fs::canonicalize(&base) {
|
||||
return parts[kept..].iter().fold(found, |path, part| path.join(part));
|
||||
}
|
||||
}
|
||||
parts.iter().collect()
|
||||
}
|
||||
|
||||
/// The regular files of `dir` with the extension `ext` (any case), by file name, at most
|
||||
/// [`MAX_STORE_FILES`]; none when the folder can't be read.
|
||||
fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
|
||||
@@ -355,9 +404,6 @@ impl Session {
|
||||
let disabled =
|
||||
read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
if self.plugin_dir.as_ref() != Some(&dir) {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
}
|
||||
self.plugin_dir = Some(dir);
|
||||
self.load_stored_plugins();
|
||||
}
|
||||
@@ -368,7 +414,8 @@ impl Session {
|
||||
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
|
||||
/// stays in the folder with its grant. A grant for an id whose stored module lists no
|
||||
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
|
||||
/// the rest of the session ([`Session::plugin_approver`]).
|
||||
/// any session in the process attached to the folder until the file can be written for the id
|
||||
/// ([`Session::ignore_stored_grant`]).
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
if safe_mode::active() {
|
||||
@@ -432,8 +479,11 @@ impl Session {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
};
|
||||
if named && !self.store_grant(id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id);
|
||||
if named {
|
||||
let writes = self.grant_writes();
|
||||
if !self.store_grant(id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -515,12 +565,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session
|
||||
/// doesn't count ([`Session::ignore_stored_grant`]).
|
||||
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those the process
|
||||
/// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked
|
||||
/// out on each call, so a path whose link now leads elsewhere is matched with where it leads.
|
||||
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
let ignored = self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let key = plugin_store_key(dir);
|
||||
let mut grants = stored_grants(dir);
|
||||
grants.retain(|id, _| !ignored.contains(id));
|
||||
let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) {
|
||||
grants.remove(id);
|
||||
}
|
||||
grants
|
||||
}
|
||||
|
||||
@@ -573,20 +627,53 @@ impl Session {
|
||||
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now
|
||||
/// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts
|
||||
/// again ([`Session::ignore_stored_grant`]).
|
||||
/// again, for every session in the process attached to the store ([`Session::ignore_stored_grant`]).
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let done = self.write_grant(id, grant);
|
||||
if done {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
|
||||
if done && let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) {
|
||||
let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let entry = (key, id.to_string());
|
||||
shared.ignored.remove(&entry);
|
||||
shared.writes = shared.writes.saturating_add(1);
|
||||
let writes = shared.writes;
|
||||
shared.written.insert(entry, writes);
|
||||
if shared.written.len() > MAX_GRANT_WRITES_KEPT
|
||||
&& let Some(oldest) = shared.written.iter().min_by_key(|(_, at)| **at).map(|(entry, _)| entry.clone())
|
||||
{
|
||||
shared.written.remove(&oldest);
|
||||
}
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
/// Stop counting the store's grant for the plug-in `id` until [`Session::store_grant`] next
|
||||
/// succeeds for it or another store is attached: for a grant that should be gone and could not
|
||||
/// be removed, which would otherwise approve the bytes it covers.
|
||||
pub(crate) fn ignore_stored_grant(&self, id: &str) {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string());
|
||||
/// How many grant writes the sessions of the process have made ([`Session::store_grant`]).
|
||||
/// Taken before a write that may fail, for [`Session::ignore_stored_grant`].
|
||||
pub(crate) fn grant_writes(&self) -> u64 {
|
||||
IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).writes
|
||||
}
|
||||
|
||||
/// How many grant writes the process keeps ([`IgnoredGrants::written`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn grant_writes_kept() -> usize {
|
||||
IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).written.len()
|
||||
}
|
||||
|
||||
/// Stop counting the attached store's grant for the plug-in `id`, in every session in the
|
||||
/// process attached to the same folder, until [`Session::store_grant`] next succeeds for it in
|
||||
/// one of them: for a grant that should be gone and could not be removed, which would otherwise
|
||||
/// approve the bytes it covers. `writes` is [`Session::grant_writes`] from before the failed
|
||||
/// write: when a session has written the store's grants for `id` since, the file holds what that
|
||||
/// write asked for, and the grant keeps counting. A write no longer among the latest
|
||||
/// [`MAX_GRANT_WRITES_KEPT`] is not seen, and the grant stops counting. Another process on the
|
||||
/// folder reads `grants.json` as it is.
|
||||
pub(crate) fn ignore_stored_grant(&self, id: &str, writes: u64) {
|
||||
if let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) {
|
||||
let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let entry = (key, id.to_string());
|
||||
if shared.written.get(&entry).is_none_or(|at| *at <= writes) {
|
||||
shared.ignored.insert(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
|
||||
@@ -133,6 +133,7 @@ mod placed_document;
|
||||
mod plugins;
|
||||
mod prefs;
|
||||
mod prefs_file;
|
||||
mod prefs_roots;
|
||||
mod previewbounds;
|
||||
mod print;
|
||||
mod printadvanced;
|
||||
|
||||
@@ -418,3 +418,179 @@ fn native_blend_easing_values_clamp_and_non_finite_become_default() {
|
||||
assert_eq!((spec.ease.ramp, spec.color_shift), (ramp, shift), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
fn create_spine(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("object.blend.createSpine", &p).unwrap()["mode"].clone()
|
||||
}
|
||||
|
||||
/// Two squares 100 pt apart blended with `p`; the blend.
|
||||
fn make(s: &mut Session, y: f64, p: Value) -> NodeId {
|
||||
let (a, b) = (rect(s, 0.0, y, 10.0), rect(s, 100.0, y, 10.0));
|
||||
let mut p = p;
|
||||
p["ids"] = json!([a.0, b.0]);
|
||||
p["steps"] = json!(3);
|
||||
id_of(&s.execute("object.blend.make", &p).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_spine_sets_whether_new_blends_get_a_spine() {
|
||||
let mut s = session();
|
||||
assert_eq!(create_spine(&mut s, json!({})), "auto", "Auto until one is chosen");
|
||||
let spined = make(&mut s, 0.0, json!({}));
|
||||
assert!(!spec(&s, spined).1.no_spine);
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(create_spine(&mut s, json!({"mode": "never"})), "never");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "a tool setting, not an undo step");
|
||||
assert_eq!(create_spine(&mut s, json!({})), "never");
|
||||
// The Blend Options set with nothing selected keep it, and it keeps them.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"steps": 7})).unwrap();
|
||||
assert_eq!(create_spine(&mut s, json!({})), "never");
|
||||
assert_eq!(s.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7));
|
||||
// A new blend has no spine; the blend made before keeps its own.
|
||||
let bare = make(&mut s, 50.0, json!({}));
|
||||
assert!(spec(&s, bare).1.no_spine);
|
||||
assert!(!spec(&s, spined).1.no_spine, "blends already made keep their spine");
|
||||
sel(&mut s, &[bare]);
|
||||
let info = s.execute("object.blend.info", &json!({})).unwrap();
|
||||
assert_eq!(info["hasSpine"], json!(false));
|
||||
assert!(info.get("spine").is_none(), "{info}");
|
||||
sel(&mut s, &[spined]);
|
||||
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap()["hasSpine"], json!(true));
|
||||
// `createSpine` on Make chooses for that blend only.
|
||||
let forced = make(&mut s, 100.0, json!({"createSpine": "always"}));
|
||||
assert!(!spec(&s, forced).1.no_spine);
|
||||
assert_eq!(create_spine(&mut s, json!({})), "never");
|
||||
assert_eq!(create_spine(&mut s, json!({"mode": "always"})), "always");
|
||||
let always = make(&mut s, 150.0, json!({}));
|
||||
assert!(!spec(&s, always).1.no_spine);
|
||||
assert!(spec(&s, bare).1.no_spine, "blends already made keep having no spine");
|
||||
let none = make(&mut s, 200.0, json!({"createSpine": "never"}));
|
||||
assert!(spec(&s, none).1.no_spine);
|
||||
// The setting survives a round trip through the preferences file; Auto is not written.
|
||||
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
|
||||
assert_eq!(back.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Always);
|
||||
assert_eq!(s.prefs.to_json()["blendOptions"]["createSpine"], json!("always"));
|
||||
create_spine(&mut s, json!({"mode": "auto"}));
|
||||
assert!(s.prefs.to_json()["blendOptions"].get("createSpine").is_none());
|
||||
let mut odd = s.prefs.to_json();
|
||||
odd["blendOptions"]["createSpine"] = json!("sometimes");
|
||||
let unknown: Prefs = serde_json::from_value(odd).unwrap();
|
||||
assert_eq!(unknown.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Auto, "an unknown value reads as Auto");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_spine_refuses_bad_values_and_changes_nothing() {
|
||||
let mut s = session();
|
||||
create_spine(&mut s, json!({"mode": "never"}));
|
||||
let prefs = s.prefs.blend_options;
|
||||
for bad in [json!({"mode": "sometimes"}), json!({"mode": 1}), json!({"mode": true}), json!({"mode": ["never"]}), json!({"mode": "Never"})] {
|
||||
let e = s.execute("object.blend.createSpine", &bad).unwrap_err().to_string();
|
||||
assert!(e.contains("`mode` must be one of auto, always, never"), "{bad}: {e}");
|
||||
assert_eq!(s.prefs.blend_options, prefs, "{bad}");
|
||||
}
|
||||
let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0), rect(&mut s, 100.0, 0.0, 10.0));
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
for bad in [json!({"createSpine": "x"}), json!({"createSpine": 0}), json!({"createSpine": "never", "easingType": "easeIn"}), json!({"ramp": 30})]
|
||||
{
|
||||
let mut p = bad.clone();
|
||||
p["ids"] = json!([a.0, b.0]);
|
||||
assert!(s.execute("object.blend.make", &p).is_err(), "{bad}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "{bad}: nothing made");
|
||||
}
|
||||
assert!(s.execute("object.blend.createSpine", &json!({"spine": "never"})).is_err(), "an unknown key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release() {
|
||||
let mut s = session();
|
||||
let g = make(&mut s, 0.0, json!({"createSpine": "never"}));
|
||||
sel(&mut s, &[g]);
|
||||
let before = node(&s, g);
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
// Reverse Spine, easing and the spine point commands refuse it and change nothing.
|
||||
let refused = [
|
||||
("object.blend.reverseSpine", json!({})),
|
||||
("object.blend.options", json!({"easingType": "easeOut"})),
|
||||
("object.blend.options", json!({"ramp": 40})),
|
||||
("object.blend.spine.addAnchor", json!({"x": 50, "y": 5})),
|
||||
("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 50})),
|
||||
];
|
||||
for (cmd, p) in refused {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("the blend has no spine"), "{cmd}: {e}");
|
||||
assert_eq!((node(&s, g), s.doc().unwrap().history.undo.len()), (before.clone(), depth), "{cmd}");
|
||||
}
|
||||
// Spacing, Orientation and Shift still apply; Align to Path makes no spine.
|
||||
s.execute("object.blend.options", &json!({"steps": 2, "orientation": "path", "colorShift": 20})).unwrap();
|
||||
let sp = spec(&s, g).1;
|
||||
assert_eq!((sp.spacing, sp.orientation, sp.color_shift, sp.no_spine), (BlendSpacing::Steps(2), BlendOrientation::AlignToPath, 20.0, true));
|
||||
assert!(s.execute("object.blend.info", &json!({})).unwrap().get("spine").is_none());
|
||||
// Taking in another key keeps it without a spine, whatever Create Spine says.
|
||||
let c = rect(&mut s, 200.0, 0.0, 10.0);
|
||||
sel(&mut s, &[g, c]);
|
||||
create_spine(&mut s, json!({"mode": "always"}));
|
||||
let g = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
|
||||
assert_eq!(spec(&s, g).0.len(), 3);
|
||||
assert!(spec(&s, g).1.no_spine && spec(&s, g).1.spine.is_none());
|
||||
// Release gives back the keys and no spine path.
|
||||
sel(&mut s, &[g]);
|
||||
let r = s.execute("object.blend.release", &json!({})).unwrap();
|
||||
assert_eq!((r["ids"].as_array().map(Vec::len), &r["spines"]), (Some(3), &json!([])));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Replace Spine gives it one: then it reverses and eases like any other.
|
||||
let line = id_of(&s.execute("path.create", &json!({"d": "M0 100 L200 150"})).unwrap());
|
||||
sel(&mut s, &[g, line]);
|
||||
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
|
||||
let sp = spec(&s, g).1;
|
||||
assert!(!sp.no_spine && sp.spine.is_some());
|
||||
let info = s.execute("object.blend.info", &json!({})).unwrap();
|
||||
assert_eq!((&info["hasSpine"], &info["spine"]["explicit"]), (&json!(true), &json!(true)));
|
||||
s.execute("object.blend.reverseSpine", &json!({})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"easingType": "easeOut", "ramp": 40})).unwrap();
|
||||
assert_eq!(spec(&s, g).1.ease.ramp, 0.4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blend_without_a_spine_draws_its_steps_where_one_with_a_spine_does() {
|
||||
let mut s = session();
|
||||
for orientation in ["page", "path"] {
|
||||
let spined = make(&mut s, 0.0, json!({"orientation": orientation}));
|
||||
let bare = make(&mut s, 0.0, json!({"orientation": orientation, "createSpine": "never"}));
|
||||
let boxes = |g: NodeId| -> Vec<_> { vectorcraft_doc::live::expand_live(&node(&s, g)).iter().map(|n| n.geometric_bounds()).collect() };
|
||||
assert_eq!(boxes(bare), boxes(spined), "{orientation}");
|
||||
assert!(boxes(bare).len() >= 3, "the three steps at least");
|
||||
}
|
||||
// Easing stored on a blend without a spine (a hand-edited file) leaves its steps evenly spaced.
|
||||
let bare = make(&mut s, 300.0, json!({"orientation": "path", "createSpine": "never"}));
|
||||
let even = vectorcraft_doc::live::expand_live(&node(&s, bare));
|
||||
let mut eased = node(&s, bare);
|
||||
if let NodeKind::Blend { spec, .. } = &mut eased.kind {
|
||||
spec.ease = vectorcraft_doc::live::BlendEase { kind: vectorcraft_doc::live::BlendEaseType::In, ramp: 1.0 };
|
||||
}
|
||||
let boxes = |v: &[Node]| -> Vec<_> { v.iter().map(|n| n.geometric_bounds()).collect() };
|
||||
assert_eq!(boxes(&vectorcraft_doc::live::expand_live(&eased)), boxes(&even));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() {
|
||||
let mut s = session();
|
||||
let bare = make(&mut s, 0.0, json!({"createSpine": "never"}));
|
||||
let spined = make(&mut s, 50.0, json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap();
|
||||
assert_eq!(&back.layers, &d.layers);
|
||||
let saved = |g: NodeId| match &back.node(g).unwrap().kind {
|
||||
NodeKind::Blend { spec, .. } => spec.no_spine,
|
||||
_ => panic!("not a blend"),
|
||||
};
|
||||
assert!(saved(bare) && !saved(spined));
|
||||
assert_eq!(serde_json::to_value(spec(&s, bare).1).unwrap()["noSpine"], json!(true));
|
||||
assert!(serde_json::to_value(spec(&s, spined).1).unwrap().get("noSpine").is_none(), "a spine is not written");
|
||||
let old: BlendSpec = serde_json::from_value(json!({"spacing": {"steps": 4}})).unwrap();
|
||||
assert!(!old.no_spine, "a blend saved before Create Spine has a spine");
|
||||
for odd in [json!("yes"), json!(1), json!(null)] {
|
||||
let v: BlendSpec = serde_json::from_value(json!({"noSpine": odd.clone()})).unwrap_or_else(|e| panic!("{odd}: {e}"));
|
||||
assert!(!v.no_spine, "{odd}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,6 +253,118 @@ fn selection_art_is_the_art_new_brush_takes() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only brush.new is an undo step");
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn selected(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().selection.objects.clone()
|
||||
}
|
||||
|
||||
/// The JSON of object `id`, as `brush.options` params take art.
|
||||
fn art_json(s: &mut Session, id: NodeId) -> Value {
|
||||
s.execute("brush.selectionArt", &json!({"ids": [id.0]})).unwrap()["art"].clone()
|
||||
}
|
||||
|
||||
/// `brush.placeArt` places a copy of an art or scatter brush's art centered where it is dropped
|
||||
/// (by default on the first artboard's center), selected, in one undo step; brushes without art,
|
||||
/// unknown brushes and a position that is not a number are refused.
|
||||
#[test]
|
||||
fn place_art_puts_a_copy_of_the_brush_art_where_it_is_dropped() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0);
|
||||
s.execute("brush.new", &json!({"type": "art", "name": "Bar", "ids": [r.0]})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Bar", "x": 100, "y": 80})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(selected(&s), vec![id]);
|
||||
assert_ne!(id, r, "a copy, not the art the brush was made from");
|
||||
assert!(close(bounds(&s, id), Rect::new(80.0, 76.0, 120.0, 84.0), 1e-6), "{:?}", bounds(&s, id));
|
||||
// Without a position: the first artboard's center (the document is 400 × 300).
|
||||
let scatter = NodeId(s.execute("brush.placeArt", &json!({"name": "Dots"})).unwrap()["id"].as_u64().unwrap());
|
||||
let c = bounds(&s, scatter).center();
|
||||
assert!((c.x - 200.0).abs() < 1e-6 && (c.y - 150.0).abs() < 1e-6, "{c:?}");
|
||||
let steps = undo_steps(&s);
|
||||
for (p, msg) in [
|
||||
(json!({"name": "3 pt. Round"}), "`3 pt. Round` has no art (only scatter, art and pattern brushes do)"),
|
||||
(json!({"name": "Bristle Round"}), "`Bristle Round` has no art (only scatter, art and pattern brushes do)"),
|
||||
(json!({"name": "Nope"}), "no brush named `Nope`"),
|
||||
] {
|
||||
let e = s.execute("brush.placeArt", &p).unwrap_err();
|
||||
assert!(e.to_string().contains(msg), "{p}: {e}");
|
||||
}
|
||||
assert!(s.execute("brush.placeArt", &json!({"name": "Bar", "x": "100"})).is_err());
|
||||
assert_eq!(undo_steps(&s), steps, "a refused call adds no undo step");
|
||||
}
|
||||
|
||||
/// Brush art holding an instance of a symbol whose art lies away from the symbol's origin (as
|
||||
/// imported symbols can) is centered by that art, not by the box an instance has without its
|
||||
/// document.
|
||||
#[test]
|
||||
fn placed_art_with_a_symbol_instance_is_centered_by_the_symbols_art() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 300.0, 10.0, 100.0, 40.0);
|
||||
let art = node(&s, r);
|
||||
s.execute("edit.clear", &json!({"ids": [r.0]})).unwrap();
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Off".into(), art: std::sync::Arc::new(art) });
|
||||
let layer = d.layers[0].id;
|
||||
let inst = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::translate((50.0, 50.0));
|
||||
d.insert(Some(layer), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Off".into(), xf })).unwrap();
|
||||
let inst = inst.0;
|
||||
s.execute("brush.new", &json!({"type": "art", "name": "Stamp", "ids": [inst]})).unwrap();
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Stamp", "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap());
|
||||
let st = s.doc().unwrap();
|
||||
let b = st.doc.bounds_of(&[id], false).unwrap();
|
||||
assert!((b.center().x - 200.0).abs() < 1e-6 && (b.center().y - 150.0).abs() < 1e-6, "{b:?}");
|
||||
assert!((b.width() - 100.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// A pattern brush with side, outer corner and start tiles, the side tile with a repeat frame
|
||||
/// wider than its art: → its name.
|
||||
fn framed_pattern_brush(s: &mut Session) -> String {
|
||||
let side = rect(s, 0.0, 0.0, 20.0, 10.0);
|
||||
let corner = rect(s, 0.0, 40.0, 10.0, 10.0);
|
||||
let start = rect(s, 0.0, 80.0, 6.0, 10.0);
|
||||
let name = s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "ids": [side.0]})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
let params = json!({
|
||||
"side": art_json(s, side),
|
||||
"side_frame": Rect::new(-2.0, 0.0, 22.0, 10.0),
|
||||
"outer_corner": art_json(s, corner),
|
||||
"start": art_json(s, start),
|
||||
});
|
||||
s.execute("brush.options", &json!({"name": name, "params": params})).unwrap();
|
||||
name
|
||||
}
|
||||
|
||||
/// `brush.placeArt` lays a pattern brush's tiles out left to right, each in a group named for its
|
||||
/// tile, with an unpainted rectangle at the back of a tile with a repeat frame marking that frame.
|
||||
#[test]
|
||||
fn pattern_brushes_place_their_tiles_in_a_row() {
|
||||
let mut s = session();
|
||||
let name = framed_pattern_brush(&mut s);
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": name, "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap());
|
||||
let placed = node(&s, id);
|
||||
let tiles: Vec<Node> = placed.children().unwrap().iter().map(|c| (**c).clone()).collect();
|
||||
let names: Vec<&str> = tiles.iter().map(|t| t.name.as_deref().unwrap_or("")).collect();
|
||||
assert_eq!(names, ["Side Tile", "Outer Corner Tile", "Start Tile"]);
|
||||
let boxes: Vec<Rect> = tiles.iter().map(|t| t.geometric_bounds().unwrap()).collect();
|
||||
assert!(boxes.windows(2).all(|w| (w[1].x0 - w[0].x1 - 10.0).abs() < 1e-6), "10 pt apart, left to right: {boxes:?}");
|
||||
// The side tile: the frame's rectangle, unpainted, behind the art.
|
||||
let side = tiles[0].children().unwrap();
|
||||
assert_eq!(side.len(), 2);
|
||||
let marker = &side[0];
|
||||
assert!(marker.appearance.items.iter().all(|i| match i {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => f.paint.is_none(),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(st) => st.paint.is_none(),
|
||||
}));
|
||||
let frame = marker.geometric_bounds().unwrap();
|
||||
assert!((frame.width() - 24.0).abs() < 1e-6 && (frame.height() - 10.0).abs() < 1e-6, "{frame:?}");
|
||||
assert_eq!(tiles[1].children().unwrap().len(), 1, "no frame, no rectangle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_options_rename_duplicate_and_delete_update_strokes() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -4489,6 +4489,41 @@ fn cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on(
|
||||
assert_eq!(owners(&mut s)[4..], [Value::Null, json!(1)]);
|
||||
}
|
||||
|
||||
/// The rulers' origin dragged out of their corner snaps as a drawn point does: onto a shape's
|
||||
/// corner and edge, the artboard's centre, and with Snap to Point along a ruler guide; with
|
||||
/// nothing on it stays at the pointer. The drag changes nothing, and its guides go when it ends.
|
||||
#[test]
|
||||
fn the_ruler_origin_dragged_from_the_corner_snaps_as_a_drawn_point() {
|
||||
use vectorcraft_geom::Point;
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
|
||||
let (n, doc) = (undo_len(&s), s.doc().unwrap().doc.clone());
|
||||
let v = ViewInfo::default();
|
||||
let at = |s: &mut Session, x, y| s.ruler_origin_drag(Some(Point::new(x, y)), v).unwrap();
|
||||
assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0), "the corner");
|
||||
assert!(!s.overlays(v).is_empty(), "the guide showing it");
|
||||
assert_eq!(at(&mut s, 130.0, 202.0), Point::new(130.0, 200.0), "the bottom edge");
|
||||
assert_eq!(at(&mut s, 398.0, 301.5), Point::new(400.0, 300.0), "the artboard's centre");
|
||||
assert_eq!(at(&mut s, 302.0, 50.0).x, 300.0, "along the ruler guide");
|
||||
assert_eq!(s.ruler_origin_drag(None, v), None, "off the canvas");
|
||||
assert!(s.overlays(v).is_empty());
|
||||
assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0));
|
||||
s.end_ruler_origin_drag();
|
||||
assert!(s.overlays(v).is_empty());
|
||||
assert_eq!((undo_len(&s), &*s.doc().unwrap().doc), (n, &*doc), "nothing changed");
|
||||
// Nothing on: it stays at the pointer.
|
||||
let off = ViewInfo { smart_guides: false, snap_to_point: false, ..v };
|
||||
assert_eq!(s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), off), Some(Point::new(101.5, 98.5)));
|
||||
s.end_ruler_origin_drag();
|
||||
// Snap to Grid: onto a gridline crossing.
|
||||
let grid = ViewInfo { snap_to_grid: true, ..v };
|
||||
let p = s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), grid).unwrap();
|
||||
s.end_ruler_origin_drag();
|
||||
assert_eq!(p, Point::new(p.x.round(), p.y.round()), "{p:?}");
|
||||
assert_ne!(p, Point::new(101.5, 98.5));
|
||||
}
|
||||
|
||||
/// Guides saved before guides had layers are put on a layer when the document opens.
|
||||
#[test]
|
||||
fn guides_from_older_files_are_put_on_a_layer() {
|
||||
|
||||
@@ -280,6 +280,103 @@ fn a_missing_link_is_reported_not_copied() {
|
||||
assert!(report.contains("blue.png: not found"), "{report}");
|
||||
}
|
||||
|
||||
/// Packaged for a client whose read root holds neither the document's file nor its links: the report,
|
||||
/// its Document Info part included, names them by their file names, and `document.info` gives no
|
||||
/// link. The person's report names them whole.
|
||||
#[test]
|
||||
fn a_confined_package_names_files_outside_the_read_root_by_name() {
|
||||
let dir = Folder::new("package-roots");
|
||||
let mut s = poster(&dir);
|
||||
std::fs::create_dir_all(dir.file("in")).unwrap();
|
||||
std::fs::remove_file(dir.file("art/blue.png")).unwrap();
|
||||
open(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let report = |r: &Value| {
|
||||
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap()
|
||||
};
|
||||
let person = report(&run(&mut s, "file.package", json!({})));
|
||||
assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}");
|
||||
assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}");
|
||||
assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}");
|
||||
|
||||
let in_root = dir.0.join("in");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap();
|
||||
let client = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
|
||||
let text = report(&client);
|
||||
assert!(text.contains("From: poster.vectorcraft\n"), "{text}");
|
||||
assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}");
|
||||
let base = dir.0.to_string_lossy().into_owned();
|
||||
assert!(!text.contains(&base), "{text}");
|
||||
for key in ["missingLinks", "warnings", "files"] {
|
||||
assert!(!client[key].to_string().contains(&base), "{key}: {client}");
|
||||
}
|
||||
// Document Info, whose report the package holds, gives no link either.
|
||||
for p in [json!({}), json!({"format": "text"})] {
|
||||
let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone()));
|
||||
assert!(!info.to_string().contains(&base), "{p}: {info}");
|
||||
}
|
||||
let info = run(&mut s, "document.info", json!({"format": "text"}));
|
||||
assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}");
|
||||
}
|
||||
|
||||
/// A missing link stored as a path relative to the document names a file inside a confined
|
||||
/// request's read root: the package report and Document Info give its stored path.
|
||||
#[test]
|
||||
fn a_relative_link_inside_the_read_root_keeps_its_path() {
|
||||
let dir = Folder::new("package-roots-relative");
|
||||
write(&dir.file("art/near.png"), &png(8, 8, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &dir.file("art/near.png"));
|
||||
let mut doc = (*s.doc().unwrap().doc).clone();
|
||||
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") };
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new("art/near.png"));
|
||||
write(&dir.file("near.vectorcraft"), &vectorcraft_format::save(&doc, false));
|
||||
// Missing, the link keeps its stored path when the document opens (the package copies the
|
||||
// image the document holds).
|
||||
std::fs::remove_file(dir.file("art/near.png")).unwrap();
|
||||
open(&mut s, &dir.file("near.vectorcraft"));
|
||||
let roots = crate::file_access::AutomationRoots::new(&[dir.0.as_path()], &[]).unwrap();
|
||||
let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
|
||||
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap();
|
||||
assert!(text.contains("\nart/near.png → Links/near.png\n"), "{text}");
|
||||
let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({})));
|
||||
let links: Vec<&Value> = info["images"].as_object().unwrap().values().map(|i| &i["link"]).collect();
|
||||
assert_eq!(links, [&json!("art/near.png")], "{info}");
|
||||
let text = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({"format": "text"})));
|
||||
assert!(text.to_string().contains("art/near.png"), "{text}");
|
||||
}
|
||||
|
||||
/// A link whose stored path names a place outside a confined request's read root, with its file
|
||||
/// found by name beside the document inside the root: the package report and reply give the file
|
||||
/// name, not the stored path.
|
||||
#[test]
|
||||
fn a_stored_path_outside_the_read_root_is_left_out_when_its_file_is_found_inside() {
|
||||
let dir = Folder::new("package-roots-stale");
|
||||
write(&dir.file("in/near.png"), &png(8, 8, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &dir.file("in/near.png"));
|
||||
let mut doc = (*s.doc().unwrap().doc).clone();
|
||||
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") };
|
||||
let stale = dir.file("out/near.png");
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new(&stale));
|
||||
write(&dir.file("in/near.vectorcraft"), &vectorcraft_format::save(&doc, false));
|
||||
// Missing when the document opens, the link keeps its stored path; the file then appears beside it.
|
||||
std::fs::remove_file(dir.file("in/near.png")).unwrap();
|
||||
open(&mut s, &dir.file("in/near.vectorcraft"));
|
||||
write(&dir.file("in/near.png"), &png(8, 8, RED));
|
||||
let in_root = dir.0.join("in");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap();
|
||||
let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
|
||||
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap();
|
||||
assert!(text.contains("\nnear.png → Links/near.png\n"), "{text}");
|
||||
assert!(!text.contains(&stale), "{text}");
|
||||
for key in ["missingLinks", "warnings", "files"] {
|
||||
assert!(!r[key].to_string().contains(&stale), "{key}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file missing from a document that moved keeps the place its relative path names from the
|
||||
/// document's folder: the packaged document writes its relative path from there.
|
||||
#[test]
|
||||
|
||||
@@ -1153,6 +1153,98 @@ fn deferred_stages_in_symbol_art_are_listed_and_refreshed() {
|
||||
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([]));
|
||||
}
|
||||
|
||||
/// `effect.refreshDeferred` takes the id of an object in the art of a symbol, pattern, brush or
|
||||
/// opacity mask, as `effect.deferredStatus` lists it: one with a deferred stage is refreshed, and
|
||||
/// one without (or whose stage is gone) adds nothing to the counts. The id of art that is no
|
||||
/// longer in the document is an error.
|
||||
#[test]
|
||||
fn refresh_takes_objects_in_definition_art() {
|
||||
let mut s = session();
|
||||
const FX: &str = "plugin.test.engine.deferred.nested";
|
||||
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
|
||||
install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.nested", "effect", "{}"), &out));
|
||||
// A symbol whose art holds an object with the effect and one without.
|
||||
let staged = rect(&mut s, 10.0, "#ff0000");
|
||||
let plain = rect(&mut s, 30.0, "#ff0000");
|
||||
run(&mut s, "effect.apply", json!({"ids": [staged.0], "effect": FX}));
|
||||
run(&mut s, "select.set", json!({"ids": [staged.0, plain.0]}));
|
||||
run(&mut s, "symbol.new", json!({"name": "Nested"}));
|
||||
// A pattern, an art brush (its source deleted) and an opacity mask, none with a stage.
|
||||
let tile = rect(&mut s, 50.0, "#00ff00");
|
||||
run(&mut s, "select.set", json!({"ids": [tile.0]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tile", "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let bar = rect(&mut s, 70.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [bar.0]}));
|
||||
run(&mut s, "brush.new", json!({"type": "art", "name": "Bar"}));
|
||||
run(&mut s, "edit.clear", json!({"ids": [bar.0]}));
|
||||
let masked = rect(&mut s, 90.0, "#ff0000");
|
||||
let mask = rect(&mut s, 90.0, "#ffffff");
|
||||
run(&mut s, "select.set", json!({"ids": [masked.0, mask.0]}));
|
||||
run(&mut s, "transparency.makeOpacityMask", json!({}));
|
||||
// A layer object with a stage that stays deferred, and one without.
|
||||
let kept = rect(&mut s, 130.0, "#ff0000");
|
||||
run(&mut s, "effect.apply", json!({"ids": [kept.0], "effect": FX}));
|
||||
let bare = rect(&mut s, 150.0, "#ff0000");
|
||||
|
||||
// The ids of the objects of `art` that are not in the layers.
|
||||
let nested = |s: &Session, art: &vectorcraft_doc::Node| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut ids = Vec::new();
|
||||
vectorcraft_doc::swatches::walk_with_masks(art, &mut |n| {
|
||||
if d.node(n.id).is_none() {
|
||||
ids.push(n.id.0);
|
||||
}
|
||||
});
|
||||
ids
|
||||
};
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let in_symbol = nested(&s, &d.symbols[0].art);
|
||||
let in_pattern = d.patterns.iter().flat_map(|p| p.art.iter().flat_map(|a| nested(&s, a))).collect::<Vec<_>>();
|
||||
let brushes = vectorcraft_brush::library(&d);
|
||||
let in_brush = brushes.iter().flat_map(|b| b.art().into_iter().flat_map(|a| nested(&s, a)).collect::<Vec<_>>()).collect::<Vec<_>>();
|
||||
let in_mask = d.node(masked).and_then(|n| n.extras().mask.as_ref()).map(|m| nested(&s, &m.art)).unwrap_or_default();
|
||||
for (what, ids) in [("symbol", &in_symbol), ("pattern", &in_pattern), ("brush", &in_brush), ("opacity mask", &in_mask)] {
|
||||
assert!(!ids.is_empty(), "the {what} art has an object outside the layers");
|
||||
}
|
||||
|
||||
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
|
||||
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
|
||||
s.doc_mut().unwrap().plugin_effects = fx.clone();
|
||||
fx.view(|| drawn(&s));
|
||||
fx.first_view_done();
|
||||
let listed = |s: &mut Session| {
|
||||
run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::<Vec<_>>()
|
||||
};
|
||||
let deferred = listed(&mut s);
|
||||
let [nested_staged, last] = deferred[..] else { panic!("two stages: {deferred:?}") };
|
||||
assert!(in_symbol.contains(&nested_staged) && last == kept.0, "{deferred:?} {in_symbol:?}");
|
||||
let Some(&nested_plain) = in_symbol.iter().find(|i| **i != nested_staged) else { panic!("{in_symbol:?}") };
|
||||
|
||||
// Objects without a stage, each on its own and together: nothing to refresh.
|
||||
let none = json!({"refreshed": 0, "stillDeferred": 0, "failed": 0});
|
||||
let mut plain_ids = vec![nested_plain, in_pattern[0], in_brush[0], in_mask[0], bare.0];
|
||||
for id in &plain_ids {
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": id})), none, "object {id}");
|
||||
}
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), none);
|
||||
assert_eq!(listed(&mut s), [nested_staged, kept.0]);
|
||||
|
||||
// The staged object of the symbol's art, by its id, with the others.
|
||||
step.store(0, std::sync::atomic::Ordering::Relaxed);
|
||||
plain_ids.push(nested_staged);
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0}));
|
||||
assert_eq!(listed(&mut s), [kept.0]);
|
||||
// Its stage is gone; the object is still there.
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": nested_staged})), none);
|
||||
|
||||
// Art no longer in the document, and an id of no object.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).patterns.clear();
|
||||
assert!(s.execute("effect.refreshDeferred", &json!({"id": in_pattern[0]})).is_err(), "the pattern is gone");
|
||||
assert!(s.execute("effect.refreshDeferred", &json!({"ids": [nested_plain, 999_999]})).is_err(), "not an object of the document");
|
||||
assert_eq!(listed(&mut s), [kept.0]);
|
||||
}
|
||||
|
||||
/// `CRAFT_PLUGIN_PAINTS_WASM=<folder>` saves a test live effect to try in the app
|
||||
/// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its
|
||||
/// object's stroke is 5 pt wide, and hands the geometry back otherwise.
|
||||
@@ -1820,11 +1912,11 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() {
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grant that a load of the plug-in store should forget and can't stays out of the approvals for
|
||||
/// the session: both when `grants.json` can't be rewritten and when it can't be read at the load.
|
||||
/// A grant recorded later counts again, and another store starts with nothing ignored.
|
||||
/// A grant that a load of the plug-in store should forget and can't stays out of the approvals in
|
||||
/// the process: both when `grants.json` can't be rewritten and when it can't be read at the load.
|
||||
/// A grant recorded later counts again, and another store's grant for the id counts.
|
||||
#[test]
|
||||
fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
|
||||
fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-load-forget");
|
||||
let elsewhere = crate::tests_links::Folder::new("plugin-store-load-forget-other");
|
||||
@@ -1856,8 +1948,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
|
||||
next.attach_plugin_store(elsewhere.0.clone());
|
||||
assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
|
||||
|
||||
// A load that can rewrite the file forgets the grant, and the store has nothing ignored again.
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
next.attach_plugin_store(folder.0.clone());
|
||||
assert!(!grants.exists(), "the load removes the grant");
|
||||
|
||||
// A directory at the file's path gives a read error on every platform.
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
std::fs::create_dir(&grants).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut third = session();
|
||||
@@ -1883,6 +1979,180 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
|
||||
run(&mut third, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grant one session stops counting stops counting for every session in the process attached to
|
||||
/// the same folder, by any path to it: one attached before, one attached after with no stored module
|
||||
/// to try the removal for, and one that comes back from another folder. A successful write of the
|
||||
/// grant in any of them makes it count in all of them again.
|
||||
#[test]
|
||||
fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-shared-ignore");
|
||||
let elsewhere = crate::tests_links::Folder::new("plugin-store-shared-ignore-other");
|
||||
let id = "test.engine.permissions.sharedignore";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let needs_approval = json!({"dataBase64": approved_data});
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
|
||||
let recorded = serde_json::to_vec(&json!([entry])).unwrap();
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
let mut first = session();
|
||||
first.attach_plugin_store(folder.0.clone());
|
||||
let inside = folder.0.join("inside");
|
||||
std::fs::create_dir(&inside).unwrap();
|
||||
let mut other = session();
|
||||
other.attach_plugin_store(inside.join(".."));
|
||||
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
|
||||
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)}));
|
||||
let file = first.stored_plugin_file(id).unwrap();
|
||||
assert!(!std::path::Path::new(&file).exists(), "the store keeps no module");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
|
||||
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it");
|
||||
let refused = other.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(refused.contains("doc.read"), "{refused}");
|
||||
std::fs::write(&file, &approved).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
other.load_stored_plugins();
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "the formerly approved module isn't loaded");
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
|
||||
let mut later = session();
|
||||
later.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it");
|
||||
|
||||
std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap();
|
||||
other.attach_plugin_store(elsewhere.0.clone());
|
||||
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
|
||||
other.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't");
|
||||
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written");
|
||||
for s in [&mut first, &mut other, &mut later] {
|
||||
assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again");
|
||||
}
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
}
|
||||
|
||||
/// A plug-in folder that doesn't exist yet gets the key it gets once it is made, and every path to a
|
||||
/// folder gets the same key.
|
||||
#[test]
|
||||
fn a_plugin_folder_has_one_key_for_every_path_to_it() {
|
||||
use crate::store::plugin_store_key;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-key");
|
||||
let dir = folder.0.join("Plug-ins");
|
||||
let before = plugin_store_key(&dir);
|
||||
assert_eq!(plugin_store_key(&dir.join("sub").join("..")), before);
|
||||
assert_eq!(plugin_store_key(&folder.0.join(".").join("Plug-ins")), before);
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
assert_eq!(plugin_store_key(&dir), before, "the key stays when the folder is made");
|
||||
assert_eq!(plugin_store_key(&dir.join(".")), before);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let plain = std::path::absolute(&dir).unwrap();
|
||||
let verbatim = std::path::PathBuf::from(format!(r"\\?\{}", plain.display()));
|
||||
assert_eq!(plugin_store_key(&verbatim), before, "a verbatim path names the same folder");
|
||||
}
|
||||
}
|
||||
|
||||
/// Sessions attached to a plug-in folder before it exists, by paths that only name the same folder
|
||||
/// once it is made, share the grants the process doesn't count for it. A grant that one session
|
||||
/// writes while another fails to remove it keeps counting.
|
||||
#[test]
|
||||
fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-late-folder");
|
||||
let id = "test.engine.permissions.latefolder";
|
||||
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
|
||||
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
|
||||
std::fs::create_dir_all(folder.0.join("a").join("b")).unwrap();
|
||||
let dir = folder.0.join("a").join("Plug-ins");
|
||||
// On disk `link/..` is `a`, so `link/../Plug-ins` is the folder; by name it is a `Plug-ins` beside `a`.
|
||||
// On Windows the folder is named in other letter case.
|
||||
#[cfg(unix)]
|
||||
let alias = {
|
||||
std::os::unix::fs::symlink(folder.0.join("a").join("b"), folder.0.join("link")).unwrap();
|
||||
folder.0.join("link").join("..").join("Plug-ins")
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let alias = folder.0.join("A").join("PLUG-INS");
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let alias = dir.clone();
|
||||
let mut first = session();
|
||||
first.attach_plugin_store(dir.clone());
|
||||
let mut other = session();
|
||||
other.attach_plugin_store(alias);
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap();
|
||||
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
|
||||
|
||||
first.ignore_stored_grant(id, first.grant_writes());
|
||||
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it");
|
||||
assert!(other.store_grant(id, Some(serde_json::from_value(entry.clone()).unwrap())), "the file can be written");
|
||||
assert_eq!(run(&mut first, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again");
|
||||
|
||||
// A write that fails in one session while another writes the grant for the id leaves the grant
|
||||
// counting.
|
||||
let before = first.grant_writes();
|
||||
assert!(other.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the other session writes the grant");
|
||||
first.ignore_stored_grant(id, before);
|
||||
assert_eq!(run(&mut first, "plugin.inspect", needs_approval)["needsApproval"], false, "the written grant counts");
|
||||
std::fs::remove_file(dir.join("grants.json")).unwrap();
|
||||
}
|
||||
|
||||
/// Grant writes that change nothing, each for another id, don't grow what the process keeps past its
|
||||
/// limit.
|
||||
#[test]
|
||||
fn the_process_keeps_a_bounded_number_of_grant_writes() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-writes-kept");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
for n in 0..300 {
|
||||
assert!(s.store_grant(&format!("test.engine.permissions.unknown{n}"), None), "nothing to remove is a success");
|
||||
}
|
||||
assert!(Session::grant_writes_kept() <= 256, "{}", Session::grant_writes_kept());
|
||||
}
|
||||
|
||||
/// A session attached by a link to a plug-in folder matches the grants the process doesn't count
|
||||
/// with the folder the link leads to now, not the one it led to when the session was attached.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-relinked");
|
||||
let id = "test.engine.permissions.relinked";
|
||||
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
|
||||
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
|
||||
let recorded = serde_json::to_vec(&json!([entry])).unwrap();
|
||||
let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins"));
|
||||
for dir in [&old, &new] {
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
std::fs::write(dir.join("grants.json"), &recorded).unwrap();
|
||||
}
|
||||
std::os::unix::fs::symlink(&old, &link).unwrap();
|
||||
let mut linked = session();
|
||||
linked.attach_plugin_store(link.clone());
|
||||
assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
|
||||
|
||||
std::fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink(&new, &link).unwrap();
|
||||
let mut direct = session();
|
||||
direct.attach_plugin_store(new.clone());
|
||||
direct.ignore_stored_grant(id, direct.grant_writes());
|
||||
assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the link leads to the ignored grant");
|
||||
assert!(linked.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written");
|
||||
assert_eq!(run(&mut direct, "plugin.inspect", needs_approval)["needsApproval"], false, "it counts again");
|
||||
}
|
||||
|
||||
/// A grants file that can't be opened or read may name the old module once it reads again, so
|
||||
/// neither a module listing no permissions nor `plugin.remove` gets past it. A directory at the
|
||||
/// file's path gives a read error on every platform.
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! The preferences commands under automation roots: a confined request sees a folder preference and
|
||||
//! an export preset's folder only inside its read roots.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::fileio::ScreenExportPreset;
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn text(p: &Path) -> String {
|
||||
p.to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
/// A fresh scratch folder for one test, with the folders `in` and `out`.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-prefs-roots-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
for sub in ["in", "out"] {
|
||||
std::fs::create_dir_all(dir.join(sub)).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// The folder preferences that name the folder outside the read root.
|
||||
const OUTSIDE: [&str; 3] = ["pluginsFolder", "scratchPrimary", "templatesFolder"];
|
||||
|
||||
/// A session whose folder preferences name `inside` (fonts, and the Data Recovery folder with
|
||||
/// spaces around it) and `outside` (the [`OUTSIDE`] ones, the Templates folder with spaces around
|
||||
/// it), with a scratch disk choice and an export preset kept with each folder.
|
||||
fn session(inside: &str, outside: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.prefs.fonts_folder = inside.to_string();
|
||||
s.prefs.recovery_folder = format!(" {inside} ");
|
||||
s.prefs.plugins_folder = outside.to_string();
|
||||
s.prefs.scratch_primary = outside.to_string();
|
||||
s.prefs.scratch_secondary = "None".to_string();
|
||||
s.prefs.templates_folder = format!(" {outside} ");
|
||||
for (name, folder) in [("Inside", inside), ("Outside", outside)] {
|
||||
let settings = json!({"formats": [{"format": "svg"}], "folder": folder});
|
||||
s.prefs.screen_export_presets.push(ScreenExportPreset { name: name.into(), settings: settings.as_object().cloned().unwrap_or_default() });
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Does a string anywhere in `v` hold `path`?
|
||||
fn holds(v: &Value, path: &str) -> bool {
|
||||
v.to_string().contains(&path.replace('\\', "\\\\"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefs_commands_leave_out_folders_outside_the_read_root() {
|
||||
let base = folder("get");
|
||||
let (inside, outside) = (text(&base.join("in").join("fonts")), text(&base.join("out")));
|
||||
let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap();
|
||||
let mut s = session(&inside, &outside);
|
||||
|
||||
let all = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({})));
|
||||
let prefs = &all["prefs"];
|
||||
assert_eq!(prefs["fontsFolder"], json!(inside), "a folder inside the root is shown");
|
||||
assert_eq!(prefs["recoveryFolder"], json!(format!(" {inside} ")), "checked without the spaces, shown as kept");
|
||||
assert_eq!(prefs["scratchSecondary"], json!("None"), "a scratch disk choice is shown");
|
||||
for key in OUTSIDE {
|
||||
assert_eq!(prefs[key], Value::Null, "{key}: {all}");
|
||||
}
|
||||
let presets = prefs["screenExportPresets"].as_array().unwrap();
|
||||
assert_eq!(presets[0]["settings"]["folder"], json!(inside));
|
||||
assert_eq!(presets[1]["name"], json!("Outside"), "the preset stays");
|
||||
assert!(presets[1]["settings"].get("folder").is_none(), "{all}");
|
||||
assert!(!holds(&all, &outside), "{all}");
|
||||
|
||||
for key in OUTSIDE {
|
||||
let one = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": key})));
|
||||
assert_eq!(one, Value::Null, "{key}");
|
||||
}
|
||||
assert_eq!(confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": "fontsFolder"}))), json!(inside));
|
||||
|
||||
let list = confine(roots.as_ref(), || run(&mut s, "prefs.list", json!({})));
|
||||
assert!(!holds(&list, &outside), "{list}");
|
||||
let row = |key: &str| list.as_array().unwrap().iter().find(|r| r["key"] == key).cloned().unwrap();
|
||||
assert_eq!(row("fontsFolder")["value"], json!(inside));
|
||||
assert_eq!(row("pluginsFolder")["value"], Value::Null);
|
||||
assert_eq!(row("pluginsFolder")["kind"], json!("text"), "the row stays");
|
||||
|
||||
// A request that sets another preference, or resets a category without folders.
|
||||
let set = confine(roots.as_ref(), || run(&mut s, "prefs.set", json!({"values": {"keyboardIncrement": 2, "pluginsFolder": outside}})));
|
||||
assert_eq!(set, json!({"keyboardIncrement": 2.0, "pluginsFolder": null}), "a folder kept as it was is left out too");
|
||||
let reset = confine(roots.as_ref(), || run(&mut s, "prefs.reset", json!({"category": "General"})));
|
||||
assert!(!holds(&reset, &outside), "{reset}");
|
||||
assert_eq!(reset["prefs"]["fontsFolder"], json!(inside));
|
||||
|
||||
// Unconfined and with only a write root.
|
||||
let all = run(&mut s, "prefs.get", json!({}));
|
||||
assert_eq!(all["prefs"]["pluginsFolder"], json!(outside), "unconfined, the folder is shown");
|
||||
assert_eq!(all["prefs"]["screenExportPresets"][1]["settings"]["folder"], json!(outside));
|
||||
let write_only = AutomationRoots::new(&[], &[&base.join("in")]).unwrap();
|
||||
let all = confine(write_only.as_ref(), || run(&mut s, "prefs.get", json!({})));
|
||||
assert_eq!(all["prefs"]["fontsFolder"], Value::Null, "without a read root no folder is shown");
|
||||
assert_eq!(all["prefs"]["recoveryFolder"], Value::Null);
|
||||
assert_eq!(s.prefs.plugins_folder, outside, "the preferences are unchanged");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
@@ -483,6 +483,105 @@ fn the_folder_store_reads_no_linked_entries() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A file where a folder of the store's path should be: the error names that file, not the area
|
||||
/// folder or the copy below it, for a write, a lock, a read, a listing, a removal and a recovery
|
||||
/// save.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folder_errors_name_a_file_in_the_way() {
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-file-in-way-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let file = base.join("file");
|
||||
std::fs::write(&file, b"").unwrap();
|
||||
let folder = file.join("recovery");
|
||||
let store = FolderStore::new(&folder);
|
||||
let mut s = Session::new();
|
||||
s.prefs.recovery_folder = folder.to_string_lossy().to_string();
|
||||
s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
|
||||
let errors = [
|
||||
("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err()),
|
||||
("lock", store.lock("1-2").err()),
|
||||
("read", store.read("1-1/Untitled-1-1.vectorcraft").err()),
|
||||
("list", store.list().err()),
|
||||
("remove", store.remove("1-1/Untitled-1-1.vectorcraft").err()),
|
||||
("save", s.execute("file.recovery.save", &json!({})).err().map(|e| e.to_string())),
|
||||
];
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let named = format!("{} is not a folder: ", file.display());
|
||||
let wrong: Vec<_> = errors.iter().filter(|(_, e)| !e.as_deref().is_some_and(|e| e.contains(&named))).collect();
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
/// A removal that finds the copy missing because a file is on the way to it (how Windows reports a
|
||||
/// file in the way) names that file. A copy that is just not there still counts as removed.
|
||||
#[test]
|
||||
fn a_removal_reported_missing_names_a_file_in_the_way() {
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-remove-in-way-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let file = base.join("file");
|
||||
std::fs::write(&file, b"").unwrap();
|
||||
let missing = || std::io::Error::from(std::io::ErrorKind::NotFound);
|
||||
let behind = FolderStore::removed(&file.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing()));
|
||||
let gone = FolderStore::removed(&base.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let named = format!("{} is not a folder: ", file.display());
|
||||
assert!(behind.as_ref().is_err_and(|e| e.starts_with(&named)), "{behind:?}");
|
||||
assert_eq!(gone, Ok(()));
|
||||
}
|
||||
|
||||
/// A folder of the store's path that is missing and can't be made: a write or a lock names it as
|
||||
/// the folder it couldn't make, and a read names it as missing. An area folder that can't be made
|
||||
/// in a store folder that is there is named the same way.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folder_errors_name_a_missing_folder_that_cannot_be_made() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-missing-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let closed = base.join("closed");
|
||||
std::fs::create_dir_all(&closed).unwrap();
|
||||
std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o500)).unwrap();
|
||||
let gone = closed.join("gone");
|
||||
let store = FolderStore::new(gone.join("recovery"));
|
||||
let unmade = format!("couldn't make {}: ", gone.display());
|
||||
let area = FolderStore::new(&closed).write("1-1/Untitled-1-1.vectorcraft", b"copy").err();
|
||||
let errors = [
|
||||
("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err(), unmade.clone()),
|
||||
("lock", store.lock("1-2").err(), unmade),
|
||||
("read", store.read("1-1/Untitled-1-1.vectorcraft").err(), format!("{} is missing", gone.display())),
|
||||
("area", area, format!("couldn't make {}: ", closed.join("1-1").display())),
|
||||
];
|
||||
std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
// An account that can write anywhere (root) makes the folders, so the test has nothing to check.
|
||||
if errors[0].1.is_none() {
|
||||
return;
|
||||
}
|
||||
let wrong: Vec<_> = errors.iter().filter(|(_, e, named)| !e.as_deref().is_some_and(|e| e.starts_with(named.as_str()))).collect();
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
/// When every folder on the way is there, an error names the folder it happened on.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folder_errors_name_the_folder_when_every_folder_is_there() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-unreadable-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let unreadable = base.join("unreadable");
|
||||
std::fs::create_dir_all(&unreadable).unwrap();
|
||||
std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o300)).unwrap();
|
||||
let listed = FolderStore::new(&unreadable).list();
|
||||
std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
// An account that can read any folder (root) lists it, so the test has nothing to check.
|
||||
let Err(err) = listed else { return };
|
||||
assert!(err.starts_with(&format!("{}: ", unreadable.display())), "{err}");
|
||||
}
|
||||
|
||||
/// A store in memory that notes each removal of an area (its lock file and folder, then its empty
|
||||
/// folder) and whether the area was still held then.
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -40,6 +40,50 @@ fn objects(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.node_count()
|
||||
}
|
||||
|
||||
/// A client confined by automation roots: a save without a path writes the document's own file, and
|
||||
/// when that file is outside the read roots the reply leaves out its `path` and names the files
|
||||
/// written beside it by their file names. A reply without a path leaves out a suggested `folder`
|
||||
/// outside them. A path inside the read roots, and one the client gives, stay whole.
|
||||
#[test]
|
||||
fn a_confined_save_leaves_out_paths_outside_the_read_root() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let d = dir("roots");
|
||||
let (inside, outside) = (d.join("in"), d.join("out"));
|
||||
for f in [&inside, &outside] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
rect(&mut s);
|
||||
let own = path(&outside, "doc.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": own})).unwrap();
|
||||
let person = s.execute("document.save", &json!({"separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = person["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert_eq!((files.len(), files[0].as_str()), (3, own.as_str()), "{person}");
|
||||
|
||||
let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap();
|
||||
let run = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, id: &str, p: Value| {
|
||||
confine(roots.as_ref(), || s.execute(id, &p)).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
};
|
||||
let hidden = outside.to_string_lossy().into_owned();
|
||||
let r = run(&mut s, &write_only, "document.save", json!({}));
|
||||
assert!(r.get("path").is_none() && r["bytes"].as_u64().is_some_and(|n| n > 0), "{r}");
|
||||
assert!(!r.to_string().contains(&hidden), "{r}");
|
||||
let r = run(&mut s, &write_only, "document.save", json!({"separateArtboards": true}));
|
||||
let names: Vec<Value> = files.iter().map(|f| json!(std::path::Path::new(f).file_name().unwrap().to_string_lossy())).collect();
|
||||
assert_eq!((r.get("path"), r["files"].as_array()), (None, Some(&names)), "{r}");
|
||||
// Inside the read roots, or given by the client: whole.
|
||||
assert_eq!(run(&mut s, &both, "document.save", json!({}))["path"], json!(own));
|
||||
assert_eq!(run(&mut s, &write_only, "document.save", json!({"path": own}))["path"], json!(own));
|
||||
// A save without a path known suggests the document's folder.
|
||||
let r = run(&mut s, &write_only, "file.saveCopy", json!({}));
|
||||
assert!(r.get("folder").is_none() && r["name"] == "doc copy.vectorcraft" && r.get("dataBase64").is_some(), "{r}");
|
||||
assert_eq!(run(&mut s, &both, "file.saveCopy", json!({}))["folder"], json!(hidden));
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_svg_path_writes_svg_and_save_writes_it_back() {
|
||||
let d = dir("svg");
|
||||
|
||||
@@ -87,6 +87,87 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
|
||||
assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painted_and_sketched_styles_set_every_effect_setting_and_reopen_applied() {
|
||||
let mut s = session();
|
||||
let list = run(&mut s, "graphicStyle.libraries", json!({}));
|
||||
let libs = list["libraries"].as_array().unwrap();
|
||||
let at = libs.iter().position(|l| l["id"] == "painted-sketched").expect("listed");
|
||||
assert_eq!((libs[at]["name"].as_str(), libs[at]["count"].as_u64()), (Some("Painted and Sketched"), Some(7)));
|
||||
assert_eq!(libs[at - 1]["id"], "textures");
|
||||
let g = run(&mut s, "graphicStyle.library", json!({"library": "Painted and Sketched"}));
|
||||
let listed: Vec<(&str, &str, Vec<&str>)> =
|
||||
g["styles"].as_array().unwrap().iter().map(|x| (x["name"].as_str().unwrap(), x["fill"].as_str().unwrap(), names(&x["effects"]))).collect();
|
||||
let want = [
|
||||
("Washed Blue", "#8ab9c9", "artistic.watercolor"),
|
||||
("Bristle Ochre", "#c4975a", "artistic.dryBrush"),
|
||||
("Pastel Heather", "#a78ca5", "artistic.roughPastels"),
|
||||
("Charcoal Shade", "#666666", "sketch.charcoal"),
|
||||
("Ink Contour", "#d9e2df", "brushStrokes.inkOutlines"),
|
||||
("Wet Ink", "#637b85", "brushStrokes.sumiE"),
|
||||
("Fine Pen", "#d8d4c6", "sketch.graphicPen"),
|
||||
];
|
||||
assert_eq!(listed, want.iter().map(|&(n, f, e)| (n, f, vec![e])).collect::<Vec<_>>());
|
||||
// Every setting of each effect is given, with the catalog's key and kind of value.
|
||||
let (_, lib) = cmd::stylelib::library(&s, "painted-sketched").unwrap();
|
||||
for st in &lib.styles {
|
||||
let e = &st.appearance.effects[0];
|
||||
let defaults = vectorcraft_render::effects::effect_info(&e.id).unwrap().defaults;
|
||||
let (set, all) = (e.params.as_object().unwrap(), defaults.as_object().unwrap());
|
||||
let keys = |m: &serde_json::Map<String, Value>| m.keys().cloned().collect::<Vec<_>>();
|
||||
assert_eq!(keys(set), keys(all), "{}", st.name);
|
||||
for (k, v) in set {
|
||||
let kind = |v: &Value| (v.is_number(), v.is_string(), v.is_boolean());
|
||||
assert_eq!(kind(v), kind(&all[k]), "{} / {k}", st.name);
|
||||
}
|
||||
}
|
||||
let strokes: Vec<(&str, f64)> =
|
||||
lib.styles.iter().filter(|g| g.appearance.stroke_paint() != Paint::None).map(|g| (g.name.as_str(), g.appearance.stroke_width())).collect();
|
||||
assert_eq!(strokes, [("Bristle Ochre", 1.0), ("Ink Contour", 1.0)]);
|
||||
|
||||
// Each one adds and applies to a rectangle in one undo step.
|
||||
let mut ids = vec![];
|
||||
for (i, (name, fill, effect)) in want.iter().enumerate() {
|
||||
let id = rect(&mut s, 10.0 + 25.0 * i as f64, 20.0, 20.0, 30.0);
|
||||
let before = undo_len(&s);
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": name, "apply": true, "ids": [id.0]}));
|
||||
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![*name], Some(*name)));
|
||||
assert_eq!(undo_len(&s), before + 1, "{name}");
|
||||
let node = doc(&s).node(id).unwrap();
|
||||
assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex(fill).unwrap()), "{name}");
|
||||
assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), [*effect]);
|
||||
assert_eq!(node.appearance.effects[0].params, lib.style(name).unwrap().appearance.effects[0].params, "{name}");
|
||||
ids.push((id, *name));
|
||||
}
|
||||
// Adding one again reuses it: no new style, no undo step.
|
||||
let before = (undo_len(&s), doc(&s).graphic_styles.len());
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Wet Ink"}));
|
||||
assert_eq!((names(&r["added"]), names(&r["existing"])), (vec![], vec!["Wet Ink"]));
|
||||
assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before);
|
||||
// An unknown style or library changes nothing.
|
||||
assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-sketched", "names": ["Wet Ink", "Nope"]})).is_err());
|
||||
assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-and-sketched", "name": "Wet Ink"})).is_err());
|
||||
assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before);
|
||||
|
||||
// Saved and opened again, the styles keep their effects and the rectangles stay linked to them.
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
run(&mut s, "document.open", json!({"name": "painted.vectorcraft", "dataBase64": b64}));
|
||||
for (id, name) in &ids {
|
||||
let d = doc(&s);
|
||||
let style = d.graphic_style(name).unwrap();
|
||||
assert!(style.same_look(lib.style(name).unwrap()), "{name}");
|
||||
let node = d.node(*id).unwrap();
|
||||
assert_eq!((node.extras().graphic_style, &node.appearance.effects), (Some(style.id), &style.appearance.effects), "{name}");
|
||||
}
|
||||
|
||||
// With nothing selected, `apply` only adds; empty `names` adds the whole library in order.
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Fine Pen", "apply": true}));
|
||||
assert!(r.get("applied").is_none() && doc(&s).graphic_style("Fine Pen").is_some());
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "names": []}));
|
||||
assert_eq!((names(&r["added"]), names(&r["existing"])), (want[..6].iter().map(|w| w.0).collect::<Vec<_>>(), vec!["Fine Pen"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_dedupes_names_as_one_undo_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -798,6 +798,39 @@ fn a_pattern_library_adds_only_the_picked_pattern_and_it_undoes_and_saves() {
|
||||
assert_eq!(back.swatch("Checkerboard").map(|w| &w.paint), doc(&s).swatch("Checkerboard").map(|w| &w.paint));
|
||||
}
|
||||
|
||||
/// Grit Textures is listed after Geometric Patterns. One of its patterns comes in with its swatch
|
||||
/// once, as one undo step that also takes both away, and both stay after a save and reopen.
|
||||
#[test]
|
||||
fn a_grit_texture_adds_once_undoes_and_saves() {
|
||||
let mut s = session();
|
||||
let list = run(&mut s, "swatch.library.list", json!({}));
|
||||
let ids: Vec<&str> =
|
||||
list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "patterns").map(|l| l["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["geometric-patterns", "grit-textures"]);
|
||||
let got = run(&mut s, "swatch.library.get", json!({"library": "Grit Textures"}));
|
||||
let names: Vec<&str> = got["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Fine Grain", "Coarse Grit", "Sand", "Speckle", "Stipple", "Scratches", "Sparse Flecks", "Dense Flecks"]);
|
||||
let counts = |d: &vectorcraft_doc::Document| (d.patterns.len(), d.swatches_iter().count());
|
||||
let empty = counts(doc(&s));
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]}));
|
||||
assert_eq!(r["added"], json!(["Stipple"]));
|
||||
assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1));
|
||||
let def = doc(&s).pattern("Stipple").expect("the pattern comes with its swatch").clone();
|
||||
assert!(def.art.len() >= 144, "{} marks", def.art.len());
|
||||
assert!(matches!(doc(&s).swatch("Stipple").map(|w| &w.paint), Some(Paint::Pattern { pattern, .. }) if pattern == "Stipple"));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]}));
|
||||
assert_eq!((r["added"].clone(), r["existing"].clone()), (json!([]), json!(["Stipple"])));
|
||||
assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1), "added once");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(counts(doc(&s)), empty);
|
||||
assert!(doc(&s).pattern("Stipple").is_none() && doc(&s).swatch("Stipple").is_none());
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc(&s), false)).unwrap();
|
||||
assert_eq!(back.pattern("Stipple"), Some(&def));
|
||||
assert_eq!(back.swatch("Stipple").map(|w| &w.paint), doc(&s).swatch("Stipple").map(|w| &w.paint));
|
||||
}
|
||||
|
||||
/// A device name is saved with a `-` after it, which can be another library's own name: neither
|
||||
/// library replaces the other, and saving either again replaces only itself.
|
||||
#[test]
|
||||
|
||||
@@ -114,3 +114,12 @@ fn keys_named(doc: &str) -> Vec<String> {
|
||||
}
|
||||
found.into_iter().map(|(k, _)| k).collect()
|
||||
}
|
||||
|
||||
/// Turn notes the key walk above doesn't reach: a numeric reflection axis and the Scatter brush's
|
||||
/// `rotation [a, b]` range, whose head isn't a plain key.
|
||||
#[test]
|
||||
fn turns_outside_plain_keys_say_which_way() {
|
||||
let doc = |id: &str| command_specs().iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default();
|
||||
assert!(doc("object.reflect").contains("|deg (the mirror line, counter-clockwise from horizontal"), "object.reflect's numeric axis");
|
||||
assert!(doc("brush.options").contains("rotation [a, b] −180..180° (counter-clockwise)"), "the Scatter brush's rotation");
|
||||
}
|
||||
|
||||
@@ -751,6 +751,27 @@ impl Session {
|
||||
self.apply_actions(acts).map(drop)
|
||||
}
|
||||
|
||||
/// The rulers' origin dragged out of their corner, whatever the tool, with the pointer at `p` in
|
||||
/// document space (none off the canvas): where it goes, snapped as a drawn point is
|
||||
/// ([`vectorcraft_tools::rulerguide::OriginDrag`]), the targets gathered on the drag's first
|
||||
/// call. It changes nothing: the caller sets the origin where the button is released
|
||||
/// (`document.setRulerOrigin`) and ends the drag ([`Session::end_ruler_origin_drag`]).
|
||||
pub fn ruler_origin_drag(&mut self, p: Option<Point>, view: ViewInfo) -> Option<Point> {
|
||||
let drag = match self.ruler_origin.take() {
|
||||
Some(d) => Some(d),
|
||||
None => self.with_tool_cx(view, |_, cx| Some(vectorcraft_tools::rulerguide::OriginDrag::new(cx))),
|
||||
};
|
||||
let Some(mut drag) = drag else { return p };
|
||||
let at = self.with_tool_cx(view, |_, cx| drag.pointer(cx, p));
|
||||
self.ruler_origin = Some(drag);
|
||||
at
|
||||
}
|
||||
|
||||
/// The drag of the rulers' origin ended, released or cancelled: its guides go.
|
||||
pub fn end_ruler_origin_drag(&mut self) {
|
||||
self.ruler_origin = None;
|
||||
}
|
||||
|
||||
/// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the
|
||||
/// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event.
|
||||
pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result<Vec<UiRequest>> {
|
||||
@@ -1112,6 +1133,9 @@ impl Session {
|
||||
v.extend(self.with_tool_cx(view, |_, cx| g.overlays(cx)));
|
||||
self.ruler_guide = Some(g);
|
||||
}
|
||||
if let Some(d) = &self.ruler_origin {
|
||||
v.extend(d.overlays());
|
||||
}
|
||||
let deferred_preview = self.unapplied_interaction_preview();
|
||||
if let Some(d) = self.active() {
|
||||
let w = self.prefs.perspective_widget;
|
||||
|
||||
@@ -674,6 +674,8 @@ fn structured_junk() {
|
||||
("object.blend.options", json!({"spacing": "distance", "value": -1e308, "orientation": 5})),
|
||||
("object.blend.options", json!({"ramp": 1e308, "colorShift": -1e308, "easingType": [1]})),
|
||||
("object.blend.make", json!({"ids": [1, 2], "ramp": f64::NAN, "colorShift": [1]})),
|
||||
("object.blend.make", json!({"ids": [1, 2], "createSpine": ["never"], "easingType": "easeIn"})),
|
||||
("object.blend.createSpine", json!({"mode": 1e308})),
|
||||
("object.blend.spine.moveAnchor", json!({"id": 2, "anchor": u64::MAX, "x": 1e308, "y": -1e308, "handle": "sideways"})),
|
||||
("object.blend.spine.addAnchor", json!({"id": u64::MAX, "x": 0, "y": 0})),
|
||||
("object.blend.spine.reshapeSegment", json!({"id": 2, "segment": u64::MAX, "t": f64::NAN, "dx": 1e308, "dy": -1e308})),
|
||||
|
||||
@@ -115,15 +115,27 @@ fn both_lexers_take_the_same_characters_into_names() {
|
||||
assert!(checker_member("\u{88F}\u{1ACF}", "\u{88F}\u{1ACF}") && one_identifier("\u{88F}\u{1ACF}", "\u{88F}\u{1ACF}"));
|
||||
for &c in NAME_CHARS {
|
||||
let escape = format!("\\u{:04X}", u32::from(c));
|
||||
let braced = format!("\\u{{{:X}}}", u32::from(c));
|
||||
for (src, name) in [
|
||||
(format!("a{c}b"), format!("a{c}b")),
|
||||
(format!("{c}b"), format!("{c}b")),
|
||||
(format!("a{escape}b"), format!("a{c}b")),
|
||||
(format!("{escape}b"), format!("{c}b")),
|
||||
(format!("a{braced}b"), format!("a{c}b")),
|
||||
(format!("{braced}b"), format!("{c}b")),
|
||||
] {
|
||||
assert_eq!(checker_member(&src, &name), one_identifier(&src, &name), "{src:?} (U+{:04X})", u32::from(c));
|
||||
}
|
||||
}
|
||||
// Braced escapes past U+FFFF and with leading zeros are read by both.
|
||||
for (src, name) in [("\\u{1D49C}b", "\u{1D49C}b"), ("a\\u{0000000062}", "ab")] {
|
||||
assert!(checker_member(src, name) && one_identifier(src, name), "{src:?}");
|
||||
}
|
||||
// Out of range, a surrogate and an empty one: the parser reads no identifier, and the checker's
|
||||
// name ends before the escape.
|
||||
for src in ["a\\u{110000}", "a\\u{D800}", "a\\u{}"] {
|
||||
assert!(checker_member(src, "a") && !one_identifier(src, "a"), "{src:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -187,7 +187,8 @@ pub enum Expr {
|
||||
qualifier: Option<XmlQualifier>,
|
||||
name: XmlNamePart,
|
||||
},
|
||||
/// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope.
|
||||
/// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope
|
||||
/// that holds it, and also an assignment, update or `delete` target.
|
||||
XmlScopeName(ExprId),
|
||||
/// `object..name`.
|
||||
XmlDescendants {
|
||||
|
||||
@@ -13,6 +13,7 @@ use super::{
|
||||
};
|
||||
use crate::heap::{Class, NativeKind, ObjId};
|
||||
use crate::interp::{Abrupt, Interp, JsResult, strict_eq};
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::value::{Str, Value, to_uint32};
|
||||
|
||||
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
@@ -278,17 +279,20 @@ fn join_with(interp: &mut Interp, o: ObjId, separator: &Value, item: fn(&mut Int
|
||||
if len == 0 {
|
||||
return Ok(Value::str(""));
|
||||
}
|
||||
let flat = sep.flat();
|
||||
let sep = &flat[..];
|
||||
// A result that cannot fit is refused before any element is read.
|
||||
let least = (sep.len() as u64).saturating_mul(u64::from(len - 1));
|
||||
if least > (interp.limits.heap_bytes / 4) as u64 {
|
||||
return Err(Abrupt::Limit(crate::LimitKind::Heap));
|
||||
}
|
||||
interp.join_stack.push(o);
|
||||
let r = join_elements(interp, o, len, sep, item);
|
||||
interp.join_stack.pop();
|
||||
r
|
||||
// The separator stays rooted for the whole join, so its flattened copy stays counted.
|
||||
interp.rooted(&[Value::String(sep.clone())], |interp| {
|
||||
let flat = flat_charged(interp, &sep)?;
|
||||
let sep = &flat[..];
|
||||
// A result that cannot fit is refused before any element is read.
|
||||
let least = (sep.len() as u64).saturating_mul(u64::from(len - 1));
|
||||
if least > (interp.limits.heap_bytes / 4) as u64 {
|
||||
return Err(Abrupt::Limit(crate::LimitKind::Heap));
|
||||
}
|
||||
interp.join_stack.push(o);
|
||||
let r = join_elements(interp, o, len, sep, item);
|
||||
interp.join_stack.pop();
|
||||
r
|
||||
})
|
||||
}
|
||||
|
||||
fn join_elements(interp: &mut Interp, o: ObjId, len: u32, sep: &[u16], item: fn(&mut Interp, Value) -> JsResult<Option<Str>>) -> JsResult<Value> {
|
||||
@@ -301,7 +305,10 @@ fn join_elements(interp: &mut Interp, o: ObjId, len: u32, sep: &[u16], item: fn(
|
||||
let Some(s) = item(interp, v)? else { continue };
|
||||
out.push_repeated(interp, sep, k.saturating_sub(seps))?;
|
||||
seps = k;
|
||||
out.push_units(interp, &s.flat())?;
|
||||
interp.rooted(&[Value::String(s.clone())], |interp| {
|
||||
let units = flat_charged(interp, &s)?;
|
||||
out.push_units(interp, &units)
|
||||
})?;
|
||||
}
|
||||
out.push_repeated(interp, sep, u64::from(len - 1).saturating_sub(seps))?;
|
||||
Ok(out.finish(interp))
|
||||
@@ -472,7 +479,7 @@ fn unshift(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul
|
||||
with_this(interp, &this, |interp, o| {
|
||||
let len = u64::from(length_of(interp, o)?);
|
||||
let count = args.len() as u64;
|
||||
// With no arguments each element is still read and written back in place (steps 6 and 7).
|
||||
// With no arguments each element is still read and written back in place (step 6).
|
||||
let maps = vec![Map::Shift(-1), Map::Shift(count as i64 - 1)];
|
||||
let mut it = Indices::new(interp, o, 1, len + 1, false, maps)?;
|
||||
while let Some(k) = it.next(interp)? {
|
||||
|
||||
@@ -13,6 +13,7 @@ use std::collections::HashSet;
|
||||
use super::{Builder, ELEMENT_BYTES, arg, data, key_of, length_of, method, new_array, new_string, to_integer};
|
||||
use crate::heap::{Class, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key, string_bytes};
|
||||
use crate::interp::{Desc, ErrorType, Hint, Interp, JsResult};
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::value::{Str, Value, number_to_str};
|
||||
|
||||
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
@@ -473,7 +474,7 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult<Se
|
||||
let n = to_integer(interp, &space)?.clamp(0.0, 10.0) as usize;
|
||||
s.gap = vec![u16::from(b' '); n];
|
||||
}
|
||||
Value::String(t) => s.gap = t.flat().iter().take(10).copied().collect(),
|
||||
Value::String(t) => s.gap = flat_charged(interp, &t)?.iter().take(10).copied().collect(),
|
||||
_ => {}
|
||||
}
|
||||
Ok(s)
|
||||
@@ -632,7 +633,10 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul
|
||||
Value::Bool(b) => out.push_str(interp, if *b { "true" } else { "false" }),
|
||||
Value::Number(n) if n.is_finite() => out.push_units(interp, &number_to_str(*n).flat()),
|
||||
Value::Number(_) => out.push_str(interp, "null"),
|
||||
Value::String(s) => write_quoted(interp, out, &s.flat()),
|
||||
Value::String(s) => interp.rooted(std::slice::from_ref(v), |i| {
|
||||
let units = flat_charged(i, s)?;
|
||||
write_quoted(i, out, &units)
|
||||
}),
|
||||
Value::Undefined | Value::Object(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,8 +160,11 @@ pub(crate) enum Op {
|
||||
parts: u32,
|
||||
list: bool,
|
||||
},
|
||||
/// `name` → the value of the name on the nearest XML value in scope.
|
||||
/// `name` → the value of the name on the nearest XML value in scope that holds it.
|
||||
XmlScopeGet,
|
||||
/// `name` → `object name`: the nearest XML value in scope that holds the name, for an
|
||||
/// assignment, update or `delete`.
|
||||
XmlScopeRef,
|
||||
/// `object` → the filter's state.
|
||||
XmlFilterStart,
|
||||
/// `state` → `state item`, or jumps with `state` when the items are used up.
|
||||
@@ -170,8 +173,9 @@ pub(crate) enum Op {
|
||||
XmlFilterTest,
|
||||
/// `state` → the XMLList of the items kept.
|
||||
XmlFilterEnd,
|
||||
/// `iterator name` → `iterator value`: the value under the name a `for each` got.
|
||||
ForEachValue,
|
||||
/// `iterator name x₁…xₙ` → `iterator name x₁…xₙ value`: the value under the name a `for each`
|
||||
/// got, read after the `n` values its target pushed.
|
||||
ForEachValue(u32),
|
||||
/// `value` → nothing: sets the default XML namespace of the running code.
|
||||
SetDefaultNamespace,
|
||||
}
|
||||
@@ -308,7 +312,8 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
|
||||
Op::XmlDescendants | Op::XmlFilterTest => e(2, 1),
|
||||
Op::XmlEscape(_) | Op::XmlScopeGet | Op::XmlFilterStart | Op::XmlFilterEnd => e(1, 1),
|
||||
Op::XmlLiteral { parts, .. } => e(parts, 1),
|
||||
Op::ForEachValue => e(2, 2),
|
||||
Op::XmlScopeRef => e(1, 2),
|
||||
Op::ForEachValue(n) => e(n + 2, n + 3),
|
||||
Op::SetDefaultNamespace => e(1, 0),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -497,16 +497,21 @@ impl<'a> FnCompiler<'a> {
|
||||
let brk = self.new_label();
|
||||
self.bind(head);
|
||||
self.jump(Op::ForInNext, brk);
|
||||
if each {
|
||||
self.emit(Op::ForEachValue);
|
||||
}
|
||||
match target {
|
||||
ForInTarget::Var(d) => {
|
||||
let n = self.var_name(&d.name.name);
|
||||
if each {
|
||||
self.emit(Op::ForEachValue(0));
|
||||
}
|
||||
self.emit(Op::SetVar(n));
|
||||
}
|
||||
ForInTarget::Expr(e) if each => self.store_value_to(*e)?,
|
||||
ForInTarget::Expr(e) => self.store_key_to(*e)?,
|
||||
}
|
||||
if each {
|
||||
// The value; the name under it goes next.
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
self.emit(Op::Pop);
|
||||
self.loop_body(body, labels, brk, head)?;
|
||||
self.jump(Op::Jump, head);
|
||||
@@ -538,6 +543,11 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::Rot3);
|
||||
self.emit(Op::SetIndex);
|
||||
}
|
||||
Some(Expr::XmlScopeName(name)) => {
|
||||
self.xml_scope_ref(target, *name)?;
|
||||
self.emit(Op::Rot3);
|
||||
self.emit(Op::SetIndex);
|
||||
}
|
||||
_ => {
|
||||
self.expr(target)?;
|
||||
self.emit(Op::Pop);
|
||||
@@ -547,6 +557,46 @@ impl<'a> FnCompiler<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Assigns the value under the name on top of the stack to a `for each` target expression,
|
||||
/// leaving the name and then the value on top. The target is evaluated before the value is
|
||||
/// read (ECMA-357 section 12.3).
|
||||
fn store_value_to(&mut self, target: ExprId) -> CResult<()> {
|
||||
let target = self.ast.unparenthesized(target);
|
||||
self.at(self.ast.expr_span(target).start);
|
||||
match self.ast.expr(target) {
|
||||
Some(Expr::Ident(name)) => {
|
||||
let n = self.var_name(name);
|
||||
self.emit(Op::ForEachValue(0));
|
||||
self.emit(Op::SetVar(n));
|
||||
}
|
||||
Some(Expr::Member { object, property }) => {
|
||||
self.expr(*object)?;
|
||||
self.emit(Op::ForEachValue(1));
|
||||
let n = self.name_key(key_of(&property.name));
|
||||
self.emit(Op::SetMember(n));
|
||||
}
|
||||
Some(Expr::Index { object, index }) => {
|
||||
self.expr(*object)?;
|
||||
self.expr(*index)?;
|
||||
self.emit(Op::ToKey);
|
||||
self.emit(Op::ForEachValue(2));
|
||||
self.emit(Op::SetIndex);
|
||||
}
|
||||
Some(Expr::XmlScopeName(name)) => {
|
||||
self.xml_scope_ref(target, *name)?;
|
||||
self.emit(Op::ForEachValue(2));
|
||||
self.emit(Op::SetIndex);
|
||||
}
|
||||
_ => {
|
||||
self.expr(target)?;
|
||||
self.emit(Op::Pop);
|
||||
self.emit(Op::ForEachValue(0));
|
||||
self.throw_invalid_target();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn throw_invalid_target(&mut self) {
|
||||
let s = self.string(&"invalid assignment target".encode_utf16().collect::<Vec<u16>>());
|
||||
let depth = self.depth;
|
||||
@@ -854,6 +904,15 @@ impl<'a> FnCompiler<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression
|
||||
/// `id`, then the name, as an assignment, update or `delete` uses them.
|
||||
fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> {
|
||||
self.expr(name)?;
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.emit(Op::XmlScopeRef);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn xml_literal(&mut self, parts: &[XmlPart], list: bool) -> CResult<()> {
|
||||
for part in parts {
|
||||
match part {
|
||||
@@ -1096,6 +1155,10 @@ impl<'a> FnCompiler<'a> {
|
||||
self.expr(*index)?;
|
||||
self.emit(Op::DeleteIndex);
|
||||
}
|
||||
Some(Expr::XmlScopeName(name)) => {
|
||||
self.xml_scope_ref(arg, *name)?;
|
||||
self.emit(Op::DeleteIndex);
|
||||
}
|
||||
_ => {
|
||||
self.expr(arg)?;
|
||||
self.emit(Op::Pop);
|
||||
@@ -1202,6 +1265,13 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::GetIndex);
|
||||
}
|
||||
}
|
||||
Some(Expr::XmlScopeName(name)) => {
|
||||
self.xml_scope_ref(target, *name)?;
|
||||
if op.is_some() {
|
||||
self.emit(Op::Dup2);
|
||||
self.emit(Op::GetIndex);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.expr(target)?;
|
||||
if op.is_none() {
|
||||
@@ -1222,7 +1292,7 @@ impl<'a> FnCompiler<'a> {
|
||||
let n = self.name_key(key_of(&property.name));
|
||||
self.emit(Op::SetMember(n));
|
||||
}
|
||||
Some(Expr::Index { .. }) => self.emit(Op::SetIndex),
|
||||
Some(Expr::Index { .. } | Expr::XmlScopeName(_)) => self.emit(Op::SetIndex),
|
||||
_ => self.throw_invalid_target(),
|
||||
}
|
||||
Ok(())
|
||||
@@ -1246,6 +1316,10 @@ impl<'a> FnCompiler<'a> {
|
||||
self.expr(*index)?;
|
||||
self.emit(Op::IncIndex { prefix, dec });
|
||||
}
|
||||
Some(Expr::XmlScopeName(name)) => {
|
||||
self.xml_scope_ref(target, *name)?;
|
||||
self.emit(Op::IncIndex { prefix, dec });
|
||||
}
|
||||
_ => {
|
||||
self.expr(target)?;
|
||||
self.emit(Op::ToNumber);
|
||||
|
||||
+73
-18
@@ -27,6 +27,7 @@ use crate::heap::{
|
||||
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId,
|
||||
Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
|
||||
};
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32};
|
||||
use crate::{LimitKind, Limits, Options};
|
||||
|
||||
@@ -205,6 +206,12 @@ pub(crate) struct Interp {
|
||||
pub(crate) date_host: crate::date_builtins::DateHost,
|
||||
/// The bytes native code holds outside the heap's cells through [`HeldBytes`].
|
||||
pub(crate) held: Rc<HeldCount>,
|
||||
/// Bytes of the copies [`Self::get_own_property`] made flattening the rope of a String
|
||||
/// object, which the heap's total adds before the next limit check.
|
||||
flattened: std::cell::Cell<usize>,
|
||||
/// Fuel for the units those copies took and the rope nodes it read in place, which the next
|
||||
/// step takes.
|
||||
pub(crate) flattened_fuel: std::cell::Cell<u64>,
|
||||
/// The global code's default XML namespace URI (ECMA-357 section 12.1).
|
||||
pub(crate) xml_default_uri: Key,
|
||||
/// Set by the host to end the current slice of a resumable run at the next safe point.
|
||||
@@ -450,6 +457,8 @@ impl Interp {
|
||||
files: None,
|
||||
date_host: crate::date_builtins::DateHost::default(),
|
||||
held: Rc::default(),
|
||||
flattened: std::cell::Cell::new(0),
|
||||
flattened_fuel: std::cell::Cell::new(0),
|
||||
xml_default_uri: Rc::from(Vec::new()),
|
||||
pause: Rc::default(),
|
||||
in_slice: false,
|
||||
@@ -569,6 +578,7 @@ impl Interp {
|
||||
|
||||
fn tick(&mut self) -> JsResult<()> {
|
||||
self.use_fuel()?;
|
||||
crate::regexp_vm::use_fuel_n(self, self.flattened_fuel.replace(0))?;
|
||||
self.settle_held();
|
||||
if self.heap.bytes > self.gc_threshold {
|
||||
self.collect_garbage();
|
||||
@@ -595,10 +605,12 @@ impl Interp {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes the bytes that dropped [`HeldBytes`] released off the heap's total.
|
||||
/// Takes the bytes that dropped [`HeldBytes`] released off the heap's total, and adds the
|
||||
/// bytes of the ropes [`Self::get_own_property`] flattened.
|
||||
fn settle_held(&mut self) {
|
||||
let released = self.held.released.replace(0);
|
||||
self.heap.bytes = self.heap.bytes.saturating_sub(released);
|
||||
let flattened = self.flattened.replace(0);
|
||||
self.heap.bytes = self.heap.bytes.saturating_sub(released).saturating_add(flattened);
|
||||
}
|
||||
|
||||
/// Collects garbage now and sets when the next collection runs.
|
||||
@@ -680,6 +692,7 @@ impl Interp {
|
||||
self.heap.collect(&roots);
|
||||
// The collection counts the live total again, so bytes already released are not in it.
|
||||
self.held.released.set(0);
|
||||
self.flattened.set(0);
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get());
|
||||
}
|
||||
|
||||
@@ -943,11 +956,12 @@ impl Interp {
|
||||
Op::XmlEscape(kind) => self.op_xml_escape(kind),
|
||||
Op::XmlLiteral { parts, list } => self.op_xml_literal(parts, list),
|
||||
Op::XmlScopeGet => self.op_xml_scope_get(),
|
||||
Op::XmlScopeRef => self.op_xml_scope_ref(),
|
||||
Op::XmlFilterStart => self.op_xml_filter_start(),
|
||||
Op::XmlFilterNext(t) => self.op_xml_filter_next(t),
|
||||
Op::XmlFilterTest => self.op_xml_filter_test(),
|
||||
Op::XmlFilterEnd => self.op_xml_filter_end(),
|
||||
Op::ForEachValue => self.op_for_each_value(),
|
||||
Op::ForEachValue(n) => self.op_for_each_value(n as usize),
|
||||
Op::SetDefaultNamespace => self.op_set_default_namespace(),
|
||||
Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"),
|
||||
}
|
||||
@@ -1234,7 +1248,33 @@ impl Interp {
|
||||
if let Some(i) = array_index(k)
|
||||
&& (i as usize) < s.len()
|
||||
{
|
||||
let unit = s.flat().get(i as usize).copied().unwrap_or(0);
|
||||
let unit = if s.is_rope() {
|
||||
let owed = self.flattened_fuel.get();
|
||||
let flattened = self.flattened.get().saturating_add(string_bytes(s.len()));
|
||||
if self.heap.bytes.saturating_add(flattened) > self.limits.heap_bytes {
|
||||
// The copy does not fit without a collection, which needs `&mut self`:
|
||||
// the unit is read along the rope instead, a unit of fuel per node.
|
||||
let Some((unit, visited)) = s.unit_at(i as usize, self.fuel.saturating_sub(owed)) else {
|
||||
return Err(Abrupt::Limit(LimitKind::Fuel));
|
||||
};
|
||||
self.flattened_fuel.set(owed.saturating_add(visited));
|
||||
unit
|
||||
} else {
|
||||
// Flattening copies the units. The run ends here when the fuel for
|
||||
// the copy is not left; otherwise the next step takes it, and the
|
||||
// next limit check adds the copy's bytes.
|
||||
let fuel = owed.saturating_add((s.len() / crate::string_builtins::UNITS_PER_FUEL) as u64 + 1);
|
||||
if fuel > self.fuel {
|
||||
return Err(Abrupt::Limit(LimitKind::Fuel));
|
||||
}
|
||||
self.flattened_fuel.set(fuel);
|
||||
self.flattened.set(flattened);
|
||||
s.flat().get(i as usize).copied()
|
||||
}
|
||||
} else {
|
||||
s.flat().get(i as usize).copied()
|
||||
}
|
||||
.unwrap_or(0);
|
||||
return Ok(Some(Prop::Data { value: Value::String(Str::from_units(vec![unit])), flags: ENUMERABLE }));
|
||||
}
|
||||
}
|
||||
@@ -1311,7 +1351,7 @@ impl Interp {
|
||||
if let Some(i) = array_index(k)
|
||||
&& (i as usize) < s.len()
|
||||
{
|
||||
let unit = s.flat().get(i as usize).copied().unwrap_or(0);
|
||||
let unit = flat_charged(self, s)?.get(i as usize).copied().unwrap_or(0);
|
||||
return Ok(Value::String(Str::from_units(vec![unit])));
|
||||
}
|
||||
}
|
||||
@@ -2419,7 +2459,7 @@ impl Interp {
|
||||
let strict = self.strict();
|
||||
self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.prepare_source(s.len())?;
|
||||
let units = s.flat();
|
||||
let units = self.flat_reserved(s)?;
|
||||
let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
|
||||
let frame = self.frame()?;
|
||||
@@ -2584,7 +2624,7 @@ impl Interp {
|
||||
Value::Null => 0.0,
|
||||
Value::Bool(b) => f64::from(u8::from(*b)),
|
||||
Value::Number(n) => *n,
|
||||
Value::String(s) => string_to_number(&s.flat()),
|
||||
Value::String(s) => string_to_number(&flat_charged(self, s)?),
|
||||
Value::Object(_) => {
|
||||
let p = self.to_primitive(v, Hint::Number)?;
|
||||
return self.to_number(&p);
|
||||
@@ -2618,19 +2658,28 @@ impl Interp {
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
pub(crate) fn to_key(&mut self, v: &Value) -> JsResult<Key> {
|
||||
match v {
|
||||
Value::String(s) => {
|
||||
let rope = s.is_rope();
|
||||
let flat = s.flat();
|
||||
if rope {
|
||||
self.heap.bytes += string_bytes(flat.len());
|
||||
}
|
||||
Ok(flat)
|
||||
}
|
||||
Value::String(s) => self.flat_reserved(s),
|
||||
Value::Number(n) if *n >= 0.0 && *n < 4_294_967_295.0 && n.fract() == 0.0 => Ok(index_key(*n as u32)),
|
||||
_ => Ok(self.to_str(v)?.flat()),
|
||||
_ => {
|
||||
let s = self.to_str(v)?;
|
||||
self.flat_reserved(&s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that
|
||||
/// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays
|
||||
/// rooted while the copy is reserved; everything else the caller still needs must be
|
||||
/// reachable from the roots.
|
||||
fn flat_reserved(&mut self, s: &Str) -> JsResult<Key> {
|
||||
if s.is_rope() {
|
||||
let bytes = string_bytes(s.len());
|
||||
self.rooted(&[Value::String(s.clone())], |i| i.reserve_heap(bytes))?;
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
|
||||
}
|
||||
Ok(s.flat())
|
||||
}
|
||||
|
||||
/// ToObject (section 9.9).
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
pub(crate) fn to_object(&mut self, v: &Value) -> JsResult<ObjId> {
|
||||
@@ -2753,7 +2802,11 @@ impl Interp {
|
||||
(self.to_primitive(x, Hint::Number)?, py)
|
||||
};
|
||||
if let (Value::String(a), Value::String(b)) = (&px, &py) {
|
||||
return Ok(Some(*a.flat() < *b.flat()));
|
||||
// Both stay rooted, so the first copy is still counted while the second is made.
|
||||
return self.rooted(&[px.clone(), py.clone()], |i| {
|
||||
let (a, b) = (flat_charged(i, a)?, flat_charged(i, b)?);
|
||||
Ok(Some(*a < *b))
|
||||
});
|
||||
}
|
||||
let nx = self.to_number(&px)?;
|
||||
let ny = self.to_number(&py)?;
|
||||
@@ -2778,7 +2831,9 @@ impl Interp {
|
||||
| (Value::String(_), Value::String(_))
|
||||
| (Value::Bool(_), Value::Bool(_))
|
||||
| (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)),
|
||||
(Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => return Ok(*n == string_to_number(&s.flat())),
|
||||
(Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => {
|
||||
return Ok(*n == string_to_number(&flat_charged(self, s)?));
|
||||
}
|
||||
(Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))),
|
||||
(_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))),
|
||||
(Value::Number(_) | Value::String(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?,
|
||||
|
||||
@@ -873,8 +873,9 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
|
||||
/// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code
|
||||
/// neither `eval` nor `arguments`), a property, or outside strict mode code a call (assigning
|
||||
/// to its result fails at run time, as ECMA-262 2015 Annex B and web browsers have it).
|
||||
/// neither `eval` nor `arguments`), a property, an E4X name standing alone (`@a`, `ns::a`;
|
||||
/// ECMA-357 section 11.1), or outside strict mode code a call (assigning to its result fails
|
||||
/// at run time, as ECMA-262 2015 Annex B and web browsers have it).
|
||||
fn check_target(&self, expr: ExprId, message: &str) -> Result<()> {
|
||||
let inner = self.ast.unparenthesized(expr);
|
||||
match self.ast.expr(inner) {
|
||||
@@ -884,7 +885,7 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some(Expr::Member { .. } | Expr::Index { .. }) => Ok(()),
|
||||
Some(Expr::Member { .. } | Expr::Index { .. } | Expr::XmlScopeName(_)) => Ok(()),
|
||||
Some(Expr::Call { .. }) if !self.ctx.strict => Ok(()),
|
||||
_ => Err(self.error_at_offset(self.ast.expr_span(expr).start, message)),
|
||||
}
|
||||
|
||||
@@ -231,6 +231,7 @@ impl Realm {
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 });
|
||||
}
|
||||
interp.fuel = interp.limits.fuel;
|
||||
interp.flattened_fuel.set(0);
|
||||
interp.source_units = 0;
|
||||
interp.throw_site = None;
|
||||
interp.last_thrown = Value::Undefined;
|
||||
|
||||
@@ -109,10 +109,11 @@ fn push_held<T>(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec<T>, it
|
||||
}
|
||||
|
||||
/// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that copy's
|
||||
/// bytes are reserved and added to the heap, and its units charged as fuel, first.
|
||||
/// bytes are reserved and added to the heap, and its units charged as fuel, first. The rope stays
|
||||
/// rooted while the copy is reserved, so what it holds is still counted.
|
||||
pub(crate) fn flat_charged(interp: &mut Interp, s: &Str) -> JsResult<Rc<[u16]>> {
|
||||
if s.is_rope() {
|
||||
reserve_units(interp, s.len())?;
|
||||
interp.rooted(&[Value::String(s.clone())], |interp| reserve_units(interp, s.len()))?;
|
||||
}
|
||||
Ok(s.flat())
|
||||
}
|
||||
|
||||
@@ -309,6 +309,131 @@ fn flattening_a_rope_counts_against_the_heap() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operators_and_builtins_count_a_flattened_rope_against_the_heap() {
|
||||
// Three ropes of about 524,288 units, each 1 MiB once flat, with a 3 MiB heap.
|
||||
let build = "var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z';";
|
||||
let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() };
|
||||
let not_stopped: Vec<_> =
|
||||
["X < 'a'", "X == 1", "+X", "X[0]", "({})[{ toString: function () { return X; } }]", "JSON.stringify(0, null, X)", "[1].join(X)"]
|
||||
.into_iter()
|
||||
.filter(|read| {
|
||||
let src = format!("{build} {}; {}; {}; 0", read.replace('X', "s"), read.replace('X', "t"), read.replace('X', "u"));
|
||||
let result = Realm::with_options(Options::default(), limits.clone()).run(&src);
|
||||
!matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap))
|
||||
})
|
||||
.collect();
|
||||
assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flattened_temporary_stays_counted_while_the_next_copy_is_made() {
|
||||
// Ropes of 262,145 units, each about half the heap once flat: one fits, two don't. Each is
|
||||
// made by a function, so nothing but the native code holds it while it is flattened.
|
||||
let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; }";
|
||||
let limits = Limits { heap_bytes: 4 * 262_146, ..Limits::default() };
|
||||
let run = |read: &str| Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} {read}; 0"));
|
||||
assert!(run("f('a')[0]").is_ok(), "one flattened copy fits");
|
||||
let not_stopped: Vec<_> = [
|
||||
"({ valueOf: function () { return f('a'); } }) < ({ valueOf: function () { return f('b'); } })",
|
||||
"JSON.stringify({ toJSON: function () { return f('a'); } })",
|
||||
"[1, 2].join({ toString: function () { return f('a'); } })",
|
||||
"[{ toString: function () { return f('a'); } }].join('')",
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|read| !matches!(run(read), Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)))
|
||||
.collect();
|
||||
assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_converted_rope_counts_what_it_holds_while_its_copy_is_made() {
|
||||
// `mk` returns a rope whose left half is a flat string of about half the heap, held by
|
||||
// nothing else. Its flattened copy is the other half, so the two don't fit together.
|
||||
let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; } \
|
||||
function mk() { var a = f('a'); a[0]; return a + 'b'; }";
|
||||
let limits = Limits { heap_bytes: 4 * 262_146, ..Limits::default() };
|
||||
let not_stopped: Vec<_> = [
|
||||
"+({ valueOf: mk })",
|
||||
"({})[{ toString: mk }]",
|
||||
"({ valueOf: mk }) == 1",
|
||||
"++({ get x() { return mk(); } }).x",
|
||||
"JSON.stringify(0, null, (function () { var o = new String(''); o.toString = mk; return o; })())",
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|read| {
|
||||
let result = Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} {read}; 0"));
|
||||
!matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap))
|
||||
})
|
||||
.collect();
|
||||
assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_object_counts_its_flattened_rope_against_the_heap() {
|
||||
// The same three ropes, each wrapped in a String object and read by index.
|
||||
let build = "var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z'; \
|
||||
String.prototype.first = function () { return this[0]; };";
|
||||
let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() };
|
||||
// Wrapping alone reads no units, so it makes no copy.
|
||||
let lengths =
|
||||
Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} Object(s).length + new String(t).length + Object(u).length"));
|
||||
assert_eq!(lengths, Ok(JsValue::Number(1_572_866.0)));
|
||||
// Two copies fit. The third read finds no room for its copy and reads the unit along the
|
||||
// rope, so the live heap stays within the limit.
|
||||
for (read, expected) in [
|
||||
("Object(X)[0]", "xxx"),
|
||||
("new String(X)[0]", "xxx"),
|
||||
("0 in Object(X)", "truetruetrue"),
|
||||
("Object(X).hasOwnProperty(0)", "truetruetrue"),
|
||||
("X.first()", "xxx"),
|
||||
("Object(X)[524288]", "undefinedyz"),
|
||||
] {
|
||||
let src = format!("{build} '' + ({}) + ({}) + ({})", read.replace('X', "s"), read.replace('X', "t"), read.replace('X', "u"));
|
||||
let mut realm = Realm::with_options(Options::default(), limits.clone());
|
||||
assert_eq!(realm.run(&src), Ok(JsValue::String(expected.into())), "{read}");
|
||||
let interp = realm.interp();
|
||||
interp.collect_garbage();
|
||||
assert!(interp.heap.bytes <= limits.heap_bytes, "{read}: {} bytes live", interp.heap.bytes);
|
||||
}
|
||||
let wrapped =
|
||||
Realm::with_options(Options::default(), Limits::default()).run(&format!("{build} Object(t)[524288] + new String(u)[524288] + t.first()"));
|
||||
assert_eq!(wrapped, Ok(JsValue::String("yzx".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_object_takes_fuel_for_the_rope_it_flattens() {
|
||||
let limits = Limits { fuel: 40_000, ..Limits::default() };
|
||||
let build = "var s = ' '; for (var i = 0; i < 20; i++) s = s + s; Object(s).length";
|
||||
assert!(Realm::with_options(Options::default(), limits.clone()).run(build).is_ok());
|
||||
for read in ["Object(s)[0]", "0 in new String(s)"] {
|
||||
let e = fail_with(Realm::with_options(Options::default(), limits.clone()), &format!("{build}; {read}"));
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{read}: {e:?}");
|
||||
}
|
||||
// A run that ends with an error right after the read leaves the next run its whole fuel.
|
||||
let mut realm = Realm::with_options(Options::default(), Limits { fuel: 100_000, ..Limits::default() });
|
||||
let defined = realm.run("var s = ' '; for (var i = 0; i < 20; i++) s = s + s; Object.defineProperty(new String(s), 0, { value: 'a' })");
|
||||
assert!(matches!(defined, Err(ref e) if e.kind == RunErrorKind::Thrown), "{defined:?}");
|
||||
assert!(realm.run("for (var j = 0; j < 5000; j++) {} j").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() {
|
||||
// `g` leaves a garbage string, so the heap is close to its limit when the rope receiver of a
|
||||
// non-strict function is boxed. The callee and the argument object are off the stack by
|
||||
// then, and must survive anything boxing the receiver does.
|
||||
let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \
|
||||
function mk() { var a = f('a'); a[0]; return a + 'b'; } 0";
|
||||
let mut realm = Realm::with_options(Options::default(), Limits::default());
|
||||
assert_eq!(realm.run(build), Ok(JsValue::Number(0.0)));
|
||||
let interp = realm.interp();
|
||||
interp.collect_garbage();
|
||||
interp.limits.heap_bytes = interp.heap.bytes + 2 * crate::heap::string_bytes(131_073) + (64 << 10);
|
||||
interp.reset_gc_threshold();
|
||||
let src = "(function () { var g = f('g'); g[0]; })(); (function (o) { return o.x; }).call(mk(), { x: 1 })";
|
||||
assert_eq!(realm.run(src), Ok(JsValue::Number(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compiling_a_pattern_counts_against_the_heap() {
|
||||
let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length";
|
||||
|
||||
@@ -163,6 +163,34 @@ impl Str {
|
||||
flat
|
||||
}
|
||||
|
||||
/// The code unit at `i` read along the rope without flattening it, visiting at most
|
||||
/// `max_nodes` nodes: `None` when that is not enough, otherwise the unit (when `i` is in
|
||||
/// range) and the number of nodes visited.
|
||||
pub(crate) fn unit_at(&self, mut i: usize, max_nodes: u64) -> Option<(Option<u16>, u64)> {
|
||||
let mut node = self.clone();
|
||||
let mut visited = 0u64;
|
||||
loop {
|
||||
visited += 1;
|
||||
if visited > max_nodes {
|
||||
return None;
|
||||
}
|
||||
let next = match &*node.0.borrow() {
|
||||
Node::Flat(f) => return Some((f.get(i).copied(), visited)),
|
||||
Node::Concat { left, right, .. } => {
|
||||
let left_len = left.len();
|
||||
if i < left_len {
|
||||
left.clone()
|
||||
} else {
|
||||
i -= left_len;
|
||||
right.clone()
|
||||
}
|
||||
}
|
||||
Node::Taken => return Some((None, visited)),
|
||||
};
|
||||
node = next;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_rust_string(&self) -> String {
|
||||
String::from_utf16_lossy(&self.flat())
|
||||
}
|
||||
|
||||
+28
-18
@@ -2863,27 +2863,24 @@ impl Interp {
|
||||
self.replace(n, value)
|
||||
}
|
||||
|
||||
pub(crate) fn op_xml_scope_get(&mut self) -> JsResult<()> {
|
||||
let name = self.peek(0)?;
|
||||
let n = self.xml_name_only(&name)?;
|
||||
/// The nearest XML or XMLList value in scope whose [[HasProperty]] accepts `n`, or a
|
||||
/// ReferenceError when none does (ECMA-357 section 11.1).
|
||||
fn xml_scope_holder(&mut self, n: &NameRef) -> JsResult<ObjId> {
|
||||
let mut cur = Some(self.frame()?.env);
|
||||
let mut first = None;
|
||||
let mut any_xml = false;
|
||||
while let Some(e) = cur {
|
||||
match self.heap.env(e) {
|
||||
Some(Env::Decl { outer, .. }) => cur = *outer,
|
||||
Some(&Env::Obj { object, outer, .. }) => {
|
||||
let v = Value::Object(object);
|
||||
if self.is_xml(&v) {
|
||||
if first.is_none() {
|
||||
first = Some(object);
|
||||
}
|
||||
any_xml = true;
|
||||
let found = match self.classify(&v) {
|
||||
Xv::Node(x) => self.node_has_name(x, &n)?,
|
||||
_ => self.list_has_name(object, &n)?,
|
||||
Xv::Node(x) => self.node_has_name(x, n)?,
|
||||
_ => self.list_has_name(object, n)?,
|
||||
};
|
||||
if found {
|
||||
first = Some(object);
|
||||
break;
|
||||
return Ok(object);
|
||||
}
|
||||
}
|
||||
cur = outer;
|
||||
@@ -2891,13 +2888,26 @@ impl Interp {
|
||||
None => return Err(Abrupt::Internal("environment out of range".into())),
|
||||
}
|
||||
}
|
||||
let Some(object) = first else {
|
||||
return Err(self.throw(ErrorType::Reference, "an XML name is used outside any XML value"));
|
||||
};
|
||||
let message = if any_xml { "no XML value in scope has the XML name" } else { "an XML name is used outside any XML value" };
|
||||
Err(self.throw(ErrorType::Reference, message))
|
||||
}
|
||||
|
||||
pub(crate) fn op_xml_scope_get(&mut self) -> JsResult<()> {
|
||||
let name = self.peek(0)?;
|
||||
let n = self.xml_name_only(&name)?;
|
||||
let object = self.xml_scope_holder(&n)?;
|
||||
let v = self.xml_select(object, &n)?;
|
||||
self.replace(1, Value::Object(v))
|
||||
}
|
||||
|
||||
pub(crate) fn op_xml_scope_ref(&mut self) -> JsResult<()> {
|
||||
let name = self.peek(0)?;
|
||||
let n = self.xml_name_only(&name)?;
|
||||
let object = self.xml_scope_holder(&n)?;
|
||||
self.replace(1, Value::Object(object))?;
|
||||
self.push(name)
|
||||
}
|
||||
|
||||
pub(crate) fn op_xml_filter_start(&mut self) -> JsResult<()> {
|
||||
let base = self.peek(0)?;
|
||||
let input = match self.classify(&base) {
|
||||
@@ -2951,9 +2961,9 @@ impl Interp {
|
||||
self.replace(1, Value::Object(out))
|
||||
}
|
||||
|
||||
pub(crate) fn op_for_each_value(&mut self) -> JsResult<()> {
|
||||
let name = self.peek(0)?;
|
||||
let Value::Object(iter) = self.peek(1)? else { return Err(Abrupt::Internal("for-in iterator is not an object".into())) };
|
||||
pub(crate) fn op_for_each_value(&mut self, above: usize) -> JsResult<()> {
|
||||
let name = self.peek(above)?;
|
||||
let Value::Object(iter) = self.peek(above + 1)? else { return Err(Abrupt::Internal("for-in iterator is not an object".into())) };
|
||||
let object = match self.heap.object(iter).map(|o| &o.class) {
|
||||
Some(Class::ForIn(state)) => state.object,
|
||||
_ => return Err(Abrupt::Internal("not a for-in iterator".into())),
|
||||
@@ -2965,7 +2975,7 @@ impl Interp {
|
||||
}
|
||||
None => Value::Undefined,
|
||||
};
|
||||
self.replace(1, v)
|
||||
self.push(v)
|
||||
}
|
||||
|
||||
/// The URI of a Namespace value or of its string form.
|
||||
|
||||
@@ -688,6 +688,103 @@ fn a_scope_name_skips_a_list_without_that_name() {
|
||||
truth("var outer = <o id='1'/>; var inner = <><i id='2'/></>; with (outer) with (inner) { @id == '2' }");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_attribute_assignment_uses_nearest_holder() {
|
||||
truth("var x = <a b='1'/>; with (x) { @b = '2'; } x.@b == '2'");
|
||||
truth("var outer = <o id='1'/>; var inner = <i/>; with (outer) with (inner) { @id = '9'; } outer.@id == '9' && inner.@id.length() === 0");
|
||||
truth("var outer = <o id='1'/>; var inner = <i id='2'/>; with (outer) with (inner) { @id = '9'; } outer.@id == '1' && inner.@id == '9'");
|
||||
truth("var outer = <o id='1'/>; var inner = <><i/></>; with (outer) with (inner) { @id = '9'; } outer.@id == '9' && inner.@id.length() === 0");
|
||||
truth("var x = <a b='1'/>; with (x) with ({ b: 7 }) { @b = '3'; } x.@b == '3'");
|
||||
truth("with (<a b='1'/>) { (@b = 5) === 5 }");
|
||||
truth("var x = <a b='1' c='2'/>; with (x) { @b = @c = 'v'; } x.@b == 'v' && x.@c == 'v'");
|
||||
truth("var n = 0; var x = <a b='1'/>; with (x) { @[(n++, 'b')] = 'z'; } n === 1 && x.@b == 'z' && x.attributes().length() === 1");
|
||||
truth("var x = <a><c>1</c></a>; with (x) { *::c = '2'; } x.c == '2' && x.*.length() === 1");
|
||||
truth("var x = <a b='1'/>; x.@b = '4'; x.@b == '4'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_qualified_assignment_keeps_namespace() {
|
||||
truth(
|
||||
"var ns = new Namespace('u'); var x = <a xmlns:p='u'><p:c>1</p:c><c>0</c></a>; with (x) { ns::c = '2'; } \
|
||||
x.ns::c == '2' && x.ns::c.name().uri === 'u' && x.c == '0' && x.*.length() === 2",
|
||||
);
|
||||
truth(
|
||||
"var ns = new Namespace('u'); var x = <a xmlns:p='u' p:t='1' t='0'/>; with (x) { @ns::t = '5'; } \
|
||||
x.@ns::t == '5' && x.@ns::t.name().uri === 'u' && x.@t == '0'",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_assignment_in_filter_mutates_each_matching_item() {
|
||||
truth("var l = <><i id='1'/><i id='2'/></>; var r = l.(@id = 'z', true); r.length() === 2 && l[0].@id == 'z' && l[1].@id == 'z'");
|
||||
truth("var l = <><i n='1'/><i n='2'/></>; var r = l.(@n = 0); r.length() === 0 && l[0].@n == '0' && l[1].@n == '0'");
|
||||
truth("var l = <><i n='1'/><i n='2'/></>; var r = l.(@n = 'k'); r.length() === 2");
|
||||
truth("var o = <o k='1'/>; var l = <><i/><i/></>; with (o) { l.(@k += 'x', true); } o.@k == '1xx' && l[0].@k.length() === 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_assignment_without_holder_throws_reference_error_before_rhs() {
|
||||
assert_eq!(thrown_name("@a = 1"), "ReferenceError");
|
||||
assert_eq!(thrown_name("with ({ a: 1 }) { @a = 1 }"), "ReferenceError");
|
||||
assert_eq!(thrown_name("with (<x/>) { @a = 1 }"), "ReferenceError");
|
||||
assert_eq!(thrown_name("with (<x/>) { @a += 1 }"), "ReferenceError");
|
||||
assert_eq!(thrown_name("with (<x/>) { @a++ }"), "ReferenceError");
|
||||
assert_eq!(thrown_name("var ns = new Namespace('u'); with (<x><c/></x>) { ns::c = 1 }"), "ReferenceError");
|
||||
truth("var n = 0; var e = ''; try { with (<x/>) { @a = (n++, 1); } } catch (err) { e = err.name; } e === 'ReferenceError' && n === 0");
|
||||
truth(
|
||||
"var b = 'g'; var x = <x/>; var e = ''; try { with (x) { @b = 'w'; } } catch (err) { e = err.name; } \
|
||||
e === 'ReferenceError' && b === 'g' && x.@b.length() === 0 && x.*.length() === 0",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_name_read_without_holder_throws_reference_error() {
|
||||
assert_eq!(thrown_name("with (<x/>) { @a }"), "ReferenceError");
|
||||
assert_eq!(thrown_name("var l = <><i id='1'/><i/></>; l.(@id == '1')"), "ReferenceError");
|
||||
truth("var o = <o id='0'/>; var l = <><i id='1'/><i/></>; var r; with (o) { r = l.(@id == '1'); } r.length() === 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_scope_compound_and_updates_resolve_once() {
|
||||
truth("var n = 0; var x = <a t='1'/>; with (x) { @[(n++, 't')] += 1; } n === 1 && x.@t == '11'");
|
||||
truth("var n = 0; var x = <a t='1'/>; with (x) { @[(n++, 't')]++; } n === 1 && x.@t == '2'");
|
||||
truth("var x = <a t='1'/>; var r; with (x) { r = ++@t; } r === 2 && x.@t == '2'");
|
||||
truth("var x = <a t='1'/>; var r; with (x) { r = @t++; } r === 1 && x.@t == '2'");
|
||||
truth("var x = <a t='5'/>; var r; with (x) { r = --@t; } r === 4 && x.@t == '4'");
|
||||
truth("var x = <a t='5'/>; var r; with (x) { r = @t--; } r === 5 && x.@t == '4'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_scope_delete_removes_attribute() {
|
||||
truth("var x = <a t='1' u='2'/>; var r; with (x) { r = delete @t; } r === true && x.@t.length() === 0 && x.@u == '2'");
|
||||
truth("var x = <a><c/><d/></a>; with (x) { delete *::c; } x.c.length() === 0 && x.d.length() === 1");
|
||||
assert_eq!(thrown_name("with (<a/>) { delete @t }"), "ReferenceError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_scope_for_targets_assign_each_iteration() {
|
||||
truth("var x = <a k=''/>; var s = ''; with (x) { for (@k in { p: 1, q: 2 }) s += @k; } s === 'pq' && x.@k == 'q'");
|
||||
truth("var x = <a k=''/>; var s = ''; with (x) { for each (@k in [3, 4]) s += @k; } s === '34' && x.@k == '4'");
|
||||
assert_eq!(thrown_name("with (<a/>) { for (@k in { p: 1 }); }"), "ReferenceError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_each_evaluates_its_target_before_reading_the_value() {
|
||||
truth("var o = { p: 1 }; var t = {}; for each ((o.p = 2, t).v in o); t.v === 2");
|
||||
truth("var o = { p: 1 }; var t = {}; for each (t[(o.p = 3, 'w')] in o); t.w === 3");
|
||||
truth("var x = <a k=''/>; var o = { p: 1 }; with (x) { for each (@[(o.p = 2, 'k')] in o); } x.@k == '2'");
|
||||
truth("var o = { p: 1, q: 2 }; var s = ''; for each (var v in o) s += v; var t; for each (t in o) s += t; s === '1212' && t === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_scope_targets_need_e4x_option() {
|
||||
for src in ["@a = 1", "ns::a = 1", "@a += 1", "++@a", "@a--", "for (@a in o);", "for each (@a in o);", "\"use strict\"; @a = 1"] {
|
||||
assert!(parse(src, &Options::default()).is_err(), "{src}");
|
||||
assert!(parse(src, &e4x()).is_ok(), "{src}");
|
||||
}
|
||||
truth("'use strict'; var l = <><i b='1'/></>; l.(@b = '2', true); l[0].@b == '2'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bracket_key_converts_to_a_string_before_it_names_a_child() {
|
||||
truth("var x = <a><true>1</true></a>; x[true] == '1' && (true in x) && !(false in x)");
|
||||
|
||||
+46
-24
@@ -56,6 +56,24 @@ fn s<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
|
||||
p.get(k).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// An optional param read with `read`: none when it is omitted or null, else an error naming the
|
||||
/// key when `read` gets nothing from its value.
|
||||
fn opt<T>(p: &Value, k: &str, read: impl Fn(&Value) -> Option<T>, what: &str) -> Result<Option<T>, String> {
|
||||
match p.get(k) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => read(v).map(Some).ok_or_else(|| format!("`{k}` must be {what}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_bool(p: &Value, k: &str) -> Result<Option<bool>, String> {
|
||||
opt(p, k, Value::as_bool, "true or false")
|
||||
}
|
||||
|
||||
/// A pointer packet's `mods`: none when omitted or null, else an object of booleans.
|
||||
fn packet_mods(p: &Value) -> Result<Option<Mods>, String> {
|
||||
opt(p, "mods", |m| m.as_object().and_then(|_| serde_json::from_value(m.clone()).ok()), "an object of true or false values")
|
||||
}
|
||||
|
||||
pub(crate) fn pointer_kind(k: &str) -> Option<PointerKind> {
|
||||
Some(match k {
|
||||
"down" => PointerKind::Down,
|
||||
@@ -210,28 +228,30 @@ impl Headless {
|
||||
|
||||
fn pointer(&mut self, p: &Value) -> Result<Value, String> {
|
||||
let events = p.get("events").and_then(Value::as_array).ok_or("missing `events`")?;
|
||||
let base: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default();
|
||||
let base = packet_mods(p)?.unwrap_or_default();
|
||||
let default = PointerEvent::json_backquote(p, false)?;
|
||||
let held = events.iter().map(|e| PointerEvent::json_backquote(e, default)).collect::<Result<Vec<_>, _>>()?;
|
||||
// Every event is read before any is sent, so a malformed packet sends none of them.
|
||||
let read = events
|
||||
.iter()
|
||||
.zip(held)
|
||||
.map(|(e, backquote)| {
|
||||
let mods = packet_mods(e)?.unwrap_or(base);
|
||||
let kind = s(e, "kind").unwrap_or("");
|
||||
let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?;
|
||||
PointerEvent::json_check(e)?;
|
||||
if s(e, "space") == Some("screen") {
|
||||
return Err("screen-space pointer events need the desktop app; use document coordinates".to_string());
|
||||
}
|
||||
let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?;
|
||||
let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?;
|
||||
Ok((e, kind, Point::new(x, y), mods, backquote))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
self.ensure_document();
|
||||
let mut requests = vec![];
|
||||
for (e, backquote) in events.iter().zip(held) {
|
||||
let kind = s(e, "kind").unwrap_or("");
|
||||
let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?;
|
||||
if s(e, "space") == Some("screen") {
|
||||
return Err("screen-space pointer events need the desktop app; use document coordinates".into());
|
||||
}
|
||||
let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?;
|
||||
let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?;
|
||||
let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base);
|
||||
let ev = PointerEvent {
|
||||
kind,
|
||||
pos: Point::new(x, y),
|
||||
mods,
|
||||
backquote,
|
||||
pressure: PointerEvent::json_pressure(e),
|
||||
pen: PointerEvent::json_pen(e),
|
||||
};
|
||||
for (e, kind, pos, mods, backquote) in read {
|
||||
let ev = PointerEvent { kind, pos, mods, backquote, pressure: PointerEvent::json_pressure(e), pen: PointerEvent::json_pen(e) };
|
||||
let reqs = self.session.pointer(&ev, self.view).map_err(|e| e.to_string())?;
|
||||
self.apply_ui_requests(reqs, &mut requests)?;
|
||||
// With no frames to show the highlight or apply an edit in later, each event waits for
|
||||
@@ -253,8 +273,8 @@ impl Headless {
|
||||
|
||||
fn key(&mut self, p: &Value) -> Result<Value, String> {
|
||||
let key = s(p, "key").ok_or("missing `key`")?;
|
||||
let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false);
|
||||
let mods = Mods { shift: b("shift"), alt: b("alt"), cmd: b("cmd"), ctrl: b("ctrl"), ..Mods::default() };
|
||||
let b = |n: &str| opt_bool(p, n).map(|on| on.unwrap_or(false));
|
||||
let mods = Mods { shift: b("shift")?, alt: b("alt")?, cmd: b("cmd")?, ctrl: b("ctrl")?, ..Mods::default() };
|
||||
// A letter reaches the tool only when the tool claims it without Cmd, Ctrl or Alt (E while
|
||||
// a selection marquee is dragged); otherwise it is a shortcut.
|
||||
let mut tk = tool_key(key);
|
||||
@@ -296,16 +316,18 @@ impl Headless {
|
||||
}
|
||||
|
||||
fn render(&mut self, p: &Value) -> Result<Value, String> {
|
||||
let idx = opt(p, "artboard", |v| v.as_u64().and_then(|i| usize::try_from(i).ok()), "a whole number of 0 or more")?.unwrap_or(0);
|
||||
let scale = opt(p, "scale", Value::as_f64, "a number")?.unwrap_or(1.0).clamp(0.01, 16.0);
|
||||
let trace_views = opt_bool(p, "traceViews")? == Some(true);
|
||||
let data = opt_bool(p, "data")? == Some(true);
|
||||
let st = self.session.active().ok_or("no document")?;
|
||||
let doc = st.doc.clone();
|
||||
let idx = p.get("artboard").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let r = doc.artboards.get(idx).map(|a| a.rect).ok_or("no such artboard")?;
|
||||
let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0).clamp(0.01, 16.0);
|
||||
vectorcraft_render::raster_size(r, scale)?;
|
||||
// Rendered with the options of a PNG export on white, so its pixels are the exported file's.
|
||||
// `traceViews: true` draws Image Trace objects as their View shows them, as the canvas does.
|
||||
let mut opts = RasterExportOptions { background: Some([255; 3]), ..Default::default() }.render_options(RasterFormat::Png);
|
||||
opts.trace_views = p.get("traceViews").and_then(Value::as_bool) == Some(true);
|
||||
opts.trace_views = trace_views;
|
||||
let img = self.renderer.render_region_with(&doc, r, scale, &opts);
|
||||
// A cancelled render stops drawing: the picture is not whole and is not written.
|
||||
vectorcraft_engine::cancel::check().map_err(|e| e.to_string())?;
|
||||
@@ -317,7 +339,7 @@ impl Headless {
|
||||
vectorcraft_format::write_atomic(std::path::Path::new(path), &png).map_err(|e| format!("write {path}: {e}"))?;
|
||||
out["path"] = json!(path);
|
||||
// `data: true` asks for the image as well as the file.
|
||||
if p.get("data").and_then(Value::as_bool) == Some(true) {
|
||||
if data {
|
||||
out["pngBase64"] = json!(vectorcraft_format::base64_encode(&png));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1452,6 +1452,44 @@ fn headless_backend_methods() {
|
||||
assert!(h.call("ui.resize", json!({})).is_err());
|
||||
}
|
||||
|
||||
/// The headless key, pointer and screenshot calls refuse a value of the wrong type and change
|
||||
/// nothing; omitting it or giving null keeps its default.
|
||||
#[test]
|
||||
fn headless_methods_refuse_params_of_the_wrong_type() {
|
||||
let mut h = Headless::new();
|
||||
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 200}})).unwrap();
|
||||
h.call("ui.tool.select", json!({"tool": "rectangle"})).unwrap();
|
||||
let before = h.call("document.json", json!({})).unwrap();
|
||||
let drag = |mods: Value| json!({"events": [{"kind": "down", "x": 10, "y": 10}, {"kind": "drag", "x": 60, "y": 60, "mods": mods}, {"kind": "up", "x": 60, "y": 60}]});
|
||||
let after_rect = |last: Value| json!({"events": [{"kind": "down", "x": 10, "y": 10}, {"kind": "drag", "x": 60, "y": 60}, {"kind": "up", "x": 60, "y": 60}, last]});
|
||||
for (method, params, key) in [
|
||||
("ui.render", json!({"artboard": "0"}), "artboard"),
|
||||
("ui.render", json!({"scale": "2"}), "scale"),
|
||||
("ui.render", json!({"traceViews": 1}), "traceViews"),
|
||||
("ui.screenshot", json!({"data": "yes", "path": "x.png"}), "data"),
|
||||
("ui.key", json!({"key": "Delete", "shift": "true"}), "shift"),
|
||||
("ui.pointer", drag(json!({"shift": "yes"})), "mods"),
|
||||
("ui.pointer", json!({"mods": 1, "events": []}), "mods"),
|
||||
("ui.pointer", drag(json!([true])), "mods"),
|
||||
// A whole rectangle comes before the malformed event, and none of it is drawn.
|
||||
("ui.pointer", after_rect(json!({"kind": "move", "x": "bad", "y": 0})), "x"),
|
||||
("ui.pointer", after_rect(json!({"kind": "wiggle", "x": 0, "y": 0})), "wiggle"),
|
||||
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "pressure": "bad"})), "pressure"),
|
||||
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "holdMs": true})), "holdMs"),
|
||||
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "tiltX": "5"})), "tiltX"),
|
||||
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "rotation": [0]})), "rotation"),
|
||||
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "space": "screeen"})), "space"),
|
||||
] {
|
||||
let e = h.call(method, params.clone()).unwrap_err();
|
||||
assert!(e.contains(&format!("`{key}`")), "{method} {params}: {e}");
|
||||
}
|
||||
assert_eq!(h.call("document.json", json!({})).unwrap(), before, "a refused call changes nothing");
|
||||
let r = h.call("ui.render", json!({"artboard": null, "scale": null, "traceViews": null})).unwrap();
|
||||
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(300), Some(200)));
|
||||
h.call("ui.pointer", drag(Value::Null)).unwrap();
|
||||
assert_ne!(h.call("document.json", json!({})).unwrap(), before, "null mods keep the packet's");
|
||||
}
|
||||
|
||||
// ---------- workflow tools ----------
|
||||
|
||||
fn id_of(result: &Value) -> u64 {
|
||||
|
||||
@@ -259,7 +259,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
"radius1": num("Star outer radius"),
|
||||
"radius2": num("Star inner radius"),
|
||||
"points": {"type": "integer", "minimum": 3, "description": "Star points (default 5)"},
|
||||
"rotation": num("Rotation in degrees clockwise (polygon/star; 0: a corner or point straight up)"),
|
||||
"rotation": num("Rotation in degrees clockwise about the centre (rectangle/ellipse: 0 upright; polygon/star: 0 a corner or point straight up)"),
|
||||
"x1": num("Line start x"),
|
||||
"y1": num("Line start y"),
|
||||
"x2": num("Line end x"),
|
||||
|
||||
@@ -1492,7 +1492,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"css.exportFile",
|
||||
"Export CSS…",
|
||||
"",
|
||||
"{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first)}",
|
||||
"{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first and how many there are, and hovering the message lists up to 30 of them, fewer when the window is small, with how many were left out)}",
|
||||
),
|
||||
(
|
||||
"file.print",
|
||||
@@ -1529,7 +1529,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.installPlugin",
|
||||
"Install Plug-in…",
|
||||
"",
|
||||
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK when it asks about permissions or a heavy budget: ui.dialog.confirm, answer_dialog and synthetic input are refused → plugin.install's result | {pending: \"pluginInstall\"} while it asks about permissions or a heavy budget | {pending: \"confirm\"} while it asks only about replacing",
|
||||
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)",
|
||||
),
|
||||
(
|
||||
"plugin.cancelRuns",
|
||||
|
||||
+35
-12
@@ -211,23 +211,46 @@ pub(crate) fn verify(pdf: &[u8], standard: Standard) -> Result<(), PdfError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `pdf` without its streams' data (dictionaries and the rest of the syntax), so that what is
|
||||
/// looked for there isn't found in image or font bytes.
|
||||
/// `pdf` without its streams' data, the text of its literal strings and its comments (dictionaries
|
||||
/// and the rest of the syntax), so that what is looked for there isn't found in image or font
|
||||
/// bytes, or in a string such as the file identifier, whose base64 hash can hold `/BM`.
|
||||
fn without_streams(pdf: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(pdf.len().min(1 << 20));
|
||||
let mut at = 0;
|
||||
while let Some(s) = find(pdf, b"stream", at) {
|
||||
let data = s + b"stream".len();
|
||||
// `endstream` itself, or a stream keyword that isn't one (inside a name or string).
|
||||
if (s >= 3 && pdf.get(s - 3..s) == Some(b"end")) || !pdf.get(data).is_some_and(|b| matches!(b, b'\r' | b'\n')) {
|
||||
out.extend_from_slice(pdf.get(at..data).unwrap_or_default());
|
||||
at = data;
|
||||
continue;
|
||||
while let Some(&b) = pdf.get(at) {
|
||||
match b {
|
||||
// A literal string: parentheses nest, and a backslash escapes the next byte.
|
||||
b'(' => {
|
||||
out.extend_from_slice(b"()");
|
||||
let mut depth = 0usize;
|
||||
at += 1;
|
||||
while let Some(&c) = pdf.get(at) {
|
||||
at += 1;
|
||||
match c {
|
||||
b'\\' => at += 1,
|
||||
b'(' => depth += 1,
|
||||
b')' if depth == 0 => break,
|
||||
b')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A comment, to the end of its line.
|
||||
b'%' => at += pdf.get(at..).unwrap_or_default().iter().take_while(|c| !matches!(c, b'\r' | b'\n')).count(),
|
||||
// A stream keyword (not `endstream`, and followed by its end of line): its data is left out.
|
||||
b's' if pdf.get(at..at + 6) == Some(b"stream")
|
||||
&& !(at >= 3 && pdf.get(at - 3..at) == Some(b"end"))
|
||||
&& pdf.get(at + 6).is_some_and(|c| matches!(c, b'\r' | b'\n')) =>
|
||||
{
|
||||
out.extend_from_slice(b"stream");
|
||||
at = find(pdf, b"endstream", at + 6).unwrap_or(pdf.len());
|
||||
}
|
||||
_ => {
|
||||
out.push(b);
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(pdf.get(at..data).unwrap_or_default());
|
||||
at = find(pdf, b"endstream", data).unwrap_or(pdf.len());
|
||||
}
|
||||
out.extend_from_slice(pdf.get(at..).unwrap_or_default());
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -224,3 +224,23 @@ fn verify_finds_what_each_standard_forbids() {
|
||||
assert!(matches!(verify(&file(font), Standard::PdfX4), Err(PdfError::Unsupported(m)) if m.contains("fonts")));
|
||||
assert!(verify(&file("<</Type/FontDescriptor/FontFile2 4 0 R>>"), Standard::PdfX4).is_ok());
|
||||
}
|
||||
|
||||
/// Names inside a string or a comment are text, not syntax: a file identifier, whose base64 hash
|
||||
/// can hold `/BM` or `/Lab`, does not make a file break its standard.
|
||||
#[test]
|
||||
fn verify_skips_names_in_strings_and_comments() {
|
||||
use crate::pdfx::verify;
|
||||
let file = |body: &str| format!("%PDF-1.3\n%/BM/Multiply\n1 0 obj\n{body}\nendobj\n").into_bytes();
|
||||
for ok in [
|
||||
"<</Size 2/ID[(q/BM+Zt1kR0x/Lab=) (q/BM+Zt1kR0x/Lab=)]>>",
|
||||
"<</Title(a\\)/SMask 5 0 R)/Subject(a(b)/ca 0.5)>>",
|
||||
"<</Title(stream\n/BM/Multiply\nendstream)>>",
|
||||
] {
|
||||
for standard in [Standard::PdfX1a, Standard::PdfX3] {
|
||||
assert!(verify(&file(ok), standard).is_ok(), "{standard:?}: {ok}");
|
||||
}
|
||||
}
|
||||
// A name after a string is still read.
|
||||
let after = "<</Title(a(b)c)/BM/Multiply>>";
|
||||
assert!(matches!(verify(&file(after), Standard::PdfX3), Err(PdfError::Unsupported(m)) if m.contains("blend modes")));
|
||||
}
|
||||
|
||||
@@ -736,10 +736,41 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
|
||||
/// Reads the `commands` list one entry at a time from the manifest itself, so each command's
|
||||
/// `params` keep their declaration order and a repeated parameter is refused. A malformed entry
|
||||
/// is an error that names it (its id when the id comes before the fault, otherwise its place in
|
||||
/// the list), and a list is refused at its first entry past [`MAX_COMMANDS`].
|
||||
/// the list), and a list is refused at its first entry past [`MAX_COMMANDS`]. A `commands` value,
|
||||
/// an entry, an `id` or a `label` of the wrong type gets a fixed message of this function's own.
|
||||
fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<Command>, D::Error> {
|
||||
use serde::de::{Error as _, IgnoredAny, MapAccess, SeqAccess, Visitor};
|
||||
|
||||
/// A visitor's methods for a boolean, a number and a string: each is the error its type's
|
||||
/// `wrong()` gives.
|
||||
macro_rules! refuse_scalars {
|
||||
() => {
|
||||
fn visit_bool<E: serde::de::Error>(self, _: bool) -> std::result::Result<Self::Value, E> {
|
||||
Err(E::custom(self.wrong()))
|
||||
}
|
||||
fn visit_i64<E: serde::de::Error>(self, _: i64) -> std::result::Result<Self::Value, E> {
|
||||
Err(E::custom(self.wrong()))
|
||||
}
|
||||
fn visit_u64<E: serde::de::Error>(self, _: u64) -> std::result::Result<Self::Value, E> {
|
||||
Err(E::custom(self.wrong()))
|
||||
}
|
||||
fn visit_f64<E: serde::de::Error>(self, _: f64) -> std::result::Result<Self::Value, E> {
|
||||
Err(E::custom(self.wrong()))
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, _: &str) -> std::result::Result<Self::Value, E> {
|
||||
Err(E::custom(self.wrong()))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// A string field of an entry: anything else is the error "`{key}` must be a string".
|
||||
fn string_field<'de, A: MapAccess<'de>>(map: &mut A, key: &str) -> std::result::Result<std::result::Result<String, String>, A::Error> {
|
||||
Ok(match map.next_value::<Value>()? {
|
||||
Value::String(s) => Ok(s),
|
||||
_ => Err(format!("`{key}` must be a string")),
|
||||
})
|
||||
}
|
||||
|
||||
/// A command's `params`, read in declaration order.
|
||||
struct Params(Vec<(String, Param)>);
|
||||
impl<'de> Deserialize<'de> for Params {
|
||||
@@ -750,6 +781,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
|
||||
|
||||
/// The entry at place `.0` in the list.
|
||||
struct Entry(usize);
|
||||
impl Entry {
|
||||
fn wrong(&self) -> String {
|
||||
format!("command {} must be an object with an `id` and a `label`", command_name(self.0, ""))
|
||||
}
|
||||
}
|
||||
impl<'de> serde::de::DeserializeSeed<'de> for Entry {
|
||||
type Value = Command;
|
||||
fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> std::result::Result<Command, D::Error> {
|
||||
@@ -759,21 +795,29 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
|
||||
impl<'de> Visitor<'de> for Entry {
|
||||
type Value = Command;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "command [{}] as {{id, label, params?}}", self.0)
|
||||
f.write_str(&self.wrong())
|
||||
}
|
||||
refuse_scalars!();
|
||||
fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Command, E> {
|
||||
Err(E::custom(self.wrong()))
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, _: A) -> std::result::Result<Command, A::Error> {
|
||||
Err(A::Error::custom(self.wrong()))
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> std::result::Result<Command, A::Error> {
|
||||
let (mut id, mut label, mut params) = (None::<String>, None::<String>, None::<Params>);
|
||||
let named = |id: &Option<String>, e: &dyn std::fmt::Display| {
|
||||
A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default())))
|
||||
};
|
||||
while let Some(key) = map.next_key::<String>().map_err(|e| named(&id, &e))? {
|
||||
// A key and an ignored value can only fail as JSON syntax, which keeps serde's own error.
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
let repeated = match key.as_str() {
|
||||
"id" if id.is_none() => {
|
||||
id = Some(map.next_value().map_err(|e| named(&id, &e))?);
|
||||
id = Some(string_field(&mut map, "id")?.map_err(|e| named(&id, &e))?);
|
||||
false
|
||||
}
|
||||
"label" if label.is_none() => {
|
||||
label = Some(map.next_value().map_err(|e| named(&id, &e))?);
|
||||
label = Some(string_field(&mut map, "label")?.map_err(|e| named(&id, &e))?);
|
||||
false
|
||||
}
|
||||
"params" if params.is_none() => {
|
||||
@@ -782,7 +826,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
|
||||
}
|
||||
"id" | "label" | "params" => true,
|
||||
_ => {
|
||||
map.next_value::<IgnoredAny>().map_err(|e| named(&id, &e))?;
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
false
|
||||
}
|
||||
};
|
||||
@@ -801,16 +845,22 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
|
||||
}
|
||||
|
||||
struct List;
|
||||
impl List {
|
||||
fn wrong(&self) -> &'static str {
|
||||
"`commands` must be a list of commands, each with an `id` and a `label`"
|
||||
}
|
||||
}
|
||||
impl<'de> Visitor<'de> for List {
|
||||
type Value = Vec<Command>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("`commands` as a list of {id, label, params?}")
|
||||
f.write_str(self.wrong())
|
||||
}
|
||||
refuse_scalars!();
|
||||
fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, _: A) -> std::result::Result<Self::Value, A::Error> {
|
||||
Err(A::Error::custom("`commands` must be a list of {id, label, params?}"))
|
||||
Err(A::Error::custom(self.wrong()))
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
@@ -1215,14 +1265,27 @@ mod tests {
|
||||
r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A","params":{"r":{"type":"bool"},"r":{"type":"int"}}}]}"#,
|
||||
"command `x`: parameter `r` is declared twice",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[1]}"#, "command [0]"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":{"id":"x"}}"#, "must be a list"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[1]}"#, "command [0] must be an object with an `id` and a `label`"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A"},null]}"#, "command [1] must be an object"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[["x"]]}"#, "command [0] must be an object"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":1,"label":"A"}]}"#, "command [0]: `id` must be a string"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":true}]}"#, "command `x`: `label` must be a string"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","id":"y","label":"A"}]}"#, "command `x`: duplicate field `id`"),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","commands":{"id":"x"}}"#,
|
||||
"`commands` must be a list of commands, each with an `id` and a `label`",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":"x"}"#, "`commands` must be a list of commands"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":7}"#, "`commands` must be a list of commands"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":true}"#, "`commands` must be a list of commands"),
|
||||
(r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"commands":[{"id":"x","label":"A"}]}"#, "only a filter or a live effect"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","budget":"heavy","commands":[{"id":"x","label":"A"}]}"#, "heavy filter"),
|
||||
(too_many.as_str(), "at most 32 `commands`"),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
// The message is the manifest reader's own, with serde's place in the manifest once.
|
||||
assert!(!e.contains("invalid type") && !e.contains("expected") && e.matches(" at line ").count() <= 1, "{bad}: {e}");
|
||||
}
|
||||
let long_id = format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"{}","label":"A"}}]}}"#, "c".repeat(MAX_COMMAND_ID + 1));
|
||||
assert!(Manifest::parse(long_id.as_bytes()).is_err());
|
||||
|
||||
@@ -88,12 +88,25 @@ pub(crate) struct Scan {
|
||||
/// Scan `src` (already through [`unescaped`]): the script itself (`file` none) or a file it includes
|
||||
/// (`file`: its path inside the script's folder), with the names it declares (`declared`, from
|
||||
/// [`declarations`] on the same `src`), the `#includepath` folders `paths` in force at its start and
|
||||
/// its variables holding what `known` says.
|
||||
pub(crate) fn scan<'s>(src: &'s str, declared: &Declared<'s>, file: Option<&str>, paths: Rc<[String]>, known: &Known, acc: &mut Acc) -> Scan {
|
||||
/// its variables holding what `known` says. Each of the `\u{…}` escapes `braced` that [`unescaped`]
|
||||
/// read is syntax later than ECMAScript 3, reported when the scan reaches the escape's line.
|
||||
pub(crate) fn scan<'s>(
|
||||
src: &'s str,
|
||||
declared: &Declared<'s>,
|
||||
braced: &[Braced],
|
||||
file: Option<&str>,
|
||||
paths: Rc<[String]>,
|
||||
known: &Known,
|
||||
acc: &mut Acc,
|
||||
) -> Scan {
|
||||
let mut lexer = Lexer::new(src, acc.limits.nesting);
|
||||
let mut a = Analyzer::new(acc, file, paths, known, declared);
|
||||
let mut breaks = LineBreaks::default();
|
||||
let mut braced = braced.iter().peekable();
|
||||
for t in lexer.by_ref() {
|
||||
while let Some((line, escape)) = braced.next_if(|(line, _)| *line <= t.line) {
|
||||
a.acc.problem(report::NEWER_SYNTAX, Some(*line), file, Some(escape));
|
||||
}
|
||||
if let Some(code) = t.problem {
|
||||
a.problem(code, t.line);
|
||||
}
|
||||
@@ -103,6 +116,9 @@ pub(crate) fn scan<'s>(src: &'s str, declared: &Declared<'s>, file: Option<&str>
|
||||
Read::Token(sig) => a.token(sig),
|
||||
}
|
||||
}
|
||||
for (line, escape) in braced {
|
||||
a.acc.problem(report::NEWER_SYNTAX, Some(*line), file, Some(escape));
|
||||
}
|
||||
if let Some(line) = lexer.unclosed_xml {
|
||||
a.problem(report::UNTERMINATED_XML, line);
|
||||
}
|
||||
@@ -115,29 +131,61 @@ pub(crate) fn scan<'s>(src: &'s str, declared: &Declared<'s>, file: Option<&str>
|
||||
Scan { includes, module, lines: lexer.lines(), known }
|
||||
}
|
||||
|
||||
/// `src` with the `\uXXXX` escapes in its names written as the characters they stand for (ECMA-262
|
||||
/// 3rd edition, section 7.6), and `src` itself when no name has one. An escape for a character a
|
||||
/// name may not hold where the escape stands stays as written. Line breaks don't change, so every
|
||||
/// line keeps its number.
|
||||
pub(crate) fn unescaped<'a>(src: Cow<'a, str>, acc: &mut Acc) -> Cow<'a, str> {
|
||||
match unescape_names(&src, acc) {
|
||||
Some(out) => Cow::Owned(out),
|
||||
None => src,
|
||||
/// A `\u{…}` escape in a name, which ECMAScript 3 does not have: its line and its text.
|
||||
pub(crate) type Braced = (usize, String);
|
||||
|
||||
/// `src` with the `\uXXXX` and `\u{…}` escapes in its names and private names written as the
|
||||
/// characters they stand for (ECMA-262, Names and Keywords), and `src` itself when no name has one,
|
||||
/// with the `\u{…}` escapes read, each listed once per line in a row. An escape for a character a
|
||||
/// name may not hold where the escape stands stays as written, and so does a private name that
|
||||
/// starts a line where the name it spells would start a preprocessor line. Line breaks don't
|
||||
/// change, so every line keeps its number.
|
||||
pub(crate) fn unescaped<'a>(src: Cow<'a, str>, acc: &mut Acc) -> (Cow<'a, str>, Vec<Braced>) {
|
||||
let mut braced = vec![];
|
||||
match unescape_names(&src, acc, &mut braced) {
|
||||
Some(out) => (Cow::Owned(out), braced),
|
||||
None => (src, braced),
|
||||
}
|
||||
}
|
||||
|
||||
fn unescape_names(src: &str, acc: &mut Acc) -> Option<String> {
|
||||
fn unescape_names(src: &str, acc: &mut Acc, braced: &mut Vec<Braced>) -> Option<String> {
|
||||
if !src.contains("\\u") {
|
||||
return None;
|
||||
}
|
||||
let mut out = String::with_capacity(src.len());
|
||||
let mut changed = false;
|
||||
let mut lexer = Lexer::new(src, acc.limits.nesting);
|
||||
for t in lexer.by_ref() {
|
||||
if t.kind == T::Ident && t.text.contains("\\u") {
|
||||
let name = unescape_name(t.text);
|
||||
changed |= name != t.text;
|
||||
out.push_str(&name);
|
||||
// One more than the report keeps, so that the report is marked truncated.
|
||||
let room = acc.limits.entries.saturating_add(1);
|
||||
// Only blanks since the last line break (or the start).
|
||||
let mut line_start = true;
|
||||
let mut found = vec![];
|
||||
while let Some(t) = lexer.next() {
|
||||
// A private name is `#` and a name.
|
||||
let (mark, name) = match t.kind {
|
||||
T::Ident => ("", t.text),
|
||||
T::Other => t.text.strip_prefix('#').map_or(("", ""), |name| ("#", name)),
|
||||
_ => ("", ""),
|
||||
};
|
||||
let starts_line = line_start;
|
||||
line_start = t.kind == T::Newline || (line_start && t.kind == T::Space);
|
||||
if name.contains("\\u") {
|
||||
found.clear();
|
||||
let written = unescape_name(name, t.line, &mut found, room);
|
||||
for escape in found.drain(..) {
|
||||
if braced.last() != Some(&escape) && braced.len() < room {
|
||||
braced.push(escape);
|
||||
}
|
||||
}
|
||||
// A private name that starts a line stays as written where the name it spells would
|
||||
// start a preprocessor line.
|
||||
if mark == "#" && starts_line && !lexer.private_line(&written) {
|
||||
out.push_str(t.text);
|
||||
continue;
|
||||
}
|
||||
changed |= written != name;
|
||||
out.push_str(mark);
|
||||
out.push_str(&written);
|
||||
} else {
|
||||
out.push_str(t.text);
|
||||
}
|
||||
@@ -146,25 +194,31 @@ fn unescape_names(src: &str, acc: &mut Acc) -> Option<String> {
|
||||
changed.then_some(out)
|
||||
}
|
||||
|
||||
/// The name `text` with each `\uXXXX` escape for a character a name may hold where it stands written
|
||||
/// as that character: a character a name may start with first, and one a name may hold after that.
|
||||
fn unescape_name(text: &str) -> String {
|
||||
/// The name `text`, on `line`, with each escape for a character a name may hold where it stands
|
||||
/// written as that character: a character a name may start with first, and one a name may hold
|
||||
/// after that. Each `\u{…}` escape read goes into `braced`, unless the last one there is the same
|
||||
/// escape on the same line or `braced` holds `room` of them.
|
||||
fn unescape_name(text: &str, line: usize, braced: &mut Vec<Braced>, room: usize) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(i) = rest.find("\\u") {
|
||||
out.push_str(rest.get(..i).unwrap_or_default());
|
||||
let after = rest.get(i + 2..).unwrap_or_default();
|
||||
let at = rest.get(i..).unwrap_or_default();
|
||||
let first = out.is_empty();
|
||||
let c = crate::lex::escaped(rest.get(i..).unwrap_or_default())
|
||||
.filter(|&c| if first { crate::lex::ident_start(c) } else { crate::lex::ident_part(c) });
|
||||
let c = crate::lex::escape(at).filter(|&(c, _)| if first { crate::lex::ident_start(c) } else { crate::lex::ident_part(c) });
|
||||
match c {
|
||||
Some(c) => {
|
||||
Some((c, len)) => {
|
||||
out.push(c);
|
||||
rest = after.get(4..).unwrap_or_default();
|
||||
let source = at.get(..len).unwrap_or_default();
|
||||
let repeated = braced.last().is_some_and(|(l, s)| *l == line && s == source);
|
||||
if source.starts_with("\\u{") && !repeated && braced.len() < room {
|
||||
braced.push((line, source.to_string()));
|
||||
}
|
||||
rest = at.get(len..).unwrap_or_default();
|
||||
}
|
||||
None => {
|
||||
out.push_str("\\u");
|
||||
rest = after;
|
||||
rest = at.get(2..).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,9 +141,9 @@ pub(crate) fn follow(
|
||||
read.insert(path.clone(), (status, Some(file)));
|
||||
let (text, _) = crate::decode(&b);
|
||||
let mut tallies = Acc::new(limits);
|
||||
let text = analyze::unescaped(text, &mut tallies);
|
||||
let (text, _) = analyze::unescaped(text, &mut tallies);
|
||||
let declared = analyze::declarations(&text, &mut tallies);
|
||||
let scan = analyze::scan(&text, &declared, Some(&path), Rc::clone(&inc.paths), known, &mut tallies);
|
||||
let scan = analyze::scan(&text, &declared, &[], Some(&path), Rc::clone(&inc.paths), known, &mut tallies);
|
||||
acc.steps = acc.steps.saturating_add(tallies.steps);
|
||||
known.add(scan.known, limits.entries);
|
||||
checked.push(ReadFile { path: path.clone(), bytes: b, paths: Rc::clone(&inc.paths) });
|
||||
|
||||
@@ -41,7 +41,9 @@ pub(crate) enum T {
|
||||
/// end or the next `{`.
|
||||
XmlMore,
|
||||
Punct,
|
||||
/// A character no token starts with, or `#` and a name away from the start of a line.
|
||||
/// A character no token starts with, or a private name: `#` and a name away from the start of a
|
||||
/// line, or at its start where the name starts with an escape, or inside braces where the name
|
||||
/// is not a directive's.
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -166,14 +168,33 @@ pub(crate) fn ident_part(c: char) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The character the `\uXXXX` escape at the start of `s` stands for: `None` when `s` doesn't start
|
||||
/// with `\u` and four hexadecimal digits, or when they give a lone surrogate.
|
||||
pub(crate) fn escaped(s: &str) -> Option<char> {
|
||||
s.strip_prefix("\\u")?
|
||||
.get(..4)
|
||||
.filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.and_then(|hex| u32::from_str_radix(hex, 16).ok())
|
||||
.and_then(char::from_u32)
|
||||
/// The character the escape at the start of `s` stands for and the escape's length in bytes: `\u`
|
||||
/// and four hexadecimal digits, or `\u{…}` with one or more hexadecimal digits of a value up to
|
||||
/// U+10FFFF, leading zeros allowed (ECMA-262, UnicodeEscapeSequence and CodePoint). `None` when `s`
|
||||
/// starts with neither, or when the escape gives a lone surrogate.
|
||||
pub(crate) fn escape(s: &str) -> Option<(char, usize)> {
|
||||
let rest = s.strip_prefix("\\u")?;
|
||||
let Some(braced) = rest.strip_prefix('{') else {
|
||||
let c = rest
|
||||
.get(..4)
|
||||
.filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.and_then(|hex| u32::from_str_radix(hex, 16).ok())
|
||||
.and_then(char::from_u32)?;
|
||||
return Some((c, 6));
|
||||
};
|
||||
// The value stops growing past U+10FFFF, so any number of digits is read once and never
|
||||
// overflows.
|
||||
let mut value: u32 = 0;
|
||||
for (i, b) in braced.bytes().enumerate() {
|
||||
match b {
|
||||
b'}' if i > 0 => return char::from_u32(value).map(|c| (c, i + 4)),
|
||||
_ => {
|
||||
let digit = char::from(b).to_digit(16)?;
|
||||
value = (value * 16 + digit).min(0x11_0000);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `Other_ID_Start` (Unicode PropList 17.0): characters kept in `ID_Start` though their category is
|
||||
@@ -394,18 +415,66 @@ impl<'s> Lexer<'s> {
|
||||
}
|
||||
|
||||
/// The rest of a name (its first character included): the characters [`ident_part`] allows,
|
||||
/// written out or as `\uXXXX` escapes. An escape for any other character, or one without four
|
||||
/// hexadecimal digits, ends the name.
|
||||
/// written out or as `\uXXXX` or `\u{…}` escapes ([`escape`]). An escape for any other
|
||||
/// character, or a malformed one, ends the name. Each character of an escape is a step.
|
||||
fn name(&mut self) {
|
||||
loop {
|
||||
match self.peek() {
|
||||
Some('\\') if escaped(self.rest()).is_some_and(ident_part) => self.skip(6),
|
||||
Some('\\') => match escape(self.rest()) {
|
||||
Some((c, len)) if ident_part(c) => {
|
||||
self.pos += len;
|
||||
self.steps += len;
|
||||
}
|
||||
_ => break,
|
||||
},
|
||||
Some(c) if ident_part(c) => self.bump(c),
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A name starts right after the `#` here: its first character written out, or an escape for a
|
||||
/// character a name may start with.
|
||||
fn private_name_follows(&self) -> bool {
|
||||
let after = self.rest().get(1..).unwrap_or_default();
|
||||
match after.chars().next() {
|
||||
Some('\\') => escape(after).is_some_and(|(c, _)| ident_start(c)),
|
||||
Some(c) => ident_start(c),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `#` at the start of this line starts a private name, not a preprocessor line: the name
|
||||
/// starts with an escape, which no directive's name holds, or [`Lexer::private_line`] holds for
|
||||
/// it.
|
||||
fn private_at_line_start(&self) -> bool {
|
||||
if !self.private_name_follows() {
|
||||
return false;
|
||||
}
|
||||
let after = self.rest().get(1..).unwrap_or_default();
|
||||
after.starts_with('\\') || self.private_line(after)
|
||||
}
|
||||
|
||||
/// A line that starts with `#` and then `rest` is a private name here, not a preprocessor line:
|
||||
/// the line is inside braces or in the code of an XML literal, and the name `rest` starts with
|
||||
/// is not a directive's. The name runs over every character a name may hold, written out or as
|
||||
/// an escape, so `#include$size` is not `#include`.
|
||||
pub fn private_line(&self, rest: &str) -> bool {
|
||||
let in_code = !self.braces.is_empty() || self.deeper_braces > 0 || !self.xml.is_empty();
|
||||
let mut end = 0;
|
||||
while let Some(more) = rest.get(end..) {
|
||||
let len = match more.chars().next() {
|
||||
Some('\\') => escape(more).filter(|&(c, _)| ident_part(c)).map(|(_, len)| len),
|
||||
Some(c) if ident_part(c) => Some(c.len_utf8()),
|
||||
_ => None,
|
||||
};
|
||||
let Some(len) = len else { break };
|
||||
end += len;
|
||||
}
|
||||
let name = rest.get(..end).unwrap_or_default();
|
||||
in_code && !catalog::DIRECTIVES.iter().any(|d| d.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
fn digits(&mut self, ok: fn(char) -> bool) {
|
||||
while let Some(c) = self.peek().filter(|&c| ok(c) || c == '_') {
|
||||
self.bump(c);
|
||||
@@ -871,10 +940,10 @@ impl<'s> Iterator for Lexer<'s> {
|
||||
} else if self.starts("/*") {
|
||||
problem = self.block_comment();
|
||||
T::Comment
|
||||
} else if c == '#' && self.line_start {
|
||||
} else if c == '#' && self.line_start && !self.private_at_line_start() {
|
||||
self.until_line_break();
|
||||
T::Directive
|
||||
} else if c == '#' && self.peek_at(1).is_some_and(ident_start) {
|
||||
} else if c == '#' && self.private_name_follows() {
|
||||
self.bump('#');
|
||||
self.name();
|
||||
T::Other
|
||||
@@ -906,7 +975,7 @@ impl<'s> Iterator for Lexer<'s> {
|
||||
self.close_level();
|
||||
self.bump('}');
|
||||
return Some(self.markup_token(start, line, T::XmlMore, stmt, expr));
|
||||
} else if ident_start(c) || (c == '\\' && escaped(self.rest()).is_some_and(ident_start)) {
|
||||
} else if ident_start(c) || (c == '\\' && escape(self.rest()).is_some_and(|(c, _)| ident_start(c))) {
|
||||
self.name();
|
||||
T::Ident
|
||||
} else if c.is_ascii_digit() || (c == '.' && self.peek_at(1).is_some_and(|d| d.is_ascii_digit())) {
|
||||
|
||||
@@ -166,14 +166,14 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits:
|
||||
if invalid {
|
||||
acc.problem(report::NOT_UTF8, None, None, None);
|
||||
}
|
||||
let text = analyze::unescaped(text, &mut acc);
|
||||
let (text, braced) = analyze::unescaped(text, &mut acc);
|
||||
let declared = analyze::declarations(&text, &mut acc);
|
||||
let none = analyze::Known::default();
|
||||
// With a loader, this first scan finds the includes and what the script's variables hold; its
|
||||
// tallies are left out.
|
||||
let mut tallies = report::Acc::new(limits);
|
||||
let pre = acc.clone();
|
||||
let scan = analyze::scan(&text, &declared, None, std::rc::Rc::from([]), &none, if loader.is_some() { &mut tallies } else { &mut acc });
|
||||
let scan = analyze::scan(&text, &declared, &braced, None, std::rc::Rc::from([]), &none, if loader.is_some() { &mut tallies } else { &mut acc });
|
||||
acc.steps = acc.steps.saturating_add(tallies.steps);
|
||||
if scan.module {
|
||||
// A module's report holds its kind and its lines, and none of what the scan found.
|
||||
@@ -183,7 +183,7 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits:
|
||||
return acc.finish(Kind::Module, scan.lines);
|
||||
}
|
||||
let Some(loader) = loader else {
|
||||
let mut acc = settle(acc, pre, &text, &declared, scan.known);
|
||||
let mut acc = settle(acc, pre, &text, &declared, &braced, scan.known);
|
||||
includes::not_read(&mut acc, scan.includes);
|
||||
return acc.finish(Kind::Script, scan.lines);
|
||||
};
|
||||
@@ -191,17 +191,23 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits:
|
||||
let read = includes::follow(&mut acc, scan.includes, loader, name, bytes.len(), &mut known);
|
||||
// Each file's text and the names it declares are worked out once for all the scans below.
|
||||
let decoded: Vec<_> = read.iter().map(|file| decode(&file.bytes)).collect();
|
||||
let texts: Vec<_> = decoded.into_iter().map(|(text, invalid)| (analyze::unescaped(text, &mut acc), invalid)).collect();
|
||||
let declarations: Vec<_> = texts.iter().map(|(text, _)| analyze::declarations(text, &mut acc)).collect();
|
||||
let texts: Vec<_> = decoded
|
||||
.into_iter()
|
||||
.map(|(text, invalid)| {
|
||||
let (text, braced) = analyze::unescaped(text, &mut acc);
|
||||
(text, braced, invalid)
|
||||
})
|
||||
.collect();
|
||||
let declarations: Vec<_> = texts.iter().map(|(text, ..)| analyze::declarations(text, &mut acc)).collect();
|
||||
// A variable may get what it holds from another file's variable: the files are scanned again,
|
||||
// each with what is known so far, while that grows, at most three more times.
|
||||
for _ in 0..3 {
|
||||
let before = known.len();
|
||||
let mut tallies = report::Acc::new(limits);
|
||||
let more = analyze::scan(&text, &declared, None, std::rc::Rc::from([]), &known, &mut tallies).known;
|
||||
let more = analyze::scan(&text, &declared, &[], None, std::rc::Rc::from([]), &known, &mut tallies).known;
|
||||
known.add(more, limits.entries);
|
||||
for ((file, (text, _)), declared) in read.iter().zip(&texts).zip(&declarations) {
|
||||
let more = analyze::scan(text, declared, Some(&file.path), std::rc::Rc::clone(&file.paths), &known, &mut tallies).known;
|
||||
for ((file, (text, ..)), declared) in read.iter().zip(&texts).zip(&declarations) {
|
||||
let more = analyze::scan(text, declared, &[], Some(&file.path), std::rc::Rc::clone(&file.paths), &known, &mut tallies).known;
|
||||
known.add(more, limits.entries);
|
||||
}
|
||||
acc.steps = acc.steps.saturating_add(tallies.steps);
|
||||
@@ -210,12 +216,12 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits:
|
||||
}
|
||||
}
|
||||
// The scans for the report: every file starts with what any file's variables hold.
|
||||
let lines = analyze::scan(&text, &declared, None, std::rc::Rc::from([]), &known, &mut acc).lines;
|
||||
for ((file, (text, invalid)), declared) in read.iter().zip(&texts).zip(&declarations) {
|
||||
let lines = analyze::scan(&text, &declared, &braced, None, std::rc::Rc::from([]), &known, &mut acc).lines;
|
||||
for ((file, (text, braced, invalid)), declared) in read.iter().zip(&texts).zip(&declarations) {
|
||||
if *invalid {
|
||||
acc.problem(report::NOT_UTF8, None, Some(&file.path), None);
|
||||
}
|
||||
analyze::scan(text, declared, Some(&file.path), std::rc::Rc::clone(&file.paths), &known, &mut acc);
|
||||
analyze::scan(text, declared, braced, Some(&file.path), std::rc::Rc::clone(&file.paths), &known, &mut acc);
|
||||
}
|
||||
acc.finish(Kind::Script, lines)
|
||||
}
|
||||
@@ -230,6 +236,7 @@ fn settle<'l>(
|
||||
pre: report::Acc<'l>,
|
||||
text: &str,
|
||||
declared: &analyze::Declared<'_>,
|
||||
braced: &[analyze::Braced],
|
||||
mut known: analyze::Known,
|
||||
) -> report::Acc<'l> {
|
||||
if known.len() == 0 {
|
||||
@@ -240,7 +247,7 @@ fn settle<'l>(
|
||||
for _ in 0..3 {
|
||||
let before = known.len();
|
||||
let mut acc = pre.clone();
|
||||
let more = analyze::scan(text, declared, None, std::rc::Rc::from([]), &known, &mut acc).known;
|
||||
let more = analyze::scan(text, declared, braced, None, std::rc::Rc::from([]), &known, &mut acc).known;
|
||||
known.add(more, entries);
|
||||
if known.len() == before {
|
||||
acc.steps = acc.steps.saturating_add(spent);
|
||||
@@ -249,7 +256,7 @@ fn settle<'l>(
|
||||
spent = spent.saturating_add(acc.steps.saturating_sub(pre.steps));
|
||||
}
|
||||
let mut acc = pre;
|
||||
analyze::scan(text, declared, None, std::rc::Rc::from([]), &known, &mut acc);
|
||||
analyze::scan(text, declared, braced, None, std::rc::Rc::from([]), &known, &mut acc);
|
||||
acc.steps = acc.steps.saturating_add(spent);
|
||||
acc
|
||||
}
|
||||
|
||||
@@ -271,7 +271,7 @@ fn names_written_with_escapes_are_read_as_the_names_they_spell() {
|
||||
/// `src` with the escapes in its names written as the characters they stand for.
|
||||
fn unescaped(src: &str) -> String {
|
||||
let limits = Limits::default();
|
||||
crate::analyze::unescaped(std::borrow::Cow::Borrowed(src), &mut crate::report::Acc::new(&limits)).into_owned()
|
||||
crate::analyze::unescaped(std::borrow::Cow::Borrowed(src), &mut crate::report::Acc::new(&limits)).0.into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -364,6 +364,155 @@ fn malformed_escapes_in_bulk_are_read_once_through() {
|
||||
assert_eq!(r.lines, 3);
|
||||
assert_eq!(feature(&r, "notify").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
assert!(r.steps <= 5 * src.len() + 16, "{} steps for {} bytes", r.steps, src.len());
|
||||
// Braced escapes: long runs of digits, closed and not, and ones that end at once.
|
||||
let zeros = "0".repeat(100_000);
|
||||
let src = format!(
|
||||
"a\\u{{{zeros}62}};\n\\u{{{}\n{}\n{}\nalert(1);\n",
|
||||
"f".repeat(100_000),
|
||||
"\\u{".repeat(20_000),
|
||||
"\\u{0000000061}\\u{110000}\\u{}\\u{D800}#\\u{61}".repeat(10_000)
|
||||
);
|
||||
let r = report(&src);
|
||||
assert_eq!(r.lines, 5);
|
||||
assert_eq!(feature(&r, "notify").map(|f| f.lines.as_slice()), Some(&[5][..]));
|
||||
assert!(r.steps <= 5 * src.len() + 16, "{} steps for {} bytes", r.steps, src.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn braced_escapes_in_names_are_read_by_their_value() {
|
||||
for (src, want) in [
|
||||
("\\u{61}pp", "app"),
|
||||
("a\\u{62}c", "abc"),
|
||||
("\\u{0000000061}", "a"),
|
||||
("\\u{2118}\\u{203F}", "\u{2118}\u{203F}"),
|
||||
("a\\u{1D7CE}", "a\u{1D7CE}"),
|
||||
("\\u{1D49C}", "\u{1D49C}"),
|
||||
// Not at the start of a name, in no name, out of range, empty, a surrogate and not closed.
|
||||
("\\u{30}a", "\\u{30}a"),
|
||||
("a\\u{1F600}", "a\\u{1F600}"),
|
||||
("a\\u{110000}", "a\\u{110000}"),
|
||||
("a\\u{FFFFFFFFFFFFFFFFFFFF}b", "a\\u{FFFFFFFFFFFFFFFFFFFF}b"),
|
||||
("a\\u{}b", "a\\u{}b"),
|
||||
("a\\u{D800}", "a\\u{D800}"),
|
||||
("a\\u{61", "a\\u{61"),
|
||||
("a\\u{6 1}", "a\\u{6 1}"),
|
||||
] {
|
||||
assert_eq!(unescaped(src), want, "{src:?}");
|
||||
}
|
||||
assert_eq!(tokens("\\u{61}pp.x"), [(T::Ident, "\\u{61}pp"), (T::Punct, "."), (T::Ident, "x")]);
|
||||
assert_eq!(tokens("a\\u{0000000062}"), [(T::Ident, "a\\u{0000000062}")]);
|
||||
assert_eq!(tokens("a\\u{1F600}").get(..2), Some(&[(T::Ident, "a"), (T::Other, "\\")][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn braced_name_escape_reports_later_syntax_and_member() {
|
||||
let r = report("\\u{61}pp.activeDocument.acmeName;\nvar a\\u{62}c = 1, \\u{0000000061}pp2 = 2;\n\\u{61}pp.x + \\u{61}pp.y;\n");
|
||||
let members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect();
|
||||
assert_eq!(members, ["app.activeDocument.acmeName", "app.x", "app.y"]);
|
||||
assert_eq!(
|
||||
problems(&r),
|
||||
[
|
||||
("newerSyntax", Some(1), Some("\\u{61}")),
|
||||
("newerSyntax", Some(2), Some("\\u{62}")),
|
||||
("newerSyntax", Some(2), Some("\\u{0000000061}")),
|
||||
("newerSyntax", Some(3), Some("\\u{61}")),
|
||||
]
|
||||
);
|
||||
// An escape that isn't a name's character, or isn't closed, makes no name and no report of one.
|
||||
for src in [
|
||||
"\\u{1F600}pp.activeDocument;",
|
||||
"\\u{110000}pp.activeDocument;",
|
||||
"\\u{}pp.activeDocument;",
|
||||
"\\u{D800}pp.activeDocument;",
|
||||
"\\u{61pp.activeDocument;",
|
||||
] {
|
||||
let r = report(src);
|
||||
assert!(r.members.iter().all(|m| !m.name.starts_with("app")), "{src:?}: {:?}", r.members);
|
||||
assert!(r.problems.iter().all(|p| p.detail.as_deref().is_none_or(|d| !d.starts_with("\\u{"))), "{src:?}: {:?}", r.problems);
|
||||
}
|
||||
// In an included file, the report names the file.
|
||||
let mut m = mem(&[("lib.jsxinc", "\\u{61}pp.name;\n")]);
|
||||
let r = check("main.jsx", b"#include 'lib.jsxinc'\n", Some(&mut m), &Limits::default());
|
||||
let found: Vec<_> = r.problems.iter().map(|p| (p.code, p.line, p.file.as_deref(), p.detail.as_deref())).collect();
|
||||
assert_eq!(found, [("newerSyntax", Some(1), Some("lib.jsxinc"), Some("\\u{61}"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_names_with_escaped_starts_are_single_tokens() {
|
||||
assert_eq!(tokens("a #\\u0061b"), [(T::Ident, "a"), (T::Other, "#\\u0061b")]);
|
||||
assert_eq!(tokens("this.#\\u0061pp"), [(T::Ident, "this"), (T::Punct, "."), (T::Other, "#\\u0061pp")]);
|
||||
assert_eq!(tokens("o.#\\u{61}b"), [(T::Ident, "o"), (T::Punct, "."), (T::Other, "#\\u{61}b")]);
|
||||
// An escape for a character no name starts with leaves `#` on its own.
|
||||
assert_eq!(tokens("a #\\u0030b").get(..3), Some(&[(T::Ident, "a"), (T::Other, "#"), (T::Other, "\\")][..]));
|
||||
let r = report("var q = this.#\\u0061pp;\nvar r = o.#\\u{61}b;\n");
|
||||
assert!(r.members.is_empty(), "{:?}", r.members);
|
||||
assert_eq!(
|
||||
problems(&r),
|
||||
[("newerSyntax", Some(1), Some("#app")), ("newerSyntax", Some(2), Some("\\u{61}")), ("newerSyntax", Some(2), Some("#ab"))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_name_reports_decoded_construct() {
|
||||
let r = report("var q = this.#hid\\u0064en;\nvar r = this.#\\u0061\\u0062;\n");
|
||||
assert_eq!(problems(&r), [("newerSyntax", Some(1), Some("#hidden")), ("newerSyntax", Some(2), Some("#ab"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_name_at_line_start_is_not_a_directive() {
|
||||
let r = report(concat!(
|
||||
"class Box {\n",
|
||||
" #size = 1;\n",
|
||||
" #\\u0061rea = 2;\n",
|
||||
" #include 'a.jsxinc'\n",
|
||||
" #\\u0069nclude = 4;\n",
|
||||
" #\\u{69}nclude = 5;\n",
|
||||
"}\n",
|
||||
"#\\u0062ox = 3;\n",
|
||||
"#pragma once\n",
|
||||
"#target acme\n",
|
||||
));
|
||||
let directives: Vec<_> = r.directives.iter().map(|d| (d.name, d.line)).collect();
|
||||
assert_eq!(directives, [("include", 4), ("target", 10)]);
|
||||
// Where the name a private name's escapes spell would start a preprocessor line, the report
|
||||
// gives the name as written.
|
||||
assert_eq!(
|
||||
problems(&r),
|
||||
[
|
||||
("newerSyntax", Some(1), Some("class")),
|
||||
("newerSyntax", Some(2), Some("#size")),
|
||||
("newerSyntax", Some(3), Some("#area")),
|
||||
("newerSyntax", Some(5), Some("#\\u0069nclude")),
|
||||
("newerSyntax", Some(6), Some("\\u{69}")),
|
||||
("newerSyntax", Some(6), Some("#\\u{69}nclude")),
|
||||
("newerSyntax", Some(8), Some("#\\u0062ox")),
|
||||
("unknownDirective", Some(9), Some("#pragma")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_name_that_starts_with_a_directive_name_is_not_a_directive() {
|
||||
let r = report(concat!(
|
||||
"class Box {\n",
|
||||
" #include$size = 1;\n",
|
||||
" #include\u{e9} = 2;\n",
|
||||
" #include\\u0041 = 3;\n",
|
||||
" #include\\u{41} = 4;\n",
|
||||
" #INCLUDE 'a.jsxinc'\n",
|
||||
"}\n",
|
||||
));
|
||||
let directives: Vec<_> = r.directives.iter().map(|d| (d.name, d.line)).collect();
|
||||
assert_eq!(directives, [("include", 6)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_code_uses_escaped_names() {
|
||||
let r = report("var x = <a>{\\u{61}pp.activeDocument}</a>;\nvar y = <b>\\u0061pp.z \\u{61}</b>;\n");
|
||||
let members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect();
|
||||
assert_eq!(members, ["app.activeDocument"]);
|
||||
assert_eq!(problems(&r), [("newerSyntax", Some(1), Some("\\u{61}"))]);
|
||||
assert!(tokens("var x = <a>{this.#\\u0061b}</a>;").contains(&(T::Other, "#\\u0061b")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1590,7 +1739,7 @@ fn include_lines_share_the_folders_of_the_include_path_before_them() {
|
||||
let limits = Limits::default();
|
||||
let mut acc = report::Acc::new(&limits);
|
||||
let declared = analyze::declarations(&src, &mut acc);
|
||||
let scan = analyze::scan(&src, &declared, None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc);
|
||||
let scan = analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc);
|
||||
let (first, rest) = scan.includes.split_first().unwrap();
|
||||
assert_eq!((first.paths.len(), rest.len()), (64, 999));
|
||||
assert!(rest.iter().all(|i| std::rc::Rc::ptr_eq(&i.paths, &first.paths)), "one list of folders, not a copy for each line");
|
||||
|
||||
@@ -119,6 +119,13 @@ impl PointSnap {
|
||||
Self { targets }
|
||||
}
|
||||
|
||||
/// Snapping for a point placed anywhere, as a drawing tool's ([`DrawSnap`]) is: the art in the
|
||||
/// window as targets ([`Targets::for_drawing`]), live text as Snap to Glyph asks.
|
||||
pub fn drawn(cx: &ToolContext) -> Self {
|
||||
let glyphs = (cx.snap_to_glyph && cx.smart_guides && cx.alignment_guides).then_some(cx.glyph_snap);
|
||||
Self::new(cx, || Targets::for_drawing(cx.doc, &[], visible(cx), glyphs))
|
||||
}
|
||||
|
||||
/// Where `p` goes, and the guides showing why.
|
||||
pub fn snap(&self, cx: &ToolContext, p: Point) -> (Point, Vec<Overlay>) {
|
||||
self.snap_from(cx, p, None)
|
||||
|
||||
@@ -109,6 +109,19 @@ impl PointerEvent {
|
||||
pub fn json_backquote(v: &Value, default: bool) -> Result<bool, String> {
|
||||
v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned()))
|
||||
}
|
||||
/// Checks the optional keys of a JSON pointer event (control channel, MCP): `pressure`,
|
||||
/// `holdMs`, `tiltX`, `tiltY` and `rotation` must be numbers, and `space` must be `doc` or
|
||||
/// `screen`. A key that is absent or null keeps its default.
|
||||
pub fn json_check(e: &Value) -> Result<(), String> {
|
||||
let given = |k: &str| e.get(k).filter(|v| !v.is_null());
|
||||
if let Some(k) = ["pressure", "holdMs", "tiltX", "tiltY", "rotation"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) {
|
||||
return Err(format!("`{k}` must be a number"));
|
||||
}
|
||||
if given("space").is_some_and(|v| !matches!(v.as_str(), Some("doc" | "screen"))) {
|
||||
return Err("`space` must be doc or screen".to_owned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -135,6 +148,27 @@ mod tests {
|
||||
assert!(PointerEvent::json_backquote(&json!({"backquote": bad}), false).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_check_refuses_pen_values_and_spaces_of_the_wrong_type() {
|
||||
use serde_json::json;
|
||||
for ok in [
|
||||
json!({}),
|
||||
json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "space": "screen"}),
|
||||
json!({"pressure": null, "space": null}),
|
||||
json!({"space": "doc"}),
|
||||
] {
|
||||
assert_eq!(PointerEvent::json_check(&ok), Ok(()), "{ok}");
|
||||
}
|
||||
for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation"] {
|
||||
for bad in [json!("1"), json!(true), json!([1])] {
|
||||
assert_eq!(PointerEvent::json_check(&json!({k: bad})), Err(format!("`{k}` must be a number")), "{k}: {bad}");
|
||||
}
|
||||
}
|
||||
for bad in [json!("screeen"), json!(true), json!(1)] {
|
||||
assert_eq!(PointerEvent::json_check(&json!({"space": bad})), Err("`space` must be doc or screen".to_owned()), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keys tools care about.
|
||||
|
||||
@@ -9,13 +9,14 @@
|
||||
//! ruler's ticks, else to whole pixels, the grid, with Smart Guides the art's and the artboards'
|
||||
//! edges, centres and anchors, or with Snap to Point the anchors. Dropped off the canvas onto its
|
||||
//! ruler, a moved guide is deleted. Hidden or locked guides (View › Guides), and guides on a hidden
|
||||
//! or locked layer, can't be picked.
|
||||
//! or locked layer, can't be picked. The rulers' origin, dragged out of their corner
|
||||
//! ([`OriginDrag`]), snaps as a drawn point does.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Guide, NodeId};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use crate::guides::Targets;
|
||||
use crate::guides::{PointSnap, Targets};
|
||||
use crate::{Action, Cursor, Overlay, PointerEvent, PointerKind, ToolContext};
|
||||
|
||||
/// The ruler guide under `p`, by its index in `guide.list`: the nearest within the selection
|
||||
@@ -247,6 +248,39 @@ impl NewGuide {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rulers' origin dragged out of the box where they meet, with any tool: it snaps as a drawn
|
||||
/// point does ([`PointSnap::drawn`]), with Smart Guides onto the anchors, centres, edges and paths
|
||||
/// of the art and the artboards or into line with them, with Snap to Point onto the anchors and
|
||||
/// along the ruler guides, else onto whole pixels or the grid. The targets are gathered when the
|
||||
/// drag begins. It changes nothing: the origin is set where the button is released.
|
||||
pub struct OriginDrag {
|
||||
snap: PointSnap,
|
||||
/// The guides showing what the origin snapped to.
|
||||
guides: Vec<Overlay>,
|
||||
}
|
||||
|
||||
impl OriginDrag {
|
||||
pub fn new(cx: &ToolContext) -> Self {
|
||||
Self { snap: PointSnap::drawn(cx), guides: vec![] }
|
||||
}
|
||||
|
||||
/// Where the origin goes with the pointer at `p` (none off the canvas).
|
||||
pub fn pointer(&mut self, cx: &ToolContext, p: Option<Point>) -> Option<Point> {
|
||||
let Some(p) = p else {
|
||||
self.guides.clear();
|
||||
return None;
|
||||
};
|
||||
let (at, guides) = self.snap.snap(cx, p);
|
||||
self.guides = guides;
|
||||
Some(at)
|
||||
}
|
||||
|
||||
/// The guides showing what the origin snapped to.
|
||||
pub fn overlays(&self) -> Vec<Overlay> {
|
||||
self.guides.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection tool's ruler-guide handling: [`Self::press`] on a press, [`Self::pointer`] for
|
||||
/// the rest of the gesture.
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::{VectorcraftApp, io, place};
|
||||
use crate::services::Inbox;
|
||||
|
||||
impl VectorcraftApp {
|
||||
/// A file dialog is open off the UI thread (a sheet on macOS, [`picks`]): what asked for it runs
|
||||
@@ -13,13 +14,25 @@ impl VectorcraftApp {
|
||||
self.services.dialogs_are_sheets && self.file_dialog_open()
|
||||
}
|
||||
|
||||
pub(super) fn drain_inbox(&mut self) {
|
||||
let arrived: Vec<(String, Vec<u8>)> =
|
||||
self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default();
|
||||
for (name, bytes) in arrived {
|
||||
if let Err(e) = io::open_bytes(self, &name, &bytes, None) {
|
||||
io::report_open_error(self, &name, &e);
|
||||
}
|
||||
pub(crate) fn drain_inbox(&mut self) {
|
||||
fn take(q: Option<&Inbox>) -> Vec<(String, Vec<u8>)> {
|
||||
q.map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default()
|
||||
}
|
||||
let answers = self.services.picked_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner())));
|
||||
// The web's file picker answers for automation when automation opened it; the page's script
|
||||
// is automation.
|
||||
let mut arrived: Vec<_> = take(self.services.inbox.as_ref()).into_iter().map(|f| (f, false)).collect();
|
||||
for answer in answers.unwrap_or_default() {
|
||||
let automated = self.picks.answer_web_open();
|
||||
arrived.extend(answer.map(|f| (f, automated)));
|
||||
}
|
||||
arrived.extend(take(self.services.page_inbox.as_ref()).into_iter().map(|f| (f, true)));
|
||||
for ((name, bytes), automated) in arrived {
|
||||
crate::picks::as_automated(self, automated, |app| {
|
||||
if let Err(e) = io::open_bytes(app, &name, &bytes, None) {
|
||||
io::report_open_error(app, &name, &e);
|
||||
}
|
||||
});
|
||||
}
|
||||
place::drain(self);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,13 @@ impl VectorcraftApp {
|
||||
self.ui.answering_control || self.synthetic_frame
|
||||
}
|
||||
|
||||
/// Did automation ask for what is being handled now: [`Self::automation_is_acting`], or the
|
||||
/// answer of a file dialog that automation opened ([`crate::picks::as_automated`]), even when a
|
||||
/// person picked the file in it?
|
||||
pub(crate) fn automation_asked(&self) -> bool {
|
||||
self.automation_is_acting() || self.picks.automated()
|
||||
}
|
||||
|
||||
/// Run a Help link command and open the URL it returns.
|
||||
pub fn open_link(&mut self, id: &str) {
|
||||
if let Ok(v) = self.run(id, serde_json::json!({}))
|
||||
|
||||
@@ -50,7 +50,7 @@ use fill::fill_uncovered;
|
||||
use fill::{fill_view, polygon_area};
|
||||
#[cfg(test)]
|
||||
use grid::ruler_rects;
|
||||
use grid::{LineLook, PIXEL_GRID, PIXEL_GRID_ZOOM, checker, clip_segment, grid, ruler_input, rulers, textured_quad, view_bounds};
|
||||
use grid::{LineLook, PIXEL_GRID, PIXEL_GRID_ZOOM, checker, clip_segment, grid, ruler_input, rulers, rulers_hidden, textured_quad, view_bounds};
|
||||
pub(crate) use grid::{RulerScale, checker_texture, ruler_label, ruler_origin_dragging};
|
||||
#[cfg(test)]
|
||||
pub(crate) use grid::{TRANSPARENCY_GRID, vertical_label_height};
|
||||
@@ -283,7 +283,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.ctx().request_repaint_after_secs(secs as f32);
|
||||
}
|
||||
let hover_still = wait.is_none();
|
||||
let origin_preview = if app.ui.view.rulers && app.ui.screen_mode < 3 { ruler_input(app, ui, full, rect, &xf) } else { None };
|
||||
let origin_preview = if app.ui.view.rulers && app.ui.screen_mode < 3 { ruler_input(app, ui, full, rect, &xf) } else { rulers_hidden(app, ui) };
|
||||
crate::document_drag::drop_on_canvas(app, &resp, &xf);
|
||||
panel_drop(app, ui, &resp, &xf);
|
||||
// In Presentation Mode a right click or a long touch opens no context menu.
|
||||
|
||||
@@ -53,7 +53,10 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf:
|
||||
/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it), the
|
||||
/// Appearance panel's thumbnail gives the object (the topmost one hit) the appearance it carries
|
||||
/// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on
|
||||
/// top of its appearance). A chip follows the pointer meanwhile.
|
||||
/// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary`
|
||||
/// for a brush library's). A Brushes panel scatter, art or pattern
|
||||
/// brush dropped where there is no art places a copy of its art there (`brush.placeArt`). A chip
|
||||
/// follows the pointer meanwhile.
|
||||
pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) {
|
||||
crate::panels::swatches::drag_preview(app, ui.ctx());
|
||||
let Some(pos) = ui.input(|i| i.pointer.interact_pos()) else { return };
|
||||
@@ -86,7 +89,19 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(hit) = hit_at(app, xf.to_doc(pos), xf.zoom) else { return };
|
||||
let hit = hit_at(app, xf.to_doc(pos), xf.zoom);
|
||||
// A scatter, art or pattern brush from the Brushes panel dropped where there is no art: a copy
|
||||
// of its art, centered where it is dropped, to edit and Alt-drag back onto the brush.
|
||||
if let (None, widgets::PanelDrag::Brush { name, def }) = (&hit, &*d)
|
||||
&& matches!(def["type"].as_str(), Some("scatter" | "art" | "pattern"))
|
||||
{
|
||||
let at = xf.to_doc(pos);
|
||||
if let Err(e) = app.run("brush.placeArt", json!({"name": name, "x": at.x, "y": at.y})) {
|
||||
app.status(e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(hit) = hit else { return };
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let (cmd, params) = match &*d {
|
||||
widgets::PanelDrag::Paint { params, .. } => {
|
||||
|
||||
@@ -181,8 +181,9 @@ pub(super) fn ruler_rects(full: egui::Rect) -> [egui::Rect; 3] {
|
||||
/// it makes none. A double-click on a ruler (both clicks on that ruler) makes a guide at the
|
||||
/// pointer, across the ruler's axis (a vertical one on the top ruler, a horizontal one on the
|
||||
/// left; swapped in a view turned 90°, where the rulers read the other document axis, and the
|
||||
/// nearer axis in between), unsnapped, as one `guide.add` and so one undo step. The corner drags the rulers' origin or resets it on a
|
||||
/// double-click.
|
||||
/// nearer axis in between), unsnapped, as one `guide.add` and so one undo step. The corner drags
|
||||
/// the rulers' origin, snapped as a drawn point is (`Session::ruler_origin_drag`), or resets it on
|
||||
/// a double-click.
|
||||
pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, canvas: egui::Rect, xf: &Xf) -> Option<Point> {
|
||||
let [top, left, corner] = ruler_rects(full);
|
||||
// Right-click on a ruler or the origin box: the document units, to swap between them as
|
||||
@@ -274,9 +275,17 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
|
||||
let mut preview = None;
|
||||
if let Some((started_in, mut cancelled)) = ui.data(|d| d.get_temp::<(Option<u64>, bool)>(drag_id)) {
|
||||
cancelled |= started_in != uid || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape));
|
||||
let at = corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p));
|
||||
let pointer =
|
||||
corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p));
|
||||
// The origin snaps as a drawn point does (Smart Guides, Snap to Point, pixels, the grid).
|
||||
let at = if cancelled {
|
||||
app.session.end_ruler_origin_drag();
|
||||
None
|
||||
} else {
|
||||
app.session.ruler_origin_drag(pointer, app.view_info())
|
||||
};
|
||||
if corner.drag_stopped_by(egui::PointerButton::Primary) {
|
||||
ui.data_mut(|d| d.remove::<(Option<u64>, bool)>(drag_id));
|
||||
end_ruler_origin_drag(app, ui);
|
||||
if !cancelled
|
||||
&& let Some(at) = at
|
||||
&& let Err(e) = app.run("document.setRulerOrigin", json!({"x": at.x, "y": at.y, "artboard": app.view().map_or(0, |v| v.artboard)}))
|
||||
@@ -284,7 +293,7 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
|
||||
app.status(e.to_string());
|
||||
}
|
||||
} else if !ui.input(|i| i.pointer.primary_down()) {
|
||||
ui.data_mut(|d| d.remove::<(Option<u64>, bool)>(drag_id));
|
||||
end_ruler_origin_drag(app, ui);
|
||||
} else {
|
||||
ui.data_mut(|d| d.insert_temp(drag_id, (started_in, cancelled)));
|
||||
if !cancelled {
|
||||
@@ -295,6 +304,21 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
|
||||
preview
|
||||
}
|
||||
|
||||
/// The rulers are hidden (View › Rulers, Presentation Mode): a drag of their origin they were
|
||||
/// showing for is cancelled, so its snapping guides don't stay on the canvas. Nothing previews.
|
||||
pub(super) fn rulers_hidden(app: &mut VectorcraftApp, ui: &Ui) -> Option<Point> {
|
||||
if ruler_origin_dragging(ui.ctx()) {
|
||||
end_ruler_origin_drag(app, ui);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Ends a drag from the rulers' corner, released or cancelled: its state and its snapping guides go.
|
||||
fn end_ruler_origin_drag(app: &mut VectorcraftApp, ui: &Ui) {
|
||||
ui.data_mut(|d| d.remove::<(Option<u64>, bool)>(ruler_origin_drag_id()));
|
||||
app.session.end_ruler_origin_drag();
|
||||
}
|
||||
|
||||
/// The key of the ruler origin drag's state in egui's temporary data.
|
||||
fn ruler_origin_drag_id() -> egui::Id {
|
||||
egui::Id::unique("ruler-origin-drag")
|
||||
|
||||
@@ -6983,6 +6983,49 @@ fn a_brush_dropped_on_a_path_is_applied_to_it() {
|
||||
assert_eq!(brush(&app).as_deref(), Some("Arrow"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.session.execute("path.create", &json!({"anchors": [{"x": 100, "y": 150}, {"x": 300, "y": 150}]})).unwrap();
|
||||
app.session.execute("select.none", &json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let drop = |app: &mut VectorcraftApp, name: &str, at: Point| {
|
||||
let def = app.session.execute("brush.get", &json!({"name": name})).unwrap();
|
||||
let at = xf.to_screen(at);
|
||||
egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Brush { name: name.into(), def });
|
||||
let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };
|
||||
frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]);
|
||||
};
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
// A calligraphic brush has no art: nothing.
|
||||
drop(&mut app, "3 pt. Round", Point::new(200.0, 250.0));
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
// An art brush: a copy of its art, centered where it lands, selected.
|
||||
drop(&mut app, "Arrow", Point::new(200.0, 250.0));
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.history.undo.len(), undo + 1);
|
||||
assert_eq!(st.history.undo.last().unwrap().label, "Place Brush Art");
|
||||
let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) };
|
||||
let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap();
|
||||
assert!((b.center() - Point::new(200.0, 250.0)).hypot() < 0.1, "{b:?}");
|
||||
// A scatter brush and a pattern brush (its tiles, in one group) place their art too.
|
||||
for (i, name) in ["Dots", "Chain"].into_iter().enumerate() {
|
||||
let at = Point::new(80.0 + 200.0 * i as f64, 60.0);
|
||||
drop(&mut app, name, at);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.history.undo.len(), undo + 2 + i, "{name}");
|
||||
let [placed] = st.selection.objects.as_slice() else { panic!("{name}: one object selected: {:?}", st.selection.objects) };
|
||||
let n = st.doc.node(*placed).unwrap();
|
||||
assert!((n.geometric_bounds().unwrap().center() - at).hypot() < 0.1, "{name}");
|
||||
if name == "Chain" {
|
||||
assert_eq!(n.children().unwrap()[0].name.as_deref(), Some("Side Tile"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
|
||||
@@ -248,8 +248,9 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) {
|
||||
/// Most notes the status message's hover and access information list.
|
||||
const MAX_LISTED_NOTES: usize = 30;
|
||||
|
||||
/// The notes behind the status message (the open's, [`crate::state::UiState::status_notes`]) when
|
||||
/// there are several and the status bar still shows the message they came with, else none.
|
||||
/// The notes behind the status message (an open's, a save's or an export's,
|
||||
/// [`crate::state::UiState::status_notes`]) when there are several and the status bar still shows
|
||||
/// the message they came with, else none.
|
||||
fn status_notes(ui: &crate::state::UiState) -> &[String] {
|
||||
let notes = ui.status_notes.as_ref().filter(|(status, notes)| *status == ui.status && notes.len() > 1);
|
||||
notes.map(|(_, notes)| notes.as_slice()).unwrap_or_default()
|
||||
|
||||
+111
-40
@@ -474,9 +474,24 @@ fn key_from(name: &str) -> Option<egui::Key> {
|
||||
|
||||
/// The modifier keys a request holds down (`cmd`, `ctrl`, `alt`, `shift`; `cmd` is Command on
|
||||
/// macOS, Ctrl elsewhere).
|
||||
fn modifiers(p: &Value) -> egui::Modifiers {
|
||||
let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false);
|
||||
egui::Modifiers { alt: b("alt"), ctrl: b("ctrl"), shift: b("shift"), mac_cmd: b("cmd") && cfg!(target_os = "macos"), command: b("cmd") }
|
||||
fn modifiers(p: &Value) -> Result<egui::Modifiers, String> {
|
||||
let b = |n: &str| crate::menus::opt_bool(p, n).map(|on| on.unwrap_or(false));
|
||||
let cmd = b("cmd")?;
|
||||
Ok(egui::Modifiers { alt: b("alt")?, ctrl: b("ctrl")?, shift: b("shift")?, mac_cmd: cmd && cfg!(target_os = "macos"), command: cmd })
|
||||
}
|
||||
|
||||
/// An optional number param of a control request as `f32`, `default` when it is omitted or null.
|
||||
fn coord(p: &Value, key: &str, default: f32) -> Result<f32, String> {
|
||||
crate::menus::opt_number(p, key).map(|n| n.map_or(default, |n| n as f32))
|
||||
}
|
||||
|
||||
/// A pointer packet's `mods`: none when omitted or null, else an object of booleans.
|
||||
fn packet_mods(value: Option<&Value>) -> Result<Option<Mods>, String> {
|
||||
match value {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(m) if !m.is_object() => Err("`mods` must be an object of true or false values".to_string()),
|
||||
Some(m) => serde_json::from_value(m.clone()).map(Some).map_err(|e| format!("`mods` must be an object of true or false values: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
|
||||
@@ -512,10 +527,13 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
"ui.pointer" => pointer_events(app, ctx, req),
|
||||
"ui.key" => {
|
||||
let Some(k) = s("key").and_then(key_from) else { return err("unknown or missing `key`") };
|
||||
let m = match modifiers(p) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
if let Err(e) = reserve_synthetic(app, 2 + usize::from(s("text").is_some())) {
|
||||
return err(e);
|
||||
}
|
||||
let m = modifiers(p);
|
||||
app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m });
|
||||
// Typed text comes with the press, so it shares the key's frame and modifiers.
|
||||
if let Some(t) = s("text") {
|
||||
@@ -526,31 +544,39 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
ok(Value::Null)
|
||||
}
|
||||
"ui.move" => {
|
||||
let pos = match coord(p, "x", 0.0).and_then(|x| Ok(egui::pos2(x, coord(p, "y", 0.0)?))) {
|
||||
Ok(pos) => pos,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
if let Err(e) = reserve_synthetic(app, 1) {
|
||||
return err(e);
|
||||
}
|
||||
let pos = egui::pos2(p.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32, p.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32);
|
||||
app.synthetic.push(egui::Event::PointerMoved(pos));
|
||||
ctx.request_repaint();
|
||||
ok(Value::Null)
|
||||
}
|
||||
"ui.click" | "ui.drag" => synthetic_click(app, ctx, req),
|
||||
"ui.wheel" => {
|
||||
// Mouse wheel notches over screen point (x, y): `dy` up (+) or down, `dx` sideways
|
||||
// (`unit: "point"` for trackpad-like points), with modifiers as `ui.click` takes them.
|
||||
let given =
|
||||
(|| Ok::<_, String>(([coord(p, "dx", 0.0)?, coord(p, "dy", 0.0)?, coord(p, "x", 0.0)?, coord(p, "y", 0.0)?], modifiers(p)?)))();
|
||||
let ([dx, dy, x, y], modifiers) = match given {
|
||||
Ok(given) => given,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
if let Err(e) = reserve_synthetic(app, 2) {
|
||||
return err(e);
|
||||
}
|
||||
// Mouse wheel notches over screen point (x, y): `dy` up (+) or down, `dx` sideways
|
||||
// (`unit: "point"` for trackpad-like points), with modifiers as `ui.click` takes them.
|
||||
let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;
|
||||
let unit = if s("unit") == Some("point") { egui::MouseWheelUnit::Point } else { egui::MouseWheelUnit::Line };
|
||||
// Notches, not a flood: a turn stays within what a real wheel sends.
|
||||
let delta = egui::vec2(f("dx"), f("dy")).clamp(egui::Vec2::splat(-100.0), egui::Vec2::splat(100.0));
|
||||
app.synthetic.push(egui::Event::PointerMoved(egui::pos2(f("x"), f("y"))));
|
||||
let delta = egui::vec2(dx, dy).clamp(egui::Vec2::splat(-100.0), egui::Vec2::splat(100.0));
|
||||
app.synthetic.push(egui::Event::PointerMoved(egui::pos2(x, y)));
|
||||
app.synthetic.push(egui::Event::MouseWheel {
|
||||
unit,
|
||||
delta,
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: modifiers(p),
|
||||
modifiers,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
});
|
||||
ctx.request_repaint();
|
||||
@@ -615,8 +641,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
ok(Value::Null)
|
||||
}
|
||||
"ui.resize" => {
|
||||
let w = p.get("width").and_then(Value::as_f64).unwrap_or(1440.0) as f32;
|
||||
let h = p.get("height").and_then(Value::as_f64).unwrap_or(900.0) as f32;
|
||||
let (w, h) = match coord(p, "width", 1440.0).and_then(|w| Ok((w, coord(p, "height", 900.0)?))) {
|
||||
Ok(size) => size,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w, h)));
|
||||
ok(Value::Null)
|
||||
}
|
||||
@@ -629,32 +657,48 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
if let Some(Err(e)) = s("path").map(vectorcraft_engine::file_access::check_write) {
|
||||
return err(e);
|
||||
}
|
||||
if p.get("focus").and_then(Value::as_bool).unwrap_or(true) {
|
||||
let flags = crate::menus::opt_bool(p, "focus").and_then(|focus| Ok((focus, crate::menus::opt_bool(p, "data")?)));
|
||||
let (focus, data) = match flags {
|
||||
Ok(flags) => flags,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
if focus.unwrap_or(true) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
||||
}
|
||||
ctx.request_repaint();
|
||||
Outcome::Screenshot { path: s("path").map(str::to_string), data: p.get("data").and_then(Value::as_bool) == Some(true) }
|
||||
Outcome::Screenshot { path: s("path").map(str::to_string), data: data == Some(true) }
|
||||
}
|
||||
"ui.render" => {
|
||||
let given = (|| {
|
||||
Ok::<_, String>((
|
||||
crate::menus::opt_index(p, "artboard")?,
|
||||
crate::menus::opt_number(p, "scale")?,
|
||||
crate::menus::opt_bool(p, "traceViews")?,
|
||||
crate::menus::opt_bool(p, "data")?,
|
||||
))
|
||||
})();
|
||||
let (index, scale, trace_views, data) = match given {
|
||||
Ok(given) => given,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
let Some(st) = app.session.active() else { return err("no document") };
|
||||
let doc = st.doc.clone();
|
||||
// The artboard asked for (0-based, as headless), else the first.
|
||||
let index = p.get("artboard").and_then(Value::as_u64).map_or(Some(0), |i| usize::try_from(i).ok());
|
||||
let Some(r) = index.and_then(|i| doc.artboards.get(i)).map(|a| a.rect) else { return err("no such artboard") };
|
||||
let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0);
|
||||
let Some(r) = doc.artboards.get(index.unwrap_or(0)).map(|a| a.rect) else { return err("no such artboard") };
|
||||
let scale = scale.unwrap_or(1.0);
|
||||
if let Err(e) = vectorcraft_render::raster_size(r, scale) {
|
||||
return err(e);
|
||||
}
|
||||
// Rendered with the options of a PNG export on white, so its pixels are the exported file's.
|
||||
// `traceViews: true` draws Image Trace objects as their View shows them, as the canvas does.
|
||||
let mut opts = RasterExportOptions { background: Some([255; 3]), ..Default::default() }.render_options(RasterFormat::Png);
|
||||
opts.trace_views = p.get("traceViews").and_then(Value::as_bool) == Some(true);
|
||||
opts.trace_views = trace_views == Some(true);
|
||||
let img = app.canvas.renderer.render_region_with(&doc, r, scale, &opts);
|
||||
let png = match img.to_png() {
|
||||
Ok(png) => png,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
let data = p.get("data").and_then(Value::as_bool) == Some(true);
|
||||
let data = data == Some(true);
|
||||
match s("path") {
|
||||
Some(path) => match app.services.write.as_mut() {
|
||||
Some(w) => wrap(
|
||||
@@ -857,7 +901,7 @@ fn rotate_view_pointer(
|
||||
|
||||
/// A Rotate View packet accepts only the documented boolean modifier fields.
|
||||
fn validate_rotate_view_mods(value: Option<&Value>) -> Result<(), String> {
|
||||
let Some(value) = value else { return Ok(()) };
|
||||
let Some(value) = value.filter(|value| !value.is_null()) else { return Ok(()) };
|
||||
let Some(fields) = value.as_object() else { return Err("Rotate View `mods` must be an object of booleans".into()) };
|
||||
if fields.iter().any(|(key, value)| !matches!(key.as_str(), "shift" | "alt" | "cmd" | "ctrl" | "space") || !value.is_boolean()) {
|
||||
return Err("Rotate View `mods` accepts only boolean shift, alt, cmd, ctrl and space".into());
|
||||
@@ -906,9 +950,36 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con
|
||||
if rotating && let Err(error) = validate_rotate_view_events(p, events) {
|
||||
return err(error);
|
||||
}
|
||||
let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default();
|
||||
// Every event is read before any is sent, so a malformed packet sends none of them.
|
||||
let read = packet_mods(p.get("mods")).and_then(|base| {
|
||||
let base = base.unwrap_or_default();
|
||||
events
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") {
|
||||
"down" => PointerKind::Down,
|
||||
"drag" => PointerKind::Drag,
|
||||
"up" => PointerKind::Up,
|
||||
"move" => PointerKind::Move,
|
||||
"doubleclick" | "dblclick" => PointerKind::DoubleClick,
|
||||
other => return Err(format!("unknown pointer kind `{other}`")),
|
||||
};
|
||||
PointerEvent::json_check(e)?;
|
||||
let at = |k: &str| crate::menus::opt_number(e, k).map(|n| n.unwrap_or(0.0));
|
||||
Ok((kind, at("x")?, at("y")?, packet_mods(e.get("mods"))?.unwrap_or(base)))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()
|
||||
});
|
||||
let read = match read {
|
||||
Ok(read) => read,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
let view = app.view_info();
|
||||
let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v));
|
||||
let screen = |e: &Value| e.get("space").and_then(Value::as_str) == Some("screen");
|
||||
if !rotating && xf.is_none() && events.iter().any(screen) {
|
||||
return err("no canvas yet");
|
||||
}
|
||||
let from = app.session.input_count();
|
||||
let held =
|
||||
PointerEvent::json_backquote(p, false).and_then(|d| events.iter().map(|e| PointerEvent::json_backquote(e, d)).collect::<Result<Vec<_>, _>>());
|
||||
@@ -916,19 +987,8 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con
|
||||
Ok(held) => held,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
for (e, backquote) in events.iter().zip(held) {
|
||||
let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") {
|
||||
"down" => PointerKind::Down,
|
||||
"drag" => PointerKind::Drag,
|
||||
"up" => PointerKind::Up,
|
||||
"move" => PointerKind::Move,
|
||||
"doubleclick" | "dblclick" => PointerKind::DoubleClick,
|
||||
other => return err(format!("unknown pointer kind `{other}`")),
|
||||
};
|
||||
let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.0);
|
||||
let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.0);
|
||||
let screen = e.get("space").and_then(Value::as_str) == Some("screen");
|
||||
let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods);
|
||||
for ((e, backquote), (kind, x, y, mods)) in events.iter().zip(held).zip(read) {
|
||||
let screen = screen(e);
|
||||
if rotating {
|
||||
if let Err(e) = rotate_view_pointer(app, kind, vectorcraft_geom::Point::new(x, y), screen, mods.shift) {
|
||||
return err(e);
|
||||
@@ -987,18 +1047,24 @@ fn synthetic_click(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlR
|
||||
let Some(events) = count.checked_mul(2).and_then(|n| n.checked_add(steps)).and_then(|n| n.checked_add(1)) else {
|
||||
return err("synthetic input event count is out of range");
|
||||
};
|
||||
// Screen-space (egui points) pointer input through egui itself: reaches every widget.
|
||||
let drag = req.method == "ui.drag";
|
||||
let given = (|| {
|
||||
let a = egui::pos2(coord(p, "x", 0.0)?, coord(p, "y", 0.0)?);
|
||||
let end = if drag { egui::pos2(coord(p, "toX", 0.0)?, coord(p, "toY", 0.0)?) } else { a };
|
||||
Ok::<_, String>((a, end, modifiers(p)?))
|
||||
})();
|
||||
let (a, end, modifiers) = match given {
|
||||
Ok(given) => given,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
if let Err(e) = reserve_synthetic(app, events) {
|
||||
return err(e);
|
||||
}
|
||||
// Screen-space (egui points) pointer input through egui itself: reaches every widget.
|
||||
let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;
|
||||
let button = match s("button") {
|
||||
Some("right") | Some("secondary") => egui::PointerButton::Secondary,
|
||||
_ => egui::PointerButton::Primary,
|
||||
};
|
||||
let modifiers = modifiers(p);
|
||||
let a = egui::pos2(f("x"), f("y"));
|
||||
let end = if req.method == "ui.drag" { egui::pos2(f("toX"), f("toY")) } else { a };
|
||||
app.synthetic.push(egui::Event::PointerMoved(a));
|
||||
app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers });
|
||||
if req.method == "ui.drag" {
|
||||
@@ -1020,6 +1086,11 @@ fn synthetic_click(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlR
|
||||
fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome {
|
||||
let p = &req.params;
|
||||
let s = |k: &str| p.get(k).and_then(Value::as_str);
|
||||
// A flag of the wrong type is refused before anything is set.
|
||||
let flags = ["rulers", "outline", "grid", "smartGuides", "boundingBox", "controlBar", "imageTracePreview"];
|
||||
if let Some(e) = flags.iter().find_map(|k| crate::menus::opt_bool(p, k).err()) {
|
||||
return err(e);
|
||||
}
|
||||
// Outline is a setting of the active document's view: without one, nothing is set.
|
||||
if p.get("outline").is_some_and(Value::is_boolean) && app.session.active().is_none() {
|
||||
return err("no document");
|
||||
|
||||
@@ -314,6 +314,93 @@ fn render_takes_the_artboard_asked_for() {
|
||||
assert_eq!(got, size.map(Some), "{params}: {r}");
|
||||
}
|
||||
assert!(request("ui.render", json!({"artboard": 2}))["error"].is_string());
|
||||
for (params, key) in [
|
||||
(json!({"artboard": "1"}), "artboard"),
|
||||
(json!({"artboard": -1}), "artboard"),
|
||||
(json!({"scale": "0.5"}), "scale"),
|
||||
(json!({"traceViews": 1}), "traceViews"),
|
||||
(json!({"data": "yes"}), "data"),
|
||||
] {
|
||||
let r = request("ui.render", params.clone());
|
||||
assert!(r["error"].as_str().is_some_and(|e| e.contains(&format!("`{key}`"))), "{params}: {r}");
|
||||
}
|
||||
let r = request("ui.render", json!({"artboard": null, "scale": null}));
|
||||
assert_eq!([&r["result"]["width"], &r["result"]["height"]].map(Value::as_u64), [Some(64), Some(64)], "null keeps the default: {r}");
|
||||
}
|
||||
|
||||
/// The control channel's input methods refuse a number or switch of the wrong type before they
|
||||
/// queue any event; omitting it keeps its default.
|
||||
#[test]
|
||||
fn control_input_refuses_params_of_the_wrong_type() {
|
||||
let move_to = |mods: Value| json!({"events": [{"kind": "move", "x": 5, "y": 5}, {"kind": "move", "x": 6, "y": 6, "mods": mods}]});
|
||||
for (method, params, key) in [
|
||||
("ui.move", json!({"x": "10"}), "x"),
|
||||
("ui.move", json!({"y": true}), "y"),
|
||||
("ui.wheel", json!({"dy": "1"}), "dy"),
|
||||
("ui.wheel", json!({"dy": 1, "shift": "yes"}), "shift"),
|
||||
("ui.click", json!({"x": [1]}), "x"),
|
||||
("ui.click", json!({"cmd": 1}), "cmd"),
|
||||
("ui.drag", json!({"toX": "5"}), "toX"),
|
||||
("ui.key", json!({"key": "Enter", "alt": "true"}), "alt"),
|
||||
("ui.resize", json!({"width": "800"}), "width"),
|
||||
("ui.screenshot", json!({"focus": "no"}), "focus"),
|
||||
("ui.screenshot", json!({"data": 1}), "data"),
|
||||
("ui.set", json!({"rulers": "true"}), "rulers"),
|
||||
("ui.set", json!({"grid": true, "controlBar": 0}), "controlBar"),
|
||||
("ui.pointer", json!({"events": [{"kind": "move", "x": "5", "y": 0}]}), "x"),
|
||||
("ui.pointer", move_to(json!({"shift": "yes"})), "mods"),
|
||||
("ui.pointer", move_to(json!([true])), "mods"),
|
||||
("ui.pointer", json!({"mods": "shift", "events": [{"kind": "move", "x": 1, "y": 1}]}), "mods"),
|
||||
] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
app.synthetic.push(egui::Event::Text("pending".into()));
|
||||
let before = (format!("{:?}", app.synthetic), app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar);
|
||||
let r = input_request(&mut app, method, params.clone());
|
||||
assert_eq!(r["ok"], false, "{method} {params}: {r}");
|
||||
assert!(r["error"].as_str().is_some_and(|e| e.contains(&format!("`{key}`"))), "{method} {params}: {r}");
|
||||
let after = (format!("{:?}", app.synthetic), app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar);
|
||||
assert_eq!(after, before, "{method} {params}: nothing is queued or set");
|
||||
}
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
assert_eq!(input_request(&mut app, "ui.move", json!({"x": null, "y": 4}))["ok"], true);
|
||||
assert!(matches!(app.synthetic.first(), Some(egui::Event::PointerMoved(p)) if *p == egui::pos2(0.0, 4.0)));
|
||||
}
|
||||
|
||||
/// The app's own commands refuse a param of the wrong type and change nothing; omitting it or
|
||||
/// giving null keeps its default.
|
||||
#[test]
|
||||
fn ui_commands_refuse_params_of_the_wrong_type() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.run("view.setZoom", json!({"zoom": 300, "center": [5, 5]})).unwrap();
|
||||
let view = |app: &VectorcraftApp| app.view().map(|v| (v.zoom, v.center.x, v.center.y));
|
||||
let before = (view(&app), app.ui.screen_mode, app.session.documents().len(), app.ui.dialog.is_some(), app.ui.open_panel.clone());
|
||||
for (id, params, key) in [
|
||||
("view.setZoom", json!({"zoom": "200"}), "zoom"),
|
||||
("view.setZoom", json!({"zoom": 200, "center": [1]}), "center"),
|
||||
("view.setZoom", json!({"zoom": 200, "center": "0,0"}), "center"),
|
||||
("view.screenMode", json!({"mode": "2"}), "mode"),
|
||||
("view.screenMode", json!({"mode": 1.5}), "mode"),
|
||||
("window.panel", json!({"panel": "layers", "toggle": "true"}), "toggle"),
|
||||
("window.panel", json!({"panel": "layers", "toggle": true, "toggleGroup": 1}), "toggleGroup"),
|
||||
("file.revert", json!({"confirmed": "yes"}), "confirmed"),
|
||||
("file.close", json!({"index": "0"}), "index"),
|
||||
("ui.newSwatch", json!({"spot": "true"}), "spot"),
|
||||
("ui.newSwatch", json!({"global": 1}), "global"),
|
||||
("ui.symbolOptions", json!({"edit": 1}), "edit"),
|
||||
("ui.batchDialog", json!({"set": "1"}), "set"),
|
||||
("ui.batchDialog", json!({"action": -1}), "action"),
|
||||
("file.exportSelection", json!({"multiple": "true"}), "multiple"),
|
||||
] {
|
||||
let e = app.run(id, params.clone()).unwrap_err();
|
||||
assert!(e.contains(&format!("`{key}`")), "{id} {params}: {e}");
|
||||
let after = (view(&app), app.ui.screen_mode, app.session.documents().len(), app.ui.dialog.is_some(), app.ui.open_panel.clone());
|
||||
assert_eq!(after, before, "{id} {params}: nothing changes");
|
||||
}
|
||||
app.run("view.setZoom", json!({"zoom": null, "center": null})).unwrap();
|
||||
assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.session.prefs.display_print_size)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -370,6 +457,35 @@ fn synthetic_pointer_rejects_a_backquote_that_is_not_a_boolean() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.pointer` refuses an unknown event kind, a pen value or `space` of the wrong type, or a
|
||||
/// screen-space event with no canvas, before any of the packet's events runs.
|
||||
#[test]
|
||||
fn synthetic_pointer_rejects_an_unknown_kind_before_any_event_runs() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
assert_eq!(input_request(&mut app, "ui.tool.select", json!({"tool": "selection"}))["ok"], true);
|
||||
let before = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone();
|
||||
let moves = [json!({"kind": "down", "x": 125, "y": 125}), json!({"kind": "drag", "x": 145, "y": 125}), json!({"kind": "up", "x": 145, "y": 125})];
|
||||
for (last, error) in [
|
||||
(json!({"kind": "wiggle", "x": 145, "y": 125}), "unknown pointer kind `wiggle`"),
|
||||
(json!({"kind": "move", "x": 145, "y": 125, "space": "screen"}), "no canvas yet"),
|
||||
(json!({"kind": "move", "x": 145, "y": 125, "pressure": "bad"}), "`pressure` must be a number"),
|
||||
(json!({"kind": "move", "x": 145, "y": 125, "holdMs": "800"}), "`holdMs` must be a number"),
|
||||
(json!({"kind": "move", "x": 145, "y": 125, "tiltY": true}), "`tiltY` must be a number"),
|
||||
(json!({"kind": "move", "x": 145, "y": 125, "rotation": "90"}), "`rotation` must be a number"),
|
||||
(json!({"kind": "move", "x": 145, "y": 125, "space": "screeen"}), "`space` must be doc or screen"),
|
||||
(json!({"kind": "move", "x": 145, "y": 125, "space": true}), "`space` must be doc or screen"),
|
||||
] {
|
||||
let events = moves.iter().cloned().chain([last]).collect::<Vec<_>>();
|
||||
let r = input_request(&mut app, "ui.pointer", json!({"events": events}));
|
||||
assert_eq!(r["ok"], false, "{error}: {r}");
|
||||
assert!(r["error"].as_str().is_some_and(|e| e.contains(error)), "{r}");
|
||||
assert_eq!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(), &before, "{error}: the drag does not run");
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.pointer` replies with the key object: a click on one of two selected objects makes it
|
||||
/// the key, and a click on the key again lets it go.
|
||||
#[test]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! DXF Options (Export As → DXF): a preset (Custom, or CNC / CAM, which sets the options below for
|
||||
//! cutting software and shows Custom again once one is changed), version, scale (1 unit of the
|
||||
//! art = N drawing units) and lineweights, number of colours, the format of placed images,
|
||||
//! Preserve Appearance or Maximize Editability, and Export Selected Art Only, Alter Paths for
|
||||
//! Appearance and Outline Text.
|
||||
//! art = N drawing units) and lineweights, number of colours, the format of placed images and
|
||||
//! Include Placed Images, Preserve Appearance or Maximize Editability, and Export Selected Art
|
||||
//! Only, Alter Paths for Appearance, Outline Text and Include Fill Hatches.
|
||||
//!
|
||||
//! Fields: `document.export` params (`format: dxf`, `path?`, the artboard choice) and the DXF
|
||||
//! options of `document.exportDxf`. OK remembers the options for next time and writes the file
|
||||
@@ -58,6 +58,8 @@ fn preset_fields(preset: DxfPreset) -> Map<String, Value> {
|
||||
("scaleLineweights", json!(o.scale_lineweights)),
|
||||
("colors", json!(o.colors.id())),
|
||||
("rasterFormat", json!(o.raster.id())),
|
||||
("includeImages", json!(o.include_images)),
|
||||
("includeHatches", json!(o.include_hatches)),
|
||||
("preserve", json!(o.preserve.id())),
|
||||
("alterPaths", json!(o.alter_paths)),
|
||||
("outlineText", json!(o.outline_text)),
|
||||
@@ -140,6 +142,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
let rasters: Vec<(&str, &str)> = RasterFormat::ALL.iter().map(|r| (r.id(), r.label())).collect();
|
||||
choice(ui, d, "rasterFormat", tl!("Raster File Format:"), &rasters);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(LABEL + 8.0);
|
||||
check(ui, d, "includeImages", tl!("Include Placed Images"));
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
widgets::subheader(ui, tl!("Export Option"));
|
||||
let preserve = Preserve::from_id(&d.str("preserve")).unwrap_or_default();
|
||||
@@ -162,6 +168,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
if widgets::check(ui, tl!("Outline Text"), appearance || d.bool("outlineText"), !appearance) {
|
||||
d.fields.insert("outlineText".into(), json!(!d.bool("outlineText")));
|
||||
}
|
||||
check(ui, d, "includeHatches", tl!("Include Fill Hatches"));
|
||||
ui.add_space(8.0);
|
||||
super::form::caption(
|
||||
ui,
|
||||
|
||||
@@ -784,8 +784,7 @@ fn save_preset_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
|
||||
/// ones → the names added
|
||||
/// (none on the web, where the picked file arrives later and imports through `io::open_bytes`).
|
||||
pub(crate) fn import_presets(app: &mut VectorcraftApp) -> Result<Vec<String>, String> {
|
||||
if let Some(f) = app.services.open_async.as_mut() {
|
||||
f();
|
||||
if crate::picks::open_async(app) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS)], ..Default::default() };
|
||||
|
||||
@@ -197,8 +197,7 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) ->
|
||||
}
|
||||
Action::Import => {
|
||||
// On the web the picked file arrives later and imports through `io::open_bytes`.
|
||||
if let Some(f) = app.services.open_async.as_mut() {
|
||||
f();
|
||||
if crate::picks::open_async(app) {
|
||||
return Ok(());
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Flattener presets", PRESET_EXTS)], ..Default::default() };
|
||||
|
||||
@@ -40,6 +40,7 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result<Value
|
||||
fields.insert("section".into(), json!("general"));
|
||||
let attrs = target.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
fields.extend(super::para_style_options::form_fields(&attrs, app.session.general_unit()));
|
||||
fields.insert("__vertical".into(), json!(super::para_style_options::vertical_text(app)));
|
||||
} else {
|
||||
fields.insert("section".into(), json!("general"));
|
||||
fields.insert("__smallCapsSize".into(), json!(d.setup.small_caps_size));
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
//! Paragraph Style Options fields shared by editing and creating a paragraph style: General, Basic
|
||||
//! Paragraph Formats (alignment, indents and spacing), Composition (composer and Roman Hanging
|
||||
//! Punctuation), Hyphenation and Justification.
|
||||
//! Paragraph Formats (alignment, indents and spacing), Tabs (the style's tab stops), Composition
|
||||
//! (composer and Roman Hanging Punctuation), Hyphenation and Justification.
|
||||
//!
|
||||
//! Each field is unset (empty, or a checkbox in its unset state) or set, and an unset field leaves
|
||||
//! its attribute out of the style. Distances are shown and typed in the General unit and kept in
|
||||
//! points. The Hyphenation and Justification options are one attribute each (`hyphenation`,
|
||||
//! `justification`): when any of their fields is set, a field left empty takes its default value.
|
||||
//! A field still as it opened keeps the style's stored value as it is.
|
||||
//! The `tabs` field is unset (null) or a list of stops, an empty list included, and is the `tabs`
|
||||
//! attribute. A field still as it opened keeps the style's stored value as it is.
|
||||
//!
|
||||
//! Behavior reference (public documentation):
|
||||
//! <https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html>.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{HyphenationOptions, JustificationOptions, Unit};
|
||||
use vectorcraft_doc::text::DEFAULT_TAB_INTERVAL;
|
||||
use vectorcraft_doc::{HyphenationOptions, JustificationOptions, TabAlign, TabStop, Unit};
|
||||
|
||||
use super::{DialogSpec, form};
|
||||
use crate::VectorcraftApp;
|
||||
@@ -21,7 +23,11 @@ use crate::state::Dialog;
|
||||
pub const KIND: &str = "paraStyleOptions";
|
||||
|
||||
/// The section ids, in the order the section list shows them.
|
||||
pub(crate) const SECTIONS: [&str; 5] = ["general", "basic", "composition", "hyphenation", "justification"];
|
||||
pub(crate) const SECTIONS: [&str; 6] = ["general", "basic", "tabs", "composition", "hyphenation", "justification"];
|
||||
/// The alignments of a tab stop with the names the `tabs` field gives them, in the Tabs panel's
|
||||
/// order.
|
||||
const TAB_ALIGNS: [(TabAlign, &str); 4] =
|
||||
[(TabAlign::Left, "left"), (TabAlign::Center, "center"), (TabAlign::Right, "right"), (TabAlign::Decimal, "decimal")];
|
||||
/// The distance fields of Basic Paragraph Formats, which are also the attributes they set.
|
||||
const DISTANCES: [&str; 5] = ["left_indent", "right_indent", "first_line_indent", "space_before", "space_after"];
|
||||
/// The range of the indents, the space before and after, and the Hyphenation Zone (pt), as
|
||||
@@ -98,6 +104,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
"glyph_max",
|
||||
"auto_leading",
|
||||
"single_word",
|
||||
"tabs",
|
||||
"section",
|
||||
]
|
||||
},
|
||||
@@ -112,6 +119,7 @@ pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> {
|
||||
let doc = &app.session.active().ok_or("no document open")?.doc;
|
||||
let def = doc.para_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no style `{name}`"))?;
|
||||
let mut fields = form_fields(&def.attrs, unit);
|
||||
fields.insert("__vertical".into(), json!(vertical_text(app)));
|
||||
fields.insert("name".into(), json!(name));
|
||||
fields.insert("__style".into(), json!(name));
|
||||
fields.insert("section".into(), json!("general"));
|
||||
@@ -129,6 +137,76 @@ pub(crate) fn form_fields(attrs: &Map<String, Value>, unit: Unit) -> Map<String,
|
||||
fields
|
||||
}
|
||||
|
||||
/// Whether the first selected text is vertical type, where the Tabs section names a stop's
|
||||
/// position Y and its Left and Right alignments Top and Bottom.
|
||||
pub(crate) fn vertical_text(app: &VectorcraftApp) -> bool {
|
||||
crate::panels::character::first_selected_text(app).is_some_and(|t| t.vertical)
|
||||
}
|
||||
|
||||
/// The `tabs` field for a style's `tabs` attribute: unset (null) when the style leaves it out,
|
||||
/// otherwise one entry per stop ([`stop_field`]).
|
||||
fn tabs_field(value: Option<&Value>, unit: Unit) -> Value {
|
||||
let Some(stops) = value.and_then(Value::as_array) else { return Value::Null };
|
||||
Value::Array(stops.iter().filter_map(|s| serde_json::from_value::<TabStop>(s.clone()).ok()).map(|s| stop_field(&s, unit)).collect())
|
||||
}
|
||||
|
||||
/// A tab stop's entry in the `tabs` field: its position as text in `unit`, its alignment, leader
|
||||
/// and Align On character, and the position in points it shows (`__pt`), which a position still as
|
||||
/// it shows keeps exactly.
|
||||
fn stop_field(s: &TabStop, unit: Unit) -> Value {
|
||||
let align = TAB_ALIGNS.iter().find(|(a, _)| *a == s.align).map_or("left", |(_, key)| *key);
|
||||
json!({"position": unit.format(s.position), "align": align, "leader": s.leader, "alignOn": s.align_on.to_string(), "__pt": s.position})
|
||||
}
|
||||
|
||||
/// The position in points of a `tabs` entry: its `__pt` while its text is as that shows in `unit`,
|
||||
/// else the text read in `unit`; `None` when the text is not a distance.
|
||||
fn stop_position(row: &Value, unit: Unit) -> Option<f64> {
|
||||
let text = row.get("position").and_then(Value::as_str).map_or("", str::trim);
|
||||
row.get("__pt").and_then(Value::as_f64).filter(|pt| pt.is_finite() && unit.format(*pt) == text).or_else(|| unit.parse(text))
|
||||
}
|
||||
|
||||
/// The tab stop a `tabs` entry sets, or why it sets none: its position must be a distance from 0 to
|
||||
/// 100000 pt (`label` names the field), its alignment one of [`TAB_ALIGNS`], its leader text of at
|
||||
/// most eight characters and its Align On character one character. A leader or Align On character
|
||||
/// left out is none or a period.
|
||||
fn read_stop(row: &Value, unit: Unit, label: &str) -> Result<TabStop, String> {
|
||||
let position = stop_position(row, unit).ok_or_else(|| format!("{label} must be a number"))?;
|
||||
if !(0.0..=TabStop::MAX_POSITION).contains(&position) {
|
||||
let (min, max) = (unit.format(0.0), unit.format(TabStop::MAX_POSITION));
|
||||
return Err(format!("{label} must be a number from {min} to {max}"));
|
||||
}
|
||||
let other = match row.get("align") {
|
||||
None | Some(Value::Null) => "left",
|
||||
Some(v) => v.as_str().unwrap_or(""),
|
||||
};
|
||||
let align = TAB_ALIGNS.iter().find(|(_, key)| *key == other).map(|(a, _)| *a).ok_or_else(|| format!("unknown align `{other}`"))?;
|
||||
let leader = match row.get("leader") {
|
||||
None | Some(Value::Null) => "",
|
||||
Some(Value::String(s)) => s.as_str(),
|
||||
Some(_) => {
|
||||
let key = "leader";
|
||||
return Err(format!("`{key}` must be a string"));
|
||||
}
|
||||
};
|
||||
let (label, max) = (caption(tl!("Leader:")), TabStop::MAX_LEADER);
|
||||
if leader.chars().count() > max {
|
||||
return Err(format!("{label} must be at most {max} characters"));
|
||||
}
|
||||
let label = caption(tl!("Align On:"));
|
||||
let align_on = match row.get("alignOn") {
|
||||
None | Some(Value::Null) => '.',
|
||||
Some(Value::String(s)) => {
|
||||
let mut chars = s.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(c), None) => c,
|
||||
_ => return Err(format!("{label} must be one character")),
|
||||
}
|
||||
}
|
||||
Some(_) => return Err(format!("{label} must be one character")),
|
||||
};
|
||||
Ok(TabStop { position, align, leader: leader.into(), align_on })
|
||||
}
|
||||
|
||||
/// A distance in points as its field shows it in `unit`.
|
||||
fn distance_field(value: Option<&Value>, unit: Unit) -> Value {
|
||||
value.and_then(Value::as_f64).map_or_else(|| json!(""), |pt| json!(unit.format(pt)))
|
||||
@@ -174,6 +252,7 @@ pub(crate) fn fields_from_attrs(attrs: &Map<String, Value>, unit: Unit) -> Map<S
|
||||
}
|
||||
fields.insert("auto_leading".into(), number_field(justification.and_then(|j| j.get("auto_leading"))));
|
||||
fields.insert("single_word".into(), justification.and_then(|j| j.get("single_word")).filter(|v| v.is_string()).cloned().unwrap_or(Value::Null));
|
||||
fields.insert("tabs".into(), tabs_field(attrs.get("tabs"), unit));
|
||||
fields
|
||||
}
|
||||
|
||||
@@ -292,9 +371,60 @@ pub(crate) fn edited_attrs(d: &Dialog) -> Result<Map<String, Value>, String> {
|
||||
let same = JUSTIFICATION_FIELDS.iter().all(|key| unchanged(key, "__resetJustification"));
|
||||
let value = if same { None } else { justification(d, &original, &original_fields)? };
|
||||
keep_or(&mut attrs, "justification", same, value);
|
||||
|
||||
let same = unchanged("tabs", "__resetTabs");
|
||||
let value = if same { None } else { tab_stops(d, &original, unit)? };
|
||||
keep_or(&mut attrs, "tabs", same, value);
|
||||
Ok(attrs)
|
||||
}
|
||||
|
||||
/// The `tabs` attribute the Tabs section sets: none while the list is unset; otherwise its stops
|
||||
/// sorted by position. Of stops within 1e-6 pt of each other, the one edited last (`__tabEdited`)
|
||||
/// is kept, else the first in the list. A stop as the style has it is kept without a check, and any
|
||||
/// other is read by [`read_stop`]. An error when the list has more than 256 stops and more than the
|
||||
/// style has.
|
||||
fn tab_stops(d: &Dialog, original: &Map<String, Value>, unit: Unit) -> Result<Option<Value>, String> {
|
||||
let rows = match d.fields.get("tabs") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::Array(rows)) => rows,
|
||||
Some(_) => {
|
||||
let key = "tabs";
|
||||
return Err(format!("`{key}` must be an array"));
|
||||
}
|
||||
};
|
||||
let kept: Vec<TabStop> =
|
||||
original.get("tabs").and_then(Value::as_array).into_iter().flatten().filter_map(|s| serde_json::from_value(s.clone()).ok()).collect();
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if rows.len() > max.max(kept.len()) {
|
||||
return Err(format!("at most {max} tab stops"));
|
||||
}
|
||||
let label = caption(if d.bool("__vertical") { tl!("Y:") } else { tl!("X:") });
|
||||
let kept_rows: Vec<Value> = kept.iter().map(|s| stop_field(s, unit)).collect();
|
||||
let mut stops = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
match kept_rows.iter().position(|k| k == row) {
|
||||
Some(i) => stops.push(kept[i].clone()),
|
||||
None => stops.push(read_stop(row, unit, label)?),
|
||||
}
|
||||
}
|
||||
let edited = d.fields.get("__tabEdited").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
|
||||
let mut order: Vec<usize> = (0..stops.len()).collect();
|
||||
order.sort_by(|&a, &b| stops[a].position.total_cmp(&stops[b].position).then(a.cmp(&b)));
|
||||
let mut keep: Vec<usize> = Vec::with_capacity(order.len());
|
||||
for i in order {
|
||||
match keep.last_mut() {
|
||||
Some(last) if (stops[*last].position - stops[i].position).abs() < 1e-6 => {
|
||||
if Some(i) == edited {
|
||||
*last = i;
|
||||
}
|
||||
}
|
||||
_ => keep.push(i),
|
||||
}
|
||||
}
|
||||
let stops: Vec<TabStop> = keep.into_iter().map(|i| stops[i].clone()).collect();
|
||||
Ok(Some(serde_json::to_value(stops).map_err(|e| e.to_string())?))
|
||||
}
|
||||
|
||||
/// The `hyphenation` attribute the Hyphenation fields set: none when every field is empty or
|
||||
/// unset; otherwise the style's options (or the defaults) with each changed field written over
|
||||
/// them, an empty one at its default.
|
||||
@@ -416,15 +546,24 @@ fn reset_justification(d: &mut Dialog) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset Panel in Tabs: the tab stops become unset, which leaves `tabs` out of the style.
|
||||
fn reset_tabs(d: &mut Dialog) {
|
||||
d.fields.insert("__resetTabs".into(), json!(true));
|
||||
d.fields.insert("tabs".into(), Value::Null);
|
||||
d.fields.remove("__tabEdited");
|
||||
d.fields.insert("__tabSel".into(), json!(0));
|
||||
}
|
||||
|
||||
/// Whether the section `d` shows has a Reset Panel: every section but General.
|
||||
pub(crate) fn can_reset(d: &Dialog) -> bool {
|
||||
["basic", "composition", "hyphenation", "justification"].contains(&d.str("section").as_str())
|
||||
["basic", "tabs", "composition", "hyphenation", "justification"].contains(&d.str("section").as_str())
|
||||
}
|
||||
|
||||
/// Reset Panel: clear the settings of the section `d` shows.
|
||||
pub(crate) fn reset_section(d: &mut Dialog) {
|
||||
match d.str("section").as_str() {
|
||||
"basic" => reset_basic(d),
|
||||
"tabs" => reset_tabs(d),
|
||||
"composition" => reset_composition(d),
|
||||
"hyphenation" => reset_hyphenation(d),
|
||||
"justification" => reset_justification(d),
|
||||
@@ -449,9 +588,8 @@ pub fn reset_panel(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
/// The section list of Paragraph Style Options and New Paragraph Style.
|
||||
pub(crate) fn section_list(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
ui.vertical(|ui| {
|
||||
for (id, label) in
|
||||
SECTIONS.into_iter().zip([tl!("General"), tl!("Basic Paragraph Formats"), tl!("Composition"), tl!("Hyphenation"), tl!("Justification")])
|
||||
{
|
||||
let labels = [tl!("General"), tl!("Basic Paragraph Formats"), tl!("Tabs"), tl!("Composition"), tl!("Hyphenation"), tl!("Justification")];
|
||||
for (id, label) in SECTIONS.into_iter().zip(labels) {
|
||||
if ui.selectable_label(d.str("section") == id, label).clicked() {
|
||||
d.fields.insert("section".into(), json!(id));
|
||||
}
|
||||
@@ -529,6 +667,156 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The editing fields of the selected tab stop, with the `tabs` entry key each one shows.
|
||||
const TAB_EDITORS: [(&str, &str); 3] = [("__tabPosition", "position"), ("__tabLeader", "leader"), ("__tabAlignOn", "alignOn")];
|
||||
|
||||
/// Tabs: the selected stop's Alignment, X (Y in vertical type), Leader and Align On, which only a
|
||||
/// decimal stop uses; Add ([`add_tab`]), Delete Tab ([`delete_tab`]) and Clear All Tabs
|
||||
/// ([`clear_tabs`]); and the list of stops, one row each, a click on which selects its stop, which
|
||||
/// scrolls when it is taller than 160 points. A change to a field makes its stop the one edited last.
|
||||
pub(crate) fn tabs_body(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let vertical = d.bool("__vertical");
|
||||
let (mut rows, mut sel, _) = tab_rows(d);
|
||||
let mut changed = false;
|
||||
let has = sel < rows.len();
|
||||
let shown = TAB_EDITORS.map(|(_, key)| rows.get(sel).and_then(|r| r.get(key)).and_then(Value::as_str).unwrap_or("").to_string());
|
||||
for ((field, _), text) in TAB_EDITORS.iter().zip(&shown) {
|
||||
d.fields.insert((*field).into(), json!(text));
|
||||
}
|
||||
let align = rows.get(sel).and_then(|r| r.get("align")).and_then(Value::as_str).unwrap_or("left").to_string();
|
||||
egui::Grid::new("paragraph-style-tabs").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| {
|
||||
let row = ui.label(tl!("Alignment:"));
|
||||
let names: Vec<&str> = TAB_ALIGNS.iter().map(|(a, _)| crate::panels::tabs::align_name(*a, vertical)).collect();
|
||||
let shown = TAB_ALIGNS.iter().position(|(_, key)| *key == align).and_then(|i| names.get(i).copied()).unwrap_or("");
|
||||
ui.add_enabled_ui(has, |ui| {
|
||||
ui.label_inputs_by(row.id, |ui| {
|
||||
if let Some(i) = crate::widgets::dropdown(ui, (KIND, "tab_align"), shown, &names, 190.0)
|
||||
&& let (Some(r), Some((_, key))) = (rows.get_mut(sel).and_then(Value::as_object_mut), TAB_ALIGNS.get(i))
|
||||
{
|
||||
r.insert("align".into(), json!(key));
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.end_row();
|
||||
field_row(ui, d, "__tabPosition", if vertical { tl!("Y:") } else { tl!("X:") }, "", has);
|
||||
field_row(ui, d, "__tabLeader", tl!("Leader:"), "", has);
|
||||
field_row(ui, d, "__tabAlignOn", tl!("Align On:"), "", has && align == "decimal");
|
||||
});
|
||||
for ((field, key), was) in TAB_EDITORS.iter().zip(&shown) {
|
||||
let typed = d.str(field);
|
||||
if let Some(r) = rows.get_mut(sel).and_then(Value::as_object_mut)
|
||||
&& typed != *was
|
||||
{
|
||||
r.insert((*key).into(), json!(typed));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
d.fields.insert("tabs".into(), Value::Array(rows.clone()));
|
||||
d.fields.insert("__tabEdited".into(), json!(sel));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
let (mut add, mut delete, mut clear) = (false, false, false);
|
||||
let can_add = new_tab_position(&rows, unit_of(d)).is_some();
|
||||
ui.horizontal(|ui| {
|
||||
add = ui.add_enabled(can_add, egui::Button::new(tl!("Add"))).clicked();
|
||||
delete = ui.add_enabled(has, egui::Button::new(tl!("Delete Tab"))).clicked();
|
||||
clear = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Clear All Tabs"))).clicked();
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let reveal = d.fields.remove("__tabScroll").is_some();
|
||||
egui::ScrollArea::vertical().id_salt("paragraph-style-tab-list").max_height(160.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
for (i, r) in rows.iter().enumerate() {
|
||||
let a = r.get("align").and_then(Value::as_str).and_then(|key| TAB_ALIGNS.iter().find(|(_, k)| *k == key)).map(|(a, _)| *a);
|
||||
let name = a.map_or("", |a| crate::panels::tabs::align_name(a, vertical));
|
||||
let mut text = format!("{} {name}", r.get("position").and_then(Value::as_str).unwrap_or(""));
|
||||
if let Some(leader) = r.get("leader").and_then(Value::as_str).filter(|l| !l.is_empty()) {
|
||||
text += &format!(" {leader}");
|
||||
}
|
||||
let row = ui.selectable_label(i == sel, text);
|
||||
if reveal && i == sel {
|
||||
ui.scroll_to_rect_animation(row.rect, None, egui::style::ScrollAnimation::none());
|
||||
}
|
||||
if row.clicked() {
|
||||
sel = i;
|
||||
}
|
||||
}
|
||||
});
|
||||
d.fields.insert("__tabSel".into(), json!(sel));
|
||||
if add {
|
||||
add_tab(d);
|
||||
} else if delete {
|
||||
delete_tab(d);
|
||||
} else if clear {
|
||||
clear_tabs(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `tabs` entries of `d` (none while unset), the selected one's index (`__tabSel`, at most the
|
||||
/// last) and the index of the one edited last (`__tabEdited`).
|
||||
fn tab_rows(d: &Dialog) -> (Vec<Value>, usize, Option<usize>) {
|
||||
let rows: Vec<Value> = d.fields.get("tabs").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let index = |key: &str| d.fields.get(key).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
|
||||
let sel = index("__tabSel").unwrap_or(0).min(rows.len().saturating_sub(1));
|
||||
(rows, sel, index("__tabEdited"))
|
||||
}
|
||||
|
||||
/// The position (pt) Add gives a new stop among `rows`: half an inch past the furthest stop that
|
||||
/// reads, half an inch when none does, and at most 100000 pt. `None` while the list holds 256 stops
|
||||
/// or when a stop already sits at that position.
|
||||
fn new_tab_position(rows: &[Value], unit: Unit) -> Option<f64> {
|
||||
if rows.len() >= TabStop::MAX_STOPS {
|
||||
return None;
|
||||
}
|
||||
let positions: Vec<f64> = rows.iter().filter_map(|r| stop_position(r, unit)).collect();
|
||||
let furthest = positions.iter().copied().filter(|pt| (0.0..=TabStop::MAX_POSITION).contains(pt)).reduce(f64::max);
|
||||
let position = furthest.map_or(DEFAULT_TAB_INTERVAL, |pt| pt + DEFAULT_TAB_INTERVAL).min(TabStop::MAX_POSITION);
|
||||
(!positions.iter().any(|pt| (pt - position).abs() < 1e-6)).then_some(position)
|
||||
}
|
||||
|
||||
/// Add in Tabs: a left stop at [`new_tab_position`], which becomes the selected and last edited
|
||||
/// stop and is scrolled into view in the list. Nothing when that gives no position.
|
||||
pub(crate) fn add_tab(d: &mut Dialog) {
|
||||
let unit = unit_of(d);
|
||||
let (mut rows, _, _) = tab_rows(d);
|
||||
let Some(position) = new_tab_position(&rows, unit) else { return };
|
||||
rows.push(stop_field(&TabStop { position, align: TabAlign::Left, leader: String::new(), align_on: '.' }, unit));
|
||||
let at = rows.len() - 1;
|
||||
d.fields.insert("tabs".into(), Value::Array(rows));
|
||||
d.fields.insert("__tabSel".into(), json!(at));
|
||||
d.fields.insert("__tabEdited".into(), json!(at));
|
||||
d.fields.insert("__tabScroll".into(), json!(true));
|
||||
}
|
||||
|
||||
/// Delete Tab in Tabs: remove the selected stop; the next one (or the last) becomes selected.
|
||||
pub(crate) fn delete_tab(d: &mut Dialog) {
|
||||
let (mut rows, sel, edited) = tab_rows(d);
|
||||
if sel >= rows.len() {
|
||||
return;
|
||||
}
|
||||
rows.remove(sel);
|
||||
match edited {
|
||||
Some(e) if e == sel => {
|
||||
d.fields.remove("__tabEdited");
|
||||
}
|
||||
Some(e) if e > sel => {
|
||||
d.fields.insert("__tabEdited".into(), json!(e - 1));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
d.fields.insert("__tabSel".into(), json!(sel.min(rows.len().saturating_sub(1))));
|
||||
d.fields.insert("tabs".into(), Value::Array(rows));
|
||||
d.fields.insert("__tabScroll".into(), json!(true));
|
||||
}
|
||||
|
||||
/// Clear All Tabs in Tabs: an empty list of stops, which the style then sets.
|
||||
pub(crate) fn clear_tabs(d: &mut Dialog) {
|
||||
d.fields.insert("tabs".into(), json!([]));
|
||||
d.fields.insert("__tabSel".into(), json!(0));
|
||||
d.fields.remove("__tabEdited");
|
||||
}
|
||||
|
||||
/// Composition: the Single-line or Every-line Composer, and Roman Hanging Punctuation.
|
||||
pub(crate) fn composition_body(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
egui::Grid::new("paragraph-style-composition").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| {
|
||||
@@ -624,6 +912,7 @@ pub(crate) fn general_body(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
pub(crate) fn section_body(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
match d.str("section").as_str() {
|
||||
"basic" => basic_body(ui, d),
|
||||
"tabs" => tabs_body(ui, d),
|
||||
"composition" => composition_body(ui, d),
|
||||
"hyphenation" => hyphenation_body(ui, d),
|
||||
"justification" => justification_body(ui, d),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user