Merge main into feat/scripts-xmp-objects

This commit is contained in:
dotCooCoo committed 2026-11-26 15:20:19 -08:00
commit 0669a4525a
259 files changed
+15004 -959

No files matched your search

Generated
+2
View File
@@ -8788,6 +8788,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-js",
"wasmi",
"wasmparser 0.228.0",
"wat",
@@ -8932,6 +8933,7 @@ dependencies = [
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-text",
"vectorcraft-tools",
]
[[package]]
+1
View File
@@ -153,6 +153,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
+3 -1
View File
@@ -238,11 +238,13 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each
/// script's `Folder.userData` in the Script Data folder there, keeps File Info's
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_startup_scripts_dir(&mut h.session);
prefs_dir::attach_script_data(&mut h.session);
prefs_dir::attach_metadata_templates_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
+5
View File
@@ -824,6 +824,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
// The startup scripts are in the Startup Scripts folder next to the preferences.
prefs_dir::attach_startup_scripts_dir(&mut session);
// File Info's metadata templates live in their own folder next to the preferences.
prefs_dir::attach_metadata_templates_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
@@ -977,6 +979,9 @@ fn main() -> std::process::ExitCode {
single_instance::set_ui(&cc.egui_ctx);
}
let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files));
// With General › Run Startup Scripts on and Safe Mode off, the startup scripts run
// now, as the person's own; in Safe Mode they wait for the choice that ends it.
file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app));
// The first frame is due from now (`gpu::watch_first_frame`).
#[cfg(feature = "wgpu")]
created.ready();
+8
View File
@@ -66,6 +66,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
}
}
/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only
/// read: the user makes it.
pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Startup Scripts") {
session.attach_startup_scripts_dir(dir);
}
}
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
/// makes.
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
+31 -6
View File
@@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4;
pub const POWERLESS_CHROMA: f64 = 0.000_004;
/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
const GAMUT_SLACK: f64 = 1e-4;
const GAMUT_SLACK: f64 = 1e-5;
/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
/// are. The hue is in 0..360, and 0 while the chroma is powerless.
@@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 {
///
/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic
/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
/// search finds each such chroma between the cubic's turning points and takes the largest one that
/// fits.
@@ -112,11 +112,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {
/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and
/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as
/// lowered.
pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
let h = if h.is_finite() { h } else { 0.0 };
if l == 0.0 || l == 1.0 {
return ([l as f32; 3], c > 0.0);
}
let exact = oklch_to_srgb(l, c, h);
let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
(rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
@@ -239,12 +244,10 @@ mod tests {
}
/// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
/// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
/// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
/// every hue and at lightnesses near black too.
#[test]
fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
let max = max_chroma(l, h);
@@ -262,4 +265,26 @@ mod tests {
assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
}
/// The lightness endpoints give exactly black and white at any chroma and hue, and report a
/// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel.
#[test]
fn the_lightness_endpoints_give_exact_black_and_white() {
assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true));
assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false));
assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true));
assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false));
}
/// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that
/// fits, not clipped at its own chroma.
#[test]
fn a_channel_just_below_zero_is_outside_the_gamut() {
assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0)));
let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0);
assert!(lowered, "{rgb:?}");
let [_, c, _] = to_oklch(rgb);
assert!(c < 0.01, "{c}");
assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0)));
}
}
+1 -1
View File
@@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use orient::OrientedBox;
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
pub use perspective::PerspectiveAttachment;
+32
View File
@@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
if let Some(e) = n.extras_box() {
b += ALLOC + size_of::<NodeExtras>();
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
b += e.attrs.as_deref().map_or(0, attrs_bytes);
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
b += e
.color_mask
@@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize {
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::<usize>()
}
/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and
/// tags.
fn attrs_bytes(a: &crate::ObjectAttributes) -> usize {
let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::<usize>();
a.url.capacity()
+ a.note.capacity()
+ pairs(&a.data)
+ pairs(&a.events)
+ vec_bytes(&a.classes)
+ a.classes.iter().map(String::capacity).sum::<usize>()
+ vec_bytes(&a.foreign)
+ a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::<usize>()
+ vec_bytes(&a.tags)
+ a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::<usize>()
}
/// A vector's buffer (not what its elements own).
fn vec_bytes<T>(v: &Vec<T>) -> usize {
if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::<T>() }
@@ -490,6 +507,21 @@ mod tests {
assert!((400..1200).contains(&per), "{per} bytes per moved rectangle");
}
/// An object's attributes count with their text: a version of a rectangle with a long tag and
/// a long note keeps both.
#[test]
fn tags_and_notes_count() {
let before = doc_with_rects(1);
let mut after = before.clone();
let id = after.layers[0].children().unwrap()[0].id;
after.node_mut(id).unwrap().edit_attrs(|a| {
a.note = "n".repeat(30_000);
a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) });
});
let bytes = after.retained_bytes(&before);
assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes");
}
#[test]
fn a_grouped_object_is_found_shared() {
let before = doc_with_rects(100);
+1 -1
View File
@@ -24,7 +24,7 @@ mod opacity;
mod ops;
mod wire;
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use clip::{ClipPaint, Uniter};
pub use extras::{Extras, ExtrasMut, NodeExtras};
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
+135
View File
@@ -38,6 +38,141 @@ pub struct ObjectAttributes {
/// with it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub foreign: Vec<ForeignAttribute>,
/// The object's tags, in order: name and value pairs that scripts read and write
/// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and
/// value at most [`MAX_TAG_TEXT`] bytes.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<ObjectTag>,
}
/// The most tags one object has.
pub const MAX_TAGS: usize = 64;
/// The longest name or value a tag has, in bytes.
pub const MAX_TAG_TEXT: usize = 64 * 1024;
/// A tag on an object: a name and a value, with an id that tells it apart from the object's other
/// tags while its name and value change.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObjectTag {
/// Distinct among the object's tags: a new tag takes an id from
/// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id,
/// so a deleted tag's id is not given out again.
#[serde(default, deserialize_with = "lenient_tag_id")]
pub id: u64,
#[serde(default)]
pub name: String,
#[serde(default)]
pub value: String,
}
/// Reading a native file never fails over a tag id that is not a whole number from 0 to
/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and
/// [`crate::Document::tidy_tags`] gives the tag a new id.
fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0))
}
impl ObjectAttributes {
/// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most
/// [`MAX_TAG_TEXT`] bytes. → whether any was dropped.
pub fn tidy_tags(&mut self) -> bool {
let before = self.tags.len();
self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT);
self.tags.truncate(MAX_TAGS);
self.tags.len() != before
}
}
impl crate::Document {
/// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of
/// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag
/// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier
/// tag of the object has it. Every other tag gets a new id: from the next node id on, above
/// every kept id, when those ids stay below that limit; otherwise the smallest id the object's
/// other tags do not have. The next node id is then raised past every tag id below the limit.
/// It recurses through the art: call it on a document no deeper than
/// [`crate::depth::MAX_DEPTH`].
pub fn tidy_tags(&mut self) {
fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool {
(1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id)
}
// The limits, the largest kept id and the number of new ids first, so that a new id never
// meets a kept one.
let mut next = self.peek_next_id();
let mut fresh = 0u64;
self.each_tagged(&mut |a| {
a.tidy_tags();
for (i, t) in a.tags.iter().enumerate() {
if keeps(t, &a.tags[..i]) {
next = next.max(t.id.saturating_add(1));
} else {
fresh = fresh.saturating_add(1);
}
}
});
if fresh == 0 {
self.raise_next_id(next);
return;
}
let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID;
self.each_tagged(&mut |a| {
let kept: Vec<bool> = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect();
let mut used: Vec<u64> = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect();
for (i, k) in kept.iter().enumerate() {
if *k {
continue;
}
let id = if in_range {
next = next.saturating_add(1);
next - 1
} else {
(1..).find(|c| !used.contains(c)).unwrap_or(1)
};
a.tags[i].id = id;
used.push(id);
}
});
self.raise_next_id(next);
}
/// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the
/// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the
/// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an
/// id below it could be a deleted tag's.
pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option<u64> {
let used: Vec<u64> =
self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default();
for _ in 0..=used.len() {
if self.peek_next_id() >= crate::limits::MAX_NEXT_ID {
return None;
}
let tag = self.alloc_id().0;
if !used.contains(&tag) {
return Some(tag);
}
}
None
}
/// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads.
fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) {
let mut fix = |n: &mut Node| {
if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) {
n.edit_attrs(&mut *f);
}
};
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix);
}
}
}
/// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter=
+6
View File
@@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str
INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect())
}
/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in
/// effects).
pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> {
catalog_index().get(id).map(|e| (e.id, e.label))
}
/// Catalogue entry for `id` (built-in, or an installed plug-in effect).
pub fn effect_info(id: &str) -> Option<EffectInfo> {
catalog_index().get(id).cloned().or_else(|| plugin_info(id))
+3 -1
View File
@@ -125,7 +125,9 @@ mod catalog;
mod geometry;
mod params;
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range};
pub use catalog::{
EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range,
};
pub(crate) use geometry::{Budget, apply_one};
pub use geometry::{
Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with,
+5
View File
@@ -102,6 +102,7 @@ pub mod swatchlib;
pub(crate) mod symboledit;
pub mod symbollib;
pub(crate) mod tabs;
pub(crate) mod tags;
mod textedit;
pub use textedit::effective_kerning;
@@ -376,6 +377,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(library::specs());
v.extend(expand::specs());
v.extend(attributes::specs());
v.extend(tags::specs());
v.extend(interactivity::specs());
v.extend(spelling::specs());
v.extend(svgfilter::specs());
@@ -924,6 +926,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT
/// An Image Trace made off the UI thread, and what it traced (#3098).
pub use buildcmds::{TraceRun, Traced, image_trace_target};
/// Retype's search of the installed fonts, made off the UI thread.
pub use retype::{RetypeFound, RetypeRun, RetypeSearch};
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
pub(crate) use buildcmds::TracePresetChanges;
+1 -1
View File
@@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…'));
let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc);
let swatches = |name: &str| kinds.get(name).copied();
recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)))
}
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
+6 -2
View File
@@ -20,7 +20,7 @@ use vectorcraft_text::edit;
use super::super::menucmds::whole_or;
use super::super::object::choice;
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
use super::super::typecmd::refresh_bounds;
use super::super::typecmd::{refresh_bounds, refresh_with_given_leading};
use super::super::typemenu::{bake_dynamic_text, text_ids};
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
use crate::{EngineError, Result, Session};
@@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
for (id, changes) in &plans {
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
t.runs = tweak(std::mem::take(&mut t.runs), changes);
refresh_bounds(t);
// With Block on, the first changed character's leading goes to the frame's line gap.
match changes.first().filter(|_| key == "leading") {
Some(&(at, _)) => refresh_with_given_leading(t, at),
None => refresh_bounds(t),
}
}
Ok(())
})?;
+6 -3
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swatch Conflicts",
[],
None,
"{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
"{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
has_doc,
conflicts
),
@@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
fn conflicts(s: &mut Session, p: &Value) -> Result<Value> {
let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex());
// The swatches as the paste brings them: converted from another profile when it converts.
let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?;
const CMD: &str = "clipboard.conflicts";
let profile = super::colormgmt::PasteProfile::param(p, CMD)?;
// Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind.
let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?;
let st = s.doc()?;
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true);
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards);
let list: Vec<Value> = converted
.as_ref()
.unwrap_or(&s.clipboard)
+2
View File
@@ -809,6 +809,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
let selection = shared_selection(selection, st.history.redo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
turned.named = e.named;
turned.effect = e.effect;
let paints = e.color_mode_paints.clone();
turned.color_mode_paints = e.color_mode_paints;
turned.recost_paints();
@@ -845,6 +846,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
let selection = shared_selection(selection, st.history.undo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
turned.named = e.named;
turned.effect = e.effect;
let paints = e.color_mode_paints.clone();
turned.color_mode_paints = e.color_mode_paints;
turned.recost_paints();
+41 -32
View File
@@ -514,11 +514,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default();
aligned(p, C)?;
if let Some(loose) = loose_for_pathfinder(s, p, id)? {
let gid = s.edit(&label, |d, sel| {
let gid = super::object::group_nodes(d, &loose)?;
d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone());
sel.set([gid]);
Ok(gid)
let gid = s.edit_effect(id, |s| {
s.edit(&label, |d, sel| {
let gid = super::object::group_nodes(d, &loose)?;
d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone());
sel.set([gid]);
Ok(gid)
})
})?;
return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true }));
}
@@ -549,9 +551,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
fx.push(effect.clone());
true
let ids = s.edit_effect(id, |s| {
edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
fx.push(effect.clone());
true
})
})?;
// The item the effect landed on in the object whose row the item is (the first selected object
// for the active item, which applies where it fits), and the effect's index in that object.
@@ -892,32 +896,37 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
let Some(e) = fx.get_mut(index) else { return false };
if let Some(id) = &warp_id {
e.id.clone_from(id);
}
if let Some(to) = kind
&& e.id != to
{
e.params = effects::three_d_params_as(&e.id, &e.params, to);
e.id = to.to_string();
}
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, &params), &mut e.params) {
if !cur.is_object() {
*cur = effects::merged_params(&e.id, &Value::Null);
// The effect edited, when every target has one at `index` and all are the same: a dialog's
// preview names its step after it.
let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default();
let ids = s.edit_effect(&one, |s| {
edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
let Some(e) = fx.get_mut(index) else { return false };
if let Some(id) = &warp_id {
e.id.clone_from(id);
}
// Earlier parameters (a Perspective strength, a light by azimuth and elevation) take
// their current form first, so the new values replace them and the rest is kept.
*cur = effects::upgrade_params(&e.id, cur);
if let Value::Object(m) = cur {
m.extend(new);
if let Some(to) = kind
&& e.id != to
{
e.params = effects::three_d_params_as(&e.id, &e.params, to);
e.id = to.to_string();
}
}
if let Some(v) = visible {
e.visible = v;
}
true
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, &params), &mut e.params) {
if !cur.is_object() {
*cur = effects::merged_params(&e.id, &Value::Null);
}
// Earlier parameters (a Perspective strength, a light by azimuth and elevation) take
// their current form first, so the new values replace them and the rest is kept.
*cur = effects::upgrade_params(&e.id, cur);
if let Value::Object(m) = cur {
m.extend(new);
}
}
if let Some(v) = visible {
e.visible = v;
}
true
})
})?;
Ok(json!({ "ids": ids_json(&ids) }))
}
+11 -4
View File
@@ -87,10 +87,12 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
/// front, the Appearance panel's active item and the tool the proxy in front shows the default
/// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art,
/// picking a part of the instance, toggling the proxy, picking another item or choosing such a
/// tool or leaving it leaves no stop selected.
/// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint
/// diamond by it as well ([`Session::gradient_owner`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct StopOwner {
doc: Option<usize>,
pub struct StopOwner {
/// The active document's uid, which stays the same when its tab moves.
doc: Option<u64>,
object: Option<NodeId>,
/// The object whose paint the active proxy shows: a Live Paint group without faces (or edges)
/// first in the selection shows the next object's.
@@ -106,7 +108,7 @@ impl StopOwner {
pub(crate) fn of(s: &Session) -> Self {
let st = s.active();
Self {
doc: s.active,
doc: st.map(|d| d.uid),
object: st.and_then(|d| d.selection.objects.first().copied()),
source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id),
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
@@ -140,6 +142,11 @@ impl Session {
pub fn selected_stop(&self) -> Option<usize> {
self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i)
}
/// Whose gradient the active proxy shows now, as a selected stop keeps it ([`StopOwner`]).
pub fn gradient_owner(&self) -> StopOwner {
StopOwner::of(self)
}
}
type Parsed<T> = std::result::Result<T, String>;
+2
View File
@@ -715,6 +715,7 @@ pub const UNCHECKED: &[&str] = &[
"document.exportForScreens",
"document.exportForWeb",
"document.exportForWeb.preview",
"document.exportForWeb.saveColorTable",
"document.exportPdf",
"document.find",
"document.inspect",
@@ -820,6 +821,7 @@ pub const UNCHECKED: &[&str] = &[
"transparency.setOpacityMask",
"transparency.unlinkOpacityMask",
"type.pathOptions",
"webExport.loadColorTable",
"webExport.optimizeToFileSize",
"webExport.presets.save",
"webExport.settings",
+28 -8
View File
@@ -50,6 +50,10 @@
//! also given the parts of the active document it names in `_context.document`, whether or not
//! anything is selected: the settings, artboards, layers and swatches, as plain values
//! ([`context`]).
//!
//! A filter may be written in JavaScript ([`vectorcraft_plugins::js`]): `plugin.install {path}`
//! takes its `.vcplugin` manifest and reads the `.js` file the manifest names beside it, and the
//! plug-in store keeps the two as one module.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
@@ -124,6 +128,10 @@ pub fn describe(p: &Plugin) -> Value {
if m.paint_output {
v["paintOutput"] = json!(true);
}
if let Some(script) = p.script() {
v["runtime"] = json!(m.runtime.name());
v["script"] = json!(script);
}
if !m.command_allowlist.is_empty() {
v["commandAllowlist"] = json!(m.command_allowlist);
}
@@ -1008,8 +1016,9 @@ pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::resu
/// Largest base64 payload `plugin.install` accepts (the module limit, encoded).
const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4;
/// The `.wasm` extension plug-in files have (File › Open installs them).
pub const EXTS: &[&str] = &["wasm"];
/// The extensions plug-in files have (File › Open installs them): a WebAssembly module, and a
/// JavaScript plug-in's manifest.
pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT];
/// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a
/// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source).
@@ -1389,12 +1398,23 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
})
}
/// The plug-in in the `.wasm` file `path`, and its module.
/// The plug-in in the `.wasm` file `path`, or in the `.vcplugin` manifest `path` and the `.js` file
/// it names, and its module: for a JavaScript plug-in, the manifest with the script's text
/// ([`registry::read_js_package`]). Under automation read roots the script must be inside them too.
#[cfg(not(target_arch = "wasm32"))]
fn load_path(path: &str) -> Result<(Plugin, Vec<u8>)> {
crate::file_access::check_read(path).map_err(EngineError::Other)?;
let limits = vectorcraft_plugins::Limits::default();
let bytes = crate::store::read_capped(std::path::Path::new(path), limits.max_module_bytes as u64).map_err(EngineError::Other)?;
let file = std::path::Path::new(path);
let bytes = if registry::is_js_package(file) {
let allow = |script: &std::path::Path| match script.to_str() {
Some(script) => crate::file_access::check_read(script),
None => Err(format!("automation path rejected: {} isn't valid text", script.display())),
};
registry::read_js_package(file, &allow).map_err(err)?
} else {
crate::store::read_capped(file, limits.max_module_bytes as u64).map_err(EngineError::Other)?
};
Ok((Plugin::load(&bytes, limits).map_err(err)?.with_source(path), bytes))
}
@@ -1958,7 +1978,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -1985,7 +2005,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Install Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
"{path: a .wasm file or a JavaScript plug-in's .vcplugin manifest (read with the .js file its script names) (desktop) | dataBase64: the module or a JavaScript plug-in as one JSON object (its manifest, with the script's text in source) (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
always,
install
),
@@ -1994,7 +2014,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
always,
inspect
),
@@ -2021,7 +2041,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reload Plug-ins",
["Object", "Plug-ins"],
None,
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}",
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm and *.vcplugin in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm and *.vcplugin files past the first 1,000, not tried}",
always,
reload
),
@@ -404,6 +404,11 @@ pub(super) const ALLOWED: &[&str] = &[
"object.slice.release",
"object.slice.select",
"object.slice.setRect",
"object.tag.add",
"object.tag.remove",
"object.tag.removeAll",
"object.tag.set",
"object.tags",
"object.textWrap.make",
"object.textWrap.options",
"object.textWrap.release",
+1
View File
@@ -146,6 +146,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showToolCards", "General", "Options", "Show Tool Cards", bool),
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
p!("runStartupScripts", "General", "Options", "Run Startup Scripts", bool),
p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool),
p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool),
p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool),
+190 -63
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only), installed?: bool} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; shapes none of those fonts match are then compared in the same way (the tolerance and the splitting included) with the installed fonts not loaded yet, unless installed is false (true, omitted or null: compared): their files are read smallest first, one at a time, until each such shape matches the fonts read, leaving out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn in all, and a font whose glyphs match such a shape, or complete the glyphs of a split one with the fonts found before it, is loaded; a plain shape (one contour of up to four straight edges, such as a rectangle) starts no such reading and matches only a font the other shapes found; a cancel stops between files; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are wh Line truncated
has_selected_path,
retype
)]
@@ -56,6 +56,10 @@ pub fn specs() -> Vec<CommandSpec> {
#[path = "retype_fonts.rs"]
pub(super) mod fonts;
#[path = "retype_installed.rs"]
mod installed;
pub use installed::{RetypeFound, RetypeRun, RetypeSearch};
/// A shape to match: a path or compound path, in document space.
struct Piece {
@@ -141,7 +145,8 @@ fn type_can_paint(ap: &Appearance) -> bool {
ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none())
}
/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face.
/// The faces to match against: the families in `fonts`, the document's fonts, the faces earlier
/// searches of the installed fonts loaded ([`installed::found`]), then every other loaded face.
fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vectorcraft_text::FontFace>> {
let mut families: Vec<String> = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect();
d.walk(|n| {
@@ -168,7 +173,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vecto
}
}
}
for face in db.loaded_faces() {
// The faces earlier searches of the installed fonts found, then the other loaded faces.
for face in installed::found(db).into_iter().chain(db.loaded_faces()) {
if faces.len() >= cap {
break;
}
@@ -1357,6 +1363,48 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
})
}
/// `type.retype`'s `fonts` param: the family names it lists.
fn fonts_param(p: &Value) -> Result<Vec<String>> {
const C: &str = "type.retype";
match p.get("fonts") {
None => Ok(vec![]),
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect()
}
Some(_) => Err(bad(C, "fonts must be a list of family names")),
}
}
/// `type.retype`'s `tolerance` param: 0 (exact matches only) when omitted.
fn tolerance_param(p: &Value) -> Result<f64> {
const C: &str = "type.retype";
match p.get("tolerance") {
None => Ok(0.0),
Some(v) => match v.as_f64() {
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => Ok(t),
_ => Err(bad(C, "tolerance must be a number from 0 to 0.05")),
},
}
}
/// The shapes of the selected objects, in paint order, and whether shapes past the limits were
/// left out; an error when the selection holds none.
fn selected_pieces(s: &Session) -> Result<(Vec<Piece>, bool)> {
let roots = selected_roots(s)?;
let d = &s.doc()?.doc;
let mut pieces = vec![];
let (mut barrier, mut truncated) = (true, false);
for r in &roots {
if let Some(n) = d.node(*r) {
collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces);
}
}
if pieces.is_empty() {
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
}
Ok((pieces, truncated))
}
/// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line
/// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape
/// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the
@@ -1675,26 +1723,70 @@ fn lookup_keys<'a>(
(wanted, near_wanted)
}
/// The candidates of `path` in `indexes`: the exact ones of every index (for a `part` of a split
/// shape, either way round), or, when there are none and `near` is set, the near ones within
/// `tolerance`. With `fill` (`Some(nonzero)`, for a shape with a visible fill), only glyphs that
/// paint the area `path` paints under that rule are kept.
fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool, fill: Option<bool>, tolerance: f64) -> Vec<GlyphMatch> {
let painted = |index: &RetypeIndex, ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
match fill {
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
None => ms,
}
};
let exact: Vec<GlyphMatch> =
indexes.iter().flat_map(|ix| painted(ix, if part { ix.matches_either_way(path) } else { ix.all_matches(path) }, 0.0)).collect();
if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact }
}
/// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour
/// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is
/// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as
/// several objects would ([`paints_once`]).
fn shape_parts(path: &BezPath, groups: &[BezPath], fill: Option<bool>, once: bool, indexes: &[&RetypeIndex], tolerance: f64) -> Vec<Vec<GlyphMatch>> {
let find = |p: &BezPath, part: bool, near: bool| candidates(indexes, p, part, near, fill, tolerance);
// Parts that all match exactly are checked at tolerance 0, in the near phase as in the exact
// one; only a part that matches nearly brings the tolerance in. The glyphs of a split may
// become separate objects: when the shape does not paint its overlaps as several objects
// would (translucent, another blend, a gradient or pattern fill, a stroke), its parts must not
// overlap, which the parts read by the even-odd rule against them all joined show.
let together = |runs: &[BezPath], near: bool| {
if fill.is_none() && once {
return true;
}
let nearly = near && runs.iter().any(|r| find(r, true, false).is_empty());
let tol = if nearly { tolerance } else { 0.0 };
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(path, runs, nz, tol))
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
};
parts(path, groups, &find, &together)
}
/// Each of `pieces`' parts, as [`shape_parts`] finds them in `indexes`: none for a piece that
/// keeps its outline or matches nothing. `groups` holds each piece's contour groups.
fn match_pieces(pieces: &[Piece], groups: &[Vec<BezPath>], indexes: &[&RetypeIndex], tolerance: f64) -> Vec<Vec<Vec<GlyphMatch>>> {
pieces
.iter()
.zip(groups)
.map(|(pc, g)| {
if pc.keeps_outline {
return vec![];
}
shape_parts(&pc.path, g, pc.filled.then_some(pc.nonzero), paints_once(pc.opacity, pc.blend, &pc.appearance), indexes, tolerance)
})
.collect()
}
fn retype(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.retype";
let fonts: Vec<String> = match p.get("fonts") {
None => vec![],
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::<Result<_>>()?
}
Some(_) => return Err(bad(C, "fonts must be a list of family names")),
};
let tolerance = match p.get("tolerance") {
None => 0.0,
Some(v) => match v.as_f64() {
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t,
_ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")),
},
};
let fonts = fonts_param(p)?;
let tolerance = tolerance_param(p)?;
let search_installed = installed::wanted(C, p)?;
let handed = installed::handed(s);
let roots = selected_roots(s)?;
let db = FontDb::global();
let system_layout = s.doc()?.doc.setup.system_layout;
let (lines, unmatched, truncated) = {
let (lines, unmatched, truncated, installed) = {
let d = &s.doc()?.doc;
let mut pieces = vec![];
let mut truncated = false;
@@ -1725,52 +1817,69 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let (wanted, near_wanted) =
lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance);
// Nothing to match (every shape stays an outline): no font is read.
let index = if wanted.is_empty() && near_wanted.is_empty() {
RetypeIndex::default()
} else {
RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted)
let keyed = !(wanted.is_empty() && near_wanted.is_empty());
let cands = if keyed { candidate_faces(db, d, &fonts) } else { vec![] };
let mut compared: Vec<u32> = cands.iter().map(|f| f.id()).collect();
let build = |faces: Vec<Arc<vectorcraft_text::FontFace>>| {
if keyed { RetypeIndex::build_near(db, faces, &wanted, &near_wanted) } else { RetypeIndex::default() }
};
// Exact matches first; near ones, when allowed, only for a path with none.
// With a visible fill, a glyph is kept only when it paints the area the shape paints under
// the shape's fill rule (`fill` is `Some(nonzero)`).
let find = |path: &BezPath, part: bool, near: bool, fill: Option<bool>| {
let painted = |ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
match fill {
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
None => ms,
}
};
let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0);
if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact }
};
// Each shape's parts (one, unless it holds several glyphs), each with its candidates.
let found: Vec<Vec<Vec<GlyphMatch>>> = pieces
.iter()
.zip(&groups)
.map(|(pc, g)| {
if pc.keeps_outline {
return vec![];
}
let fill = pc.filled.then_some(pc.nonzero);
// Parts that all match exactly are checked at tolerance 0, in the near phase as in
// the exact one; only a part that matches nearly brings the tolerance in.
// The glyphs of a split may become separate objects: when the shape does not paint
// its overlaps as several objects would (translucent, another blend, a gradient or
// pattern fill, a stroke), its parts must not overlap, which the parts read by the
// even-odd rule against them all joined show.
let once = paints_once(pc.opacity, pc.blend, &pc.appearance);
let together = |runs: &[BezPath], near: bool| {
if fill.is_none() && once {
return true;
}
let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty());
let tol = if nearly { tolerance } else { 0.0 };
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol))
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
let index = build(cands.clone());
// Exact matches first; near ones, when allowed, only for a path with none. With a visible
// fill, a glyph is kept only when it paints the area the shape paints under the shape's
// fill rule. Each shape's parts (one, unless it holds several glyphs), each with its
// candidates.
let mut found = match_pieces(&pieces, &groups, &[&index], tolerance);
// Shapes no face matched are compared with the other loaded faces, then with the installed
// fonts not loaded yet; or with what a search made off the UI thread found for them.
let left = left_shapes(&pieces, &groups, &found);
// A split shape's glyphs may be spread over the candidates and the other faces. Near
// matching spends an index's comparison budget, so with a tolerance the candidates are
// indexed again for each search that has a split shape to look for.
let again = |needed: bool| (needed && tolerance > 0.0).then(|| build(cands.clone()));
let (more, installed) = match handed {
Some(handed) => {
let mut more = handed.faces.clone();
compared.extend(handed.faces.iter().map(|f| f.id()));
// The shapes still left are compared with the loaded faces the search did not
// compare: none, unless a face was loaded after it looked.
compared.extend(handed.scanned.iter().copied());
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
more.extend(installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?.0);
(more, handed)
}
None => {
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
let (mut more, done, kept) = installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?;
let left: Vec<installed::Sought> = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect();
let installed = if search_installed {
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
let kept: Vec<RetypeIndex> = if tolerance > 0.0 { kept.iter().map(|ix| build(ix.faces().to_vec())).collect() } else { kept };
let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect();
installed::search_beside(db, &left, &beside, tolerance, false)?
} else {
installed::Installed::default()
};
parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together)
})
.collect();
more.extend(installed.faces.iter().cloned());
(more, installed)
}
};
// The faces found join the candidates, the way the loaded ones are matched (near matches
// and split shapes included), and every shape is matched again with them all, so a shape
// that matched already can take the face its neighbors found.
let mut extra: Vec<Arc<vectorcraft_text::FontFace>> = vec![];
for f in more {
if !cands.iter().chain(&extra).any(|k| k.id() == f.id()) {
extra.push(f);
}
}
if !extra.is_empty() {
// Near matching spends an index's comparison budget, so with a tolerance the
// candidates are indexed again for this pass.
let first = if tolerance > 0.0 { build(cands) } else { index };
let others: Vec<RetypeIndex> = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect();
let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect();
found = match_pieces(&pieces, &groups, &all, tolerance);
}
// The face most shapes match, so a glyph several fonts share is set in the same font as
// the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit
// them closest in all (the least leftover distance summed over those shapes), so every
@@ -1916,7 +2025,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
// for small blocks.
let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256);
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated)
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated, installed)
};
if lines.is_empty() {
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
@@ -2050,9 +2159,27 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
.collect::<Vec<_>>(),
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
"truncated": truncated,
"installed": installed.json(),
}))
}
/// The shapes of `pieces` that may become type and that `found` holds no part for, each with its
/// contour groups from `groups`.
fn left_shapes<'a>(pieces: &'a [Piece], groups: &'a [Vec<BezPath>], found: &[Vec<Vec<GlyphMatch>>]) -> Vec<installed::Sought<'a>> {
pieces
.iter()
.zip(groups)
.zip(found)
.filter(|((pc, _), parts)| !pc.keeps_outline && parts.is_empty())
.map(|((pc, g), _)| installed::Sought {
path: &pc.path,
groups: g,
fill: pc.filled.then_some(pc.nonzero),
once: paints_once(pc.opacity, pc.blend, &pc.appearance),
})
.collect()
}
#[cfg(test)]
#[path = "retype_tests.rs"]
mod tests;
+103 -45
View File
@@ -3,22 +3,25 @@
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>,
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html>).
//! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with
//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same
//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its
//! the glyphs of up to 96 loaded fonts, those of the document's live type first, and of the
//! installed fonts not loaded yet (`retype_installed.rs`), by the same matching as `type.retype`
//! (exact matches only). Of two versions of one font, only the version its
//! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many
//! of the shapes it matches, then by how closely, on average, and then by name. The query changes
//! nothing.
//! of the shapes it matches, then by how closely, on average, and then by name. The query does not
//! change the document; the installed fonts that match are loaded.
use std::collections::BTreeSet;
use std::sync::Arc;
use kurbo::BezPath;
use serde_json::{Value, json};
use vectorcraft_text::FontDb;
use vectorcraft_doc::Document;
use vectorcraft_text::retype::{RetypeIndex, shape_key};
use vectorcraft_text::{FontDb, FontFace};
use super::super::edit::selected_roots;
use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path};
use super::{candidate_faces, collect};
use super::super::{CommandSpec, Result, Session, bad, cmd, has_selected_path};
use super::installed::Installed;
use super::{candidate_faces, selected_pieces};
pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
@@ -26,7 +29,7 @@ pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
"Find Matching Fonts",
[],
None,
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
"{count?: 1..96 (default 10), installed?: bool} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed, and, unless installed is false (true, omitted or null: compared), with the installed fonts not loaded yet, within type.retype's limits on reading them (every file within them is read, and the fonts that match are loaded while the list holds fewer than 96 fonts, loaded ones included); of two versions of a font, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out), installed: {read, skipped} (as type.retype reports them)}; a count that is not a whole number from 1 to 96, or an installed that is not true, false or null, is an error",
has_selected_path,
retype_fonts
)]
@@ -38,7 +41,7 @@ pub(super) const DEFAULT_COUNT: usize = 10;
pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES;
/// One font that matched some of the shapes.
struct Ranked {
pub(super) struct Ranked {
face: Arc<vectorcraft_text::FontFace>,
/// How many shapes it matched.
matched: usize,
@@ -49,62 +52,99 @@ struct Ranked {
}
impl Ranked {
/// The font.
pub(super) fn face(&self) -> &Arc<FontFace> {
&self.face
}
fn mean(&self) -> f64 {
self.residual / self.matched.max(1) as f64
}
}
pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result<Value> {
retype_fonts_in(s, p, FontDb::global())
}
/// [`retype_fonts`] with the fonts of `db`.
fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
const C: &str = "type.retypeFonts";
let count = match p.get("count") {
None | Some(Value::Null) => DEFAULT_COUNT,
/// The `count` param: how many fonts to list.
pub(super) fn count_param(p: &Value) -> Result<usize> {
match p.get("count") {
None | Some(Value::Null) => Ok(DEFAULT_COUNT),
Some(v) => v
.as_u64()
.and_then(|n| usize::try_from(n).ok())
.filter(|n| (1..=MAX_COUNT).contains(n))
.ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?,
};
let roots = selected_roots(s)?;
let d = &s.doc()?.doc;
let mut pieces = vec![];
let (mut barrier, mut truncated) = (true, false);
for r in &roots {
if let Some(n) = d.node(*r) {
collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces);
}
.ok_or_else(|| bad("type.retypeFonts", "`count` must be a whole number from 1 to 96")),
}
if pieces.is_empty() {
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
}
// Only glyphs with a selected shape's key (segments per contour) can match one.
let wanted: BTreeSet<u64> = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect();
// A font is chosen by its family and style, which set the version the name gives: of two
// versions of one font, only that one is compared. The other versions do not take the places
// of fonts loaded after them.
let by_name = |f: &Arc<vectorcraft_text::FontFace>| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id());
let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect();
}
/// Is `f` the version of its font that its family and style name gives? A font is chosen by its
/// family and style, which set that version: of two versions of one font, only that one is
/// compared, and the other versions do not take the places of fonts loaded after them.
fn by_name(db: &FontDb, f: &FontFace) -> bool {
db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id())
}
/// The loaded faces the list compares: those of the document's live type first, then the other
/// loaded faces, each the version its name gives, at most [`MAX_COUNT`].
pub(super) fn listed_faces(db: &FontDb, d: &Document) -> Vec<Arc<FontFace>> {
let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(|f| by_name(db, f)).collect();
for f in db.loaded_faces() {
if faces.len() >= vectorcraft_text::retype::MAX_FACES {
if faces.len() >= MAX_COUNT {
break;
}
if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) {
if by_name(db, &f) && !faces.iter().any(|k| k.id() == f.id()) {
faces.push(f);
}
}
faces
}
/// The fonts of `faces` whose glyphs match `shapes`, unranked, and with `search_installed` those of
/// the installed fonts not loaded yet, for the places left of [`MAX_COUNT`] (loading the ones that
/// match), with what that search read. With `handed` (what a search made off the UI thread found,
/// [`super::installed::RetypeFound`]) its faces are ranked instead, and the installed fonts are not
/// read again.
pub(super) fn rank_fonts(
db: &FontDb,
faces: Vec<Arc<FontFace>>,
shapes: &[&BezPath],
search_installed: bool,
handed: Option<Installed>,
) -> Result<(Vec<Ranked>, Installed)> {
// Only glyphs with a selected shape's key (segments per contour) can match one.
let wanted: BTreeSet<u64> = shapes.iter().filter_map(|s| shape_key(s)).collect();
// No shape has a key: no font is read.
let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) };
// A shape's paint does not change which glyph it is: shapes that would stay outlines count too.
let mut ranked: Vec<Ranked> = vec![];
for pc in &pieces {
rank(&index, shapes, &mut ranked);
// The installed fonts not loaded yet: those whose glyphs match a shape, of the version their
// family and style name gives, up to 96 fonts listed in all. A font that matches only as
// combining marks is not listed, so it takes no place.
let room = MAX_COUNT.saturating_sub(ranked.iter().filter(|r| r.character).count());
let found = if let Some(handed) = handed {
handed
} else if !search_installed {
Installed::default()
} else if room == 0 {
// The list is full: the installed faces a search would compare count as skipped, none
// when no shape would start one.
let skipped = if super::installed::starts_search(shapes) { db.unloaded_installed_faces().len() } else { 0 };
Installed { skipped, ..Default::default() }
} else {
super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))?
};
// A face found earlier (handed in) may be loaded and ranked already: it counts once.
let more: Vec<_> = found.faces.iter().filter(|f| !ranked.iter().any(|r| r.face.id() == f.id())).cloned().collect();
if !more.is_empty() {
rank(&RetypeIndex::build(db, more, &wanted), shapes, &mut ranked);
}
Ok((ranked, found))
}
/// Adds to `ranked` the fonts of `index` that match `shapes`.
fn rank(index: &RetypeIndex, shapes: &[&BezPath], ranked: &mut Vec<Ranked>) {
for shape in shapes {
// A shape can fit several glyphs or poses of one font: it counts once for the font, at its
// closest fit.
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64, bool)> = vec![];
for m in index.all_matches(&pc.path) {
let mut best: Vec<(Arc<FontFace>, f64, bool)> = vec![];
for m in index.all_matches(shape) {
let character = !vectorcraft_text::retype::is_combining_mark(m.ch);
match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) {
Some(b) => {
@@ -125,6 +165,23 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
}
}
}
}
pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result<Value> {
retype_fonts_in(s, p, FontDb::global())
}
/// [`retype_fonts`] with the fonts of `db`.
fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
const C: &str = "type.retypeFonts";
let count = count_param(p)?;
let search_installed = super::installed::wanted(C, p)?;
let handed = super::installed::handed(s);
let (pieces, truncated) = selected_pieces(s)?;
let d = &s.doc()?.doc;
// A shape's paint does not change which glyph it is: shapes that would stay outlines count too.
let shapes: Vec<&BezPath> = pieces.iter().map(|pc| &pc.path).collect();
let (mut ranked, found) = rank_fonts(db, listed_faces(db, d), &shapes, search_installed, handed)?;
// A font whose glyphs match the shapes only as combining marks would retype none of them, as
// type.retype starts no line with a mark: it is not listed.
ranked.retain(|r| r.character);
@@ -143,6 +200,7 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
"shapes": pieces.len(),
"more": more,
"truncated": truncated,
"installed": found.json(),
}))
}
+60 -2
View File
@@ -99,7 +99,7 @@ fn shapes_that_are_no_glyph_list_no_font() {
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
let r = query(&mut s, json!({}), bundled());
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}}));
// Live type alone holds no shape to compare.
let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
@@ -113,7 +113,7 @@ fn a_font_that_matches_only_combining_marks_is_not_listed() {
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = query(&mut s, json!({}), bundled());
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}}));
// After a base, the mark counts with it.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
@@ -161,6 +161,64 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() {
assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}");
}
#[test]
fn installed_fonts_not_loaded_are_ranked_too_unless_left_out() {
use vectorcraft_text::test_fonts::named_copy;
let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed");
let file = dir.join("RetypeListed-Regular.ttf");
std::fs::write(&file, named_copy(true, ("Retype Listed", "Regular", "Version 1.000", "RetypeListed-Regular")).unwrap()).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
let mut s = session();
let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kgw", "size": 40, "font": "Inter", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [inter]})).unwrap();
// Left out: the installed copy is not read, and stays unloaded.
let r = query(&mut s, json!({"count": 96, "installed": false}), &db);
assert!(!names(&r).iter().any(|f| f.0 == "Retype Listed"), "{r}");
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed"));
// Compared: the copy of Inter matches every shape, as Inter does, and is loaded.
let r = query(&mut s, json!({"count": 96}), &db);
let fonts = names(&r);
assert!(fonts.contains(&("Retype Listed".to_string(), "Regular".to_string(), 3)), "{r}");
assert!(fonts.contains(&("Inter".to_string(), "Regular".to_string(), 3)), "{r}");
assert_eq!(r["installed"], json!({"read": 1, "skipped": 0}), "{r}");
assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed"));
}
#[test]
fn installed_fonts_fill_the_list_up_to_96_fonts_in_all() {
use vectorcraft_text::test_fonts::named_copy;
let copy = |family: &str| {
let postscript = format!("{}-Regular", family.replace(' ', ""));
(named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(), postscript)
};
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rg", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
// Loaded copies that match fill most of the list.
let loaded = FontDb::with_font_dirs(vec![]);
for i in 0..super::MAX_COUNT {
loaded.add_font(copy(&format!("Fullcopy {i:02}")).0);
}
let listed = names(&query(&mut s, json!({"count": 96, "installed": false}), &loaded)).len();
assert!(listed < super::MAX_COUNT, "{listed}");
// Installed copies, two more than the places left.
let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed-full");
for i in 0..super::MAX_COUNT - listed + 2 {
let (data, postscript) = copy(&format!("Installed {i:02}"));
std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap();
}
let db = FontDb::with_font_dirs(vec![dir]);
for i in 0..super::MAX_COUNT {
db.add_font(copy(&format!("Fullcopy {i:02}")).0);
}
let r = query(&mut s, json!({"count": 96}), &db);
assert_eq!(names(&r).len(), super::MAX_COUNT, "the installed copies fill the places left: {r}");
assert_eq!(r["more"], json!(false), "no font past the list is found: {r}");
assert_eq!(r["installed"]["skipped"], json!(2), "{r}");
assert_eq!(db.unloaded_installed_faces().len(), 2, "the two past the list stay unloaded");
}
#[test]
fn shapes_that_stay_outlines_still_name_their_font() {
// A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph.
+773
View File
@@ -0,0 +1,773 @@
//! Retype's installed fonts: the faces of installed fonts that nothing has loaded yet are
//! candidates too, as the fonts on the device are among the sources Retype suggests fonts from
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>).
//! Each font file is read for the search and let go; a face whose glyphs match a shape is loaded
//! as it was read, without the family's other files. Files are read smallest first, within a budget
//! of bytes read and glyphs drawn, and the search stops between files when it is canceled. The app
//! runs it off the UI thread ([`RetypeRun`]), with a Cancel. A face read is matched as a loaded one
//! is: with Retype's tolerance, near matches count, and a compound path of several glyphs counts
//! when every glyph it splits into matches, in one face or in several.
use std::collections::BTreeSet;
use std::sync::Arc;
use kurbo::BezPath;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId};
use vectorcraft_text::retype::{MAX_FACES, NearKey, RetypeIndex, encoded_glyphs, is_plain, shape_key};
use vectorcraft_text::{FontDb, FontFace};
use super::super::{EngineError, Result, Session, bad};
/// How much one search reads.
#[derive(Clone, Copy)]
struct Limits {
/// Font files (a suitcase font's resource fork) longer than this are not read.
file: u64,
/// The bytes of font files read, in all.
read: u64,
/// The glyphs of installed faces drawn, in all, to tell which can match a shape.
glyphs: usize,
/// The faces found: the faces after the last one found are not compared.
faces: usize,
}
const LIMITS: Limits = Limits { file: 256 << 20, read: 2 << 30, glyphs: 500_000, faces: MAX_FACES };
/// The `installed` param: whether to look in the installed fonts (default true).
pub(super) fn wanted(cmd: &str, p: &Value) -> Result<bool> {
match p.get("installed") {
None | Some(Value::Null) => Ok(true),
Some(Value::Bool(b)) => Ok(*b),
Some(_) => Err(bad(cmd, "`installed` must be true, false or null")),
}
}
/// What a search of the installed fonts found and read.
#[derive(Default)]
pub(super) struct Installed {
/// The faces whose glyphs match a shape, loaded now, in the order they were read.
pub(super) faces: Vec<Arc<FontFace>>,
/// Faces read and compared.
pub(super) read: usize,
/// Faces left out by the limits ([`LIMITS`]).
pub(super) skipped: usize,
/// For a search made away from its command, the ids of the loaded faces it compared: the
/// command does not compare them again.
pub(super) scanned: Vec<u32>,
}
impl Installed {
/// As a command's result reports it.
pub(super) fn json(&self) -> Value {
json!({"read": self.read, "skipped": self.skipped})
}
}
/// A shape to look for: its path, the contour groups it splits into when it may hold several
/// glyphs (none for a shape matched whole only), its fill rule when it has a visible fill
/// (`Some(nonzero)`) and whether it paints its overlaps once ([`super::paints_once`]), as
/// `type.retype` reads them.
#[derive(Clone, Copy)]
pub(super) struct Sought<'a> {
pub(super) path: &'a BezPath,
pub(super) groups: &'a [BezPath],
pub(super) fill: Option<bool>,
pub(super) once: bool,
}
impl<'a> Sought<'a> {
/// `path` split into `groups`, with no paint check.
pub(super) fn unpainted(path: &'a BezPath, groups: &'a [BezPath]) -> Self {
Sought { path, groups, fill: None, once: true }
}
}
/// `shapes`, each matched whole only.
fn whole<'a>(shapes: &[&'a BezPath]) -> Vec<Sought<'a>> {
shapes.iter().map(|path| Sought::unpainted(path, &[])).collect()
}
/// The keys to look glyphs up by for `shapes`, at `tolerance` ([`super::lookup_keys`]).
fn keys_of(shapes: &[Sought], tolerance: f64) -> (BTreeSet<u64>, Vec<NearKey>) {
super::lookup_keys(shapes.iter().map(|s| (s.path, s.groups)), tolerance)
}
/// Does a search look for `s`: is it not plain ([`is_plain`]: a rectangle, a triangle or a bar),
/// with a key to look glyphs up by? A shape without one matches no face.
fn starts(s: &Sought, tolerance: f64) -> bool {
if is_plain(s.path) {
return false;
}
let (keys, near) = keys_of(std::slice::from_ref(s), tolerance);
!keys.is_empty() || !near.is_empty()
}
/// Is `s` found in `indexes` at `tolerance`: does its whole shape match a glyph there, or does
/// every glyph it splits into, painting the area `s` paints ([`super::shape_parts`])?
fn found_in(indexes: &[&RetypeIndex], s: &Sought, tolerance: f64) -> bool {
!super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance).is_empty()
}
/// [`search_for`] of `shapes` matched whole, exactly.
#[cfg(test)]
pub(super) fn search(db: &FontDb, shapes: &[&BezPath], every: bool) -> Result<Installed> {
search_within(db, shapes, every, LIMITS, &|_| true)
}
/// [`search_beside`] with no loaded faces.
#[cfg(test)]
pub(super) fn search_for(db: &FontDb, shapes: &[Sought], tolerance: f64, every: bool) -> Result<Installed> {
search_beside(db, shapes, &[], tolerance, every)
}
/// The installed faces nothing has loaded that `shapes` that are not plain ([`is_plain`]) are found
/// in at `tolerance` ([`found_in`]), each loaded into `db` as it was read. With `every` false, a
/// face is found when it matches such a shape, or completes the glyphs of a split one with the
/// loaded faces of `loaded` (the indexes of faces the command compares too) and the faces found or
/// read before it (a face read before whose glyphs it completes is found with it), and the search
/// stops once each such shape is found; with it, every face within the limits ([`LIMITS`]) is
/// compared, and found when it matches a shape on its own. No file is read when every shape is
/// plain. At most [`MAX_FACES`] faces are found; the faces not compared past that count as skipped.
/// The faces of `loaded` whose glyphs complete a split shape with a face found are among the faces
/// found too, so the command compares them with it.
pub(super) fn search_beside(db: &FontDb, shapes: &[Sought], loaded: &[&RetypeIndex], tolerance: f64, every: bool) -> Result<Installed> {
search_sought(db, shapes, loaded, tolerance, every, LIMITS, &|_| true)
}
/// [`search`] comparing every face within the limits, for a list of at most `faces` faces: a face
/// found that `listed` turns down is loaded and not listed, and takes no place of the `faces`.
pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, listed: &dyn Fn(&FontFace) -> bool) -> Result<Installed> {
search_sought(db, &whole(shapes), &[], 0.0, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed)
}
/// Would a search for `shapes`, matched whole and exactly, read any installed file: is one of them
/// not plain, with a glyph's key ([`shape_key`])?
pub(super) fn starts_search(shapes: &[&BezPath]) -> bool {
shapes.iter().any(|s| !is_plain(s) && shape_key(s).is_some())
}
/// [`loaded_rest_for`] of `shapes` matched whole, exactly: the faces only.
#[cfg(test)]
pub(super) fn loaded_rest(db: &FontDb, shapes: &[&BezPath], compared: &[u32]) -> Result<Vec<Arc<FontFace>>> {
Ok(loaded_rest_for(db, &whole(shapes), &[], 0.0, compared)?.0)
}
/// The loaded faces that are not among `compared` (those past the [`MAX_FACES`] a Retype compares
/// first) that one of `shapes` that is not plain ([`is_plain`]) is found in at `tolerance`
/// ([`found_in`]), indexed [`MAX_FACES`] at a time: the faces of the glyphs it matches. The glyphs of
/// a split shape may be spread over those groups and the faces of `beside` (the indexes of faces
/// among `compared`). With them, whether each shape was found, and the indexes of the latest
/// groups that hold glyphs of the shapes while a split shape is not found (at most
/// [`MAX_KEPT_GROUPS`]), for the search of the installed fonts. A cancel stops it between those
/// groups.
pub(super) fn loaded_rest_for(db: &FontDb, shapes: &[Sought], beside: &[&RetypeIndex], tolerance: f64, compared: &[u32]) -> Result<LoadedRest> {
let mut done = vec![false; shapes.len()];
let looked: Vec<(usize, &Sought)> = shapes.iter().enumerate().filter(|(_, s)| !is_plain(s.path)).collect();
let (keys, near) = super::lookup_keys(looked.iter().map(|(_, s)| (s.path, s.groups)), tolerance);
let mut out: Vec<Arc<FontFace>> = vec![];
if keys.is_empty() && near.is_empty() {
return Ok((out, done, vec![]));
}
let rest: Vec<Arc<FontFace>> = db.loaded_faces().into_iter().filter(|f| !compared.contains(&f.id())).collect();
// The earlier groups' indexes that hold glyphs of the shapes, while a split shape is not found
// yet: the latest [`MAX_KEPT_GROUPS`].
let mut kept: Vec<RetypeIndex> = vec![];
for group in rest.chunks(MAX_FACES) {
vectorcraft_doc::cancel::check()?;
let index = RetypeIndex::build_near(db, group.iter().cloned(), &keys, &near);
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&kept).chain(std::iter::once(&index)).collect();
for (k, s) in &looked {
// A split shape not found yet is matched with the faces before the group too (one pass,
// as near matching spends an index's budget); any other shape with the group alone.
let combined = !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true);
let indexes: &[&RetypeIndex] = if combined { &with } else { &[&index] };
let parts = super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance);
if parts.is_empty() {
continue;
}
if let Some(d) = done.get_mut(*k) {
*d = true;
}
for m in parts.into_iter().flatten() {
if !compared.contains(&m.face.id()) && !out.iter().any(|f| f.id() == m.face.id()) {
out.push(m.face);
}
}
}
let open = looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true));
if open && !index.is_empty() {
// The latest groups are kept: the oldest goes when the cap is reached.
if kept.len() >= MAX_KEPT_GROUPS {
kept.remove(0);
}
kept.push(index);
}
}
if !looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)) {
kept.clear();
}
Ok((out, done, kept))
}
/// What [`loaded_rest_for`] finds: the faces, whether each shape was found, and the indexes kept
/// for the search of the installed fonts.
type LoadedRest = (Vec<Arc<FontFace>>, Vec<bool>, Vec<RetypeIndex>);
/// Earlier groups of [`MAX_FACES`] loaded faces past the ones compared first that a group's faces
/// complete a split shape's glyphs with, at most: the latest ones.
const MAX_KEPT_GROUPS: usize = 4;
/// An installed font file: its path, its length and the (family, style) of the faces wanted from it.
type File = (std::path::PathBuf, u64, Vec<(String, String)>);
/// [`search`] within `limits`, keeping in its faces only those `listed` accepts.
#[cfg(test)]
fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result<Installed> {
search_sought(db, &whole(shapes), &[], 0.0, every, limits, listed)
}
/// [`search_beside`] within `limits`, keeping in its faces only those `listed` accepts.
fn search_sought(
db: &FontDb,
shapes: &[Sought],
beside: &[&RetypeIndex],
tolerance: f64,
every: bool,
limits: Limits,
listed: &dyn Fn(&FontFace) -> bool,
) -> Result<Installed> {
let mut out = Installed::default();
// A shape without a glyph's key matches no face: the search does not wait for it.
let shapes: Vec<Sought> = shapes.iter().copied().filter(|s| starts(s, tolerance)).collect();
let (keys, near) = keys_of(&shapes, tolerance);
if keys.is_empty() && near.is_empty() {
return Ok(out);
}
let (keys, near) = (&keys, near.as_slice());
// The indexes of the faces found, which the glyphs of a split shape may be spread over.
let mut found: Vec<RetypeIndex> = vec![];
// The faces read, not loaded, that hold glyphs of the shapes without completing one, with their
// indexes: a later face may complete a split shape with them. The latest [`MAX_FACES`].
let mut partial: Vec<(Arc<FontFace>, RetypeIndex)> = vec![];
// The faces wanted from each file, smallest file first.
let mut files: Vec<File> = vec![];
let mut at: std::collections::HashMap<std::path::PathBuf, usize> = std::collections::HashMap::new();
for f in db.unloaded_installed_faces() {
match at.get(&f.path).and_then(|i| files.get_mut(*i)) {
Some(file) => file.2.push((f.family, f.style)),
None => {
at.insert(f.path.clone(), files.len());
files.push((f.path, f.len, vec![(f.family, f.style)]));
}
}
}
files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
let mut matched = vec![false; shapes.len()];
// Is a split shape not found yet: only then are faces kept in `partial`.
let open = |matched: &[bool]| shapes.iter().zip(matched).any(|(s, m)| !*m && !s.groups.is_empty());
let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs);
let total = files.len() as u64;
for (i, (path, len, styles)) in files.iter().enumerate() {
vectorcraft_doc::cancel::check()?;
vectorcraft_doc::cancel::progress(i as u64, total, "Retype: reading installed fonts");
// A file too long for what is left, or read when no glyph is left to draw, is not read.
if *len > limits.file || *len > bytes_left || glyphs_left == 0 {
out.skipped += styles.len();
continue;
}
// A file that grew since the scan is read only within what is left.
let file = db.read_unloaded_file(path, limits.file.min(bytes_left));
// The bytes read, those of a file that grew past the limits too.
bytes_left = bytes_left.saturating_sub(file.bytes);
if file.too_long {
out.skipped += styles.len();
continue;
}
let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style));
let faces: Vec<Arc<FontFace>> = file.faces.into_iter().filter(|f| wanted(f)).collect();
for (j, face) in faces.iter().enumerate() {
if out.faces.len() >= limits.faces {
// The faces not compared past the cap: the rest of this file's and the later files'.
out.skipped += styles.len().saturating_sub(j) + files.iter().skip(i + 1).map(|f| f.2.len()).sum::<usize>();
return Ok(out);
}
let n = encoded_glyphs(face);
if n > glyphs_left {
out.skipped += 1;
continue;
}
glyphs_left -= n;
out.read += 1;
let index = RetypeIndex::build_unloaded_near(db, face.clone(), keys, near);
if index.is_empty() {
continue;
}
// With `every`, a face fits a shape it matches on its own; otherwise a shape not found
// yet that it completes with the loaded faces of `beside`, the faces found before it and
// the faces read before it that hold some of its glyphs (`partial`).
let parts: Vec<&RetypeIndex> = partial.iter().map(|(_, ix)| ix).collect();
let parts_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| -> Vec<Vec<super::GlyphMatch>> {
let Some(s) = shapes.get(k) else { return vec![] };
if every {
return super::shape_parts(s.path, s.groups, s.fill, s.once, &[ix], tolerance);
}
if matched.get(k).copied().unwrap_or(true) {
return vec![];
}
// A shape matched whole only takes one glyph: the faces read before it do not hold it.
let extra = if s.groups.is_empty() { &[] } else { extra };
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(extra.iter().copied()).chain(std::iter::once(ix)).collect();
super::shape_parts(s.path, s.groups, s.fill, s.once, &with, tolerance)
};
let fit_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| !parts_with(extra, ix, k).is_empty();
let fit = |ix: &RetypeIndex, k: usize| fit_with(&parts, ix, k);
// Each shape it fits, with the glyphs it matches: one pass, as near matching spends an
// index's budget.
let first: Vec<(usize, Vec<Vec<super::GlyphMatch>>)> =
(0..shapes.len()).map(|k| (k, parts_with(&parts, &index, k))).filter(|(_, p)| !p.is_empty()).collect();
let fits: Vec<usize> = first.iter().map(|(k, _)| *k).collect();
if fits.is_empty() {
// The face holds glyphs of a shape without completing one: a later face may, while
// a split shape is not found. The latest are kept: the oldest goes when the cap is
// reached.
if !every && open(&matched) {
#[cfg(test)]
KEPT_PARTIAL.with(|n| n.set(n.get() + 1));
if partial.len() >= MAX_FACES {
partial.remove(0);
}
partial.push((face.clone(), index));
}
continue;
}
let loaded = load(db, face);
let same = loaded.id() == face.id();
let (mut fits, index) = still_fit(db, face, &loaded, index, keys, near, fits, &fit);
if fits.is_empty() {
continue;
}
// The faces read before whose glyphs the shapes it fits use, loaded with it: those
// that leave room under the cap, or else only the shapes it fits without them. A face
// loaded in place of the one read is matched again for them.
let matches: Vec<Vec<super::GlyphMatch>> = if same {
first.into_iter().flat_map(|(_, p)| p).collect()
} else {
fits.iter().flat_map(|k| parts_with(&parts, &index, *k)).collect()
};
let held: Vec<&Arc<FontFace>> = index.faces().iter().chain(found.iter().flat_map(|ix| ix.faces())).chain(&out.faces).collect();
let (mut used, mut with_loaded) = companions(&matches, &held, beside, &partial);
if out.faces.len() + used.len() + with_loaded.len() >= limits.faces {
let alone: Vec<&RetypeIndex> = found.iter().chain(std::iter::once(&index)).collect();
fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&alone, s, tolerance)));
used.clear();
with_loaded.clear();
if fits.is_empty() {
continue;
}
}
let mut shadowed = false;
let mut promoted: Vec<Arc<FontFace>> = vec![];
for at in used.into_iter().rev() {
let (read, ix) = partial.remove(at);
let loaded = load(db, &read);
let ix = if loaded.id() == read.id() {
ix
} else {
shadowed = true;
RetypeIndex::build_near(db, [loaded.clone()], keys, near)
};
promoted.insert(0, loaded);
found.push(ix);
}
// A face loaded in place of one read may have other glyphs: the shapes are checked again.
if shadowed {
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(std::iter::once(&index)).collect();
fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&with, s, tolerance)));
if fits.is_empty() {
continue;
}
}
// The faces it completes shapes with, once the match holds.
out.faces.extend(with_loaded);
for loaded in promoted {
if listed(&loaded) {
remember(db, &loaded);
if !out.faces.iter().any(|f| f.id() == loaded.id()) {
out.faces.push(loaded);
}
}
}
// A face `listed` turns down (another version shadows it) is not compared ahead of others.
if listed(&loaded) {
remember(db, &loaded);
if !out.faces.iter().any(|f| f.id() == loaded.id()) {
out.faces.push(loaded);
}
}
found.push(index);
for k in fits {
if let Some(m) = matched.get_mut(k) {
*m = true;
}
}
if !every && matched.iter().all(|m| *m) {
return Ok(out);
}
// With every split shape found, the faces kept for them are dropped.
if !open(&matched) {
partial.clear();
}
}
// The cap reached with the file's last face: the later files are not compared.
if out.faces.len() >= limits.faces {
out.skipped += files.iter().skip(i + 1).map(|f| f.2.len()).sum::<usize>();
return Ok(out);
}
}
Ok(out)
}
#[cfg(test)]
thread_local! {
/// How many times a search on this thread kept a face it read in `partial`.
static KEPT_PARTIAL: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// For each of `parts` (each part's candidates) that none of the faces of `held` has a glyph of,
/// one face that does: a loaded face of `beside` (the command compares it with the face found),
/// or else a face of `partial`, read before. The places in `partial` of those, in order, and the
/// loaded faces.
fn companions(
parts: &[Vec<super::GlyphMatch>],
held: &[&Arc<FontFace>],
beside: &[&RetypeIndex],
partial: &[(Arc<FontFace>, RetypeIndex)],
) -> (Vec<usize>, Vec<Arc<FontFace>>) {
let (mut used, mut loaded) = (BTreeSet::new(), Vec::<Arc<FontFace>>::new());
for part in parts {
let has = |f: &Arc<FontFace>| part.iter().any(|m| m.face.id() == f.id());
let chosen = used.iter().filter_map(|at: &usize| partial.get(*at).map(|(f, _)| f));
if held.iter().copied().chain(&loaded).chain(chosen).any(has) {
continue;
}
let of_beside = part.iter().find(|m| beside.iter().any(|ix| ix.faces().iter().any(|f| f.id() == m.face.id())));
if let Some(m) = of_beside {
loaded.push(m.face.clone());
} else if let Some(at) = part.iter().find_map(|m| partial.iter().position(|(f, _)| Arc::ptr_eq(f, &m.face))) {
used.insert(at);
}
}
(used.into_iter().collect(), loaded)
}
/// The faces searches loaded from installed files, by database ([`FontDb::id`]) and face id, the
/// latest first: at most [`MAX_FACES`].
static FOUND: std::sync::Mutex<Vec<(u64, u32)>> = std::sync::Mutex::new(Vec::new());
/// Keep `face`, which a search loaded into `db`, among [`found`]'s faces.
fn remember(db: &FontDb, face: &FontFace) {
let mut kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let at = (db.id(), face.id());
kept.retain(|k| *k != at);
kept.insert(0, at);
kept.truncate(MAX_FACES);
}
/// The faces of `db` that searches of the installed fonts found and loaded, the latest first. A
/// later Retype compares them ahead of the other loaded faces.
pub(super) fn found(db: &FontDb) -> Vec<Arc<FontFace>> {
let kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
kept.into_iter().filter(|(d, _)| *d == db.id()).filter_map(|(_, id)| db.face_by_id(id)).collect()
}
/// Of `fits` (the shapes `index`, the index of `read`, fits as `fit` tells), those that `loaded`,
/// the face loading `read` gave, fits too, with the index they fit in: all of them and `index`
/// when it is `read` itself. Another face of the same family, style and version, loaded from
/// another file, may have other glyphs; it is indexed by `keys` and `near`.
#[allow(clippy::too_many_arguments)]
fn still_fit(
db: &FontDb,
read: &FontFace,
loaded: &Arc<FontFace>,
index: RetypeIndex,
keys: &BTreeSet<u64>,
near: &[NearKey],
fits: Vec<usize>,
fit: &dyn Fn(&RetypeIndex, usize) -> bool,
) -> (Vec<usize>, RetypeIndex) {
if loaded.id() == read.id() {
return (fits, index);
}
let index = RetypeIndex::build_near(db, [loaded.clone()], keys, near);
let fits = fits.into_iter().filter(|k| fit(&index, *k)).collect();
(fits, index)
}
/// `face` (read from an installed file and not loaded) loaded into `db` as it was read
/// ([`FontDb::load_read_face`]): neither its file nor the family's other files are read again.
fn load(db: &FontDb, face: &Arc<FontFace>) -> Arc<FontFace> {
db.load_read_face(face.clone())
}
/// A search of the installed fonts made away from its command, so the app can run it off the UI
/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the document from the
/// session, checking the params as the command checks them; [`RetypeSearch::run`] picks the loaded
/// faces to compare, compares them and searches the installed fonts on any thread, loading the
/// faces that match; and
/// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with
/// [`RetypeRun::params`] and compares those faces as its own search would, without reading the
/// installed fonts again.
pub struct RetypeRun {
params: Value,
/// The document ([`crate::DocState::uid`]), its content and the selection the search is for.
doc: u64,
content: Arc<Document>,
selection: Vec<NodeId>,
search: Arc<RetypeSearch>,
}
/// What a [`RetypeRun`] compares and searches, without the session: it can be sent to another
/// thread ([`RetypeRun::search`]).
pub struct RetypeSearch {
command: &'static str,
/// The document it is for ([`crate::DocState::uid`]).
doc: u64,
/// The shapes to match, and the loaded faces they are compared with first.
shapes: Vec<Shape>,
faces: Faces,
/// `type.retype`'s tolerance (0 for `type.retypeFonts`).
tolerance: f64,
}
/// The loaded faces a [`RetypeSearch`] compares first.
enum Faces {
/// These faces.
#[cfg(test)]
Given(Vec<Arc<FontFace>>),
/// Those the command picks in `doc`: with `fonts` (`type.retype`'s `fonts` param), the faces of
/// those families and of the document's live type ([`super::candidate_faces`]), and without, the
/// faces `type.retypeFonts` lists ([`super::fonts::listed_faces`]). They are picked on the
/// search's thread, since a family not loaded yet is read from its files.
Of { doc: Arc<Document>, fonts: Option<Vec<String>> },
}
impl Faces {
fn get(&self, db: &FontDb) -> Vec<Arc<FontFace>> {
match self {
#[cfg(test)]
Faces::Given(faces) => faces.clone(),
Faces::Of { doc, fonts: Some(fonts) } => super::candidate_faces(db, doc, fonts),
Faces::Of { doc, fonts: None } => super::fonts::listed_faces(db, doc),
}
}
}
/// A shape a [`RetypeSearch`] compares, as `type.retype` matches it ([`super::shape_parts`]): its
/// path, its contour groups when it may hold several glyphs, its fill rule when it has a visible
/// fill (`Some(nonzero)`), and whether it paints its overlaps once ([`super::paints_once`]).
struct Shape {
path: BezPath,
groups: Vec<BezPath>,
fill: Option<bool>,
once: bool,
}
impl Shape {
/// `path`, matched whole, with no paint check.
fn whole(path: BezPath) -> Self {
Shape { path, groups: vec![], fill: None, once: true }
}
fn sought(&self) -> Sought<'_> {
Sought { path: &self.path, groups: &self.groups, fill: self.fill, once: self.once }
}
}
/// What a [`RetypeSearch`] found: for `type.retype`, the faces it compared first that match, the
/// loaded faces past those that match ([`loaded_rest`]), the installed faces whose glyphs match,
/// loaded, and the loaded faces it compared; and what it read of the installed fonts.
pub struct RetypeFound {
doc: u64,
installed: Installed,
}
impl RetypeFound {
/// Hand it to the next `type.retype` or `type.retypeFonts`, which compares the faces found as
/// its own search of the installed fonts would, in the document the search was made for. Any
/// such command takes it; one in another document compares only what is loaded.
pub fn hand_in(self, s: &mut Session) {
s.retype_hand_off = Some(self);
}
/// Drop what was handed in and no command took, as when the command failed before it took
/// it: a later command searches for itself.
pub fn drop_handed(s: &mut Session) {
s.retype_hand_off = None;
}
/// What it read, as the commands report it.
pub fn json(&self) -> Value {
self.installed.json()
}
}
/// What a search found for the active document of `s`, handed in for this command ([`RetypeFound`]).
/// It is taken whatever the document, so it is used once.
pub(super) fn handed(s: &mut Session) -> Option<Installed> {
let found = s.retype_hand_off.take()?;
let doc = s.doc().ok()?.uid;
(found.doc == doc).then_some(found.installed)
}
impl RetypeRun {
/// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the
/// active document. None when it reads no installed font: `installed` is false, or no shape
/// starts a search ([`starts`]: each is plain or has no glyph's key). An error where the command fails on its params or on the selection.
/// The faces to compare are picked when the search runs.
pub fn prepare(s: &Session, command: &str, p: &Value) -> Result<Option<RetypeRun>> {
let (command, fonts, tolerance) = match command {
"type.retype" => ("type.retype", Some(super::fonts_param(p)?), super::tolerance_param(p)?),
"type.retypeFonts" => {
super::fonts::count_param(p)?;
("type.retypeFonts", None, 0.0)
}
other => return Err(EngineError::Other(format!("`{other}` doesn't search the installed fonts"))),
};
// The keys the command refuses (an unknown one) fail here too, before any search.
s.check_params(command, p)?;
if !wanted(command, p)? {
return Ok(None);
}
let (pieces, _) = super::selected_pieces(s)?;
let st = s.doc()?;
// Retype compares the shapes that may become type, split as it splits them; the list
// compares every shape whole.
let shapes: Vec<Shape> = if fonts.is_some() {
let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS;
pieces
.into_iter()
.filter(|pc| !pc.keeps_outline)
.map(|pc| Shape {
groups: super::split_groups(&pc.path, &mut budget),
fill: pc.filled.then_some(pc.nonzero),
once: super::paints_once(pc.opacity, pc.blend, &pc.appearance),
path: pc.path,
})
.collect()
} else {
pieces.into_iter().map(|pc| Shape::whole(pc.path)).collect()
};
if !shapes.iter().any(|s| starts(&s.sought(), tolerance)) {
return Ok(None);
}
let faces = Faces::Of { doc: st.doc.clone(), fonts };
Ok(Some(RetypeRun {
params: p.clone(),
doc: st.uid,
content: st.doc.clone(),
selection: st.selection.objects.clone(),
search: Arc::new(RetypeSearch { command, doc: st.uid, shapes, faces, tolerance }),
}))
}
/// `type.retype` or `type.retypeFonts`.
pub fn command(&self) -> &'static str {
self.search.command
}
/// What it compares and searches, for another thread.
pub fn search(&self) -> Arc<RetypeSearch> {
self.search.clone()
}
/// The command's params: those it was prepared with.
pub fn params(&self) -> &Value {
&self.params
}
/// Does it still apply: is the document it was prepared in active, with the same content and
/// the same objects selected?
pub fn current(&self, s: &Session) -> bool {
s.doc().is_ok_and(|st| st.uid == self.doc && Arc::ptr_eq(&st.doc, &self.content) && st.selection.objects == self.selection)
}
/// [`RetypeSearch::run`] with the fonts of `db`.
#[cfg(test)]
fn run_in(&self, db: &FontDb) -> Result<RetypeFound> {
self.search.run_in(db)
}
}
impl RetypeSearch {
/// Compare the shapes with the loaded faces, then search the installed fonts as the command
/// would, loading the faces that match → what it found ([`EngineError::Cancelled`] when a
/// cancel stopped it). It touches no document, so it can run on any thread.
pub fn run(&self) -> Result<RetypeFound> {
self.run_in(FontDb::global())
}
/// [`RetypeSearch::run`] with the fonts of `db`.
fn run_in(&self, db: &FontDb) -> Result<RetypeFound> {
let picked = self.faces.get(db);
let installed = if self.command == "type.retypeFonts" {
let shapes: Vec<&BezPath> = self.shapes.iter().map(|s| &s.path).collect();
let (ranked, mut found) = super::fonts::rank_fonts(db, picked, &shapes, true, None)?;
// The loaded faces that match are handed in too, ahead of the installed ones found:
// loading those can move a loaded face past the 96 the command lists.
let mut faces: Vec<Arc<FontFace>> = ranked.iter().map(|r| r.face().clone()).collect();
for f in std::mem::take(&mut found.faces) {
if !faces.iter().any(|k| k.id() == f.id()) {
faces.push(f);
}
}
found.faces = faces;
found
} else {
// The shapes are matched as the command matches them first.
let tolerance = self.tolerance;
let sought: Vec<Sought> = self.shapes.iter().map(Shape::sought).collect();
let (keys, near) = keys_of(&sought, tolerance);
let index = RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near);
let parts: Vec<Vec<Vec<super::GlyphMatch>>> =
self.shapes.iter().map(|s| super::shape_parts(&s.path, &s.groups, s.fill, s.once, &[&index], tolerance)).collect();
let left: Vec<Sought> = sought.iter().zip(&parts).filter(|(_, p)| p.is_empty()).map(|(s, _)| *s).collect();
// The first faces that match are handed in too: loading the faces found can move one
// past the first 96 the command compares.
let mut first: Vec<Arc<FontFace>> = vec![];
for m in parts.into_iter().flatten().flatten() {
if !first.iter().any(|f| f.id() == m.face.id()) {
first.push(m.face);
}
}
// The loaded faces past the ones compared first, then the installed fonts for what
// none of them matches; the command takes both from what is handed in.
let compared: Vec<u32> = picked.iter().map(|f| f.id()).collect();
// Every face loaded now is compared, among the first ones or with the rest.
let scanned: Vec<u32> = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect();
// A split shape's glyphs may be spread over the faces compared first and the others.
// Near matching spends an index's comparison budget, so with a tolerance the faces
// compared first are indexed again for each search that has a split shape to look for.
let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near));
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
let (rest, done, kept) = loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?;
let left: Vec<Sought> = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect();
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
let kept: Vec<RetypeIndex> = if tolerance > 0.0 {
kept.iter().map(|ix| RetypeIndex::build_near(db, ix.faces().iter().cloned(), &keys, &near)).collect()
} else {
kept
};
let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect();
let mut found = search_beside(db, &left, &beside, tolerance, false)?;
found.faces.splice(0..0, first.into_iter().chain(rest));
found.scanned = scanned;
found
};
Ok(RetypeFound { doc: self.doc, installed })
}
}
#[cfg(test)]
#[path = "retype_installed_tests.rs"]
mod tests;
@@ -0,0 +1,833 @@
use std::collections::BTreeSet;
use std::path::PathBuf;
use kurbo::{Affine, BezPath, Shape};
use serde_json::json;
use vectorcraft_text::FontDb;
use vectorcraft_text::retype::shape_key;
use super::{Limits, search, search_within};
use crate::Session;
/// A database whose installed fonts are copies of the bundled Source Sans 3 Regular named
/// `families`, one file each, in a folder of their own: they are installed and not loaded.
/// Returns the database and the files.
fn installed(tag: &str, families: &[&str]) -> (FontDb, Vec<PathBuf>) {
let dir = vectorcraft_testkit::temp_dir(&format!("retype-installed-{tag}"));
let mut files = vec![];
for family in families {
let postscript = format!("{}-Regular", family.replace(' ', ""));
let data = vectorcraft_text::test_fonts::named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap();
let path = dir.join(format!("{postscript}.ttf"));
std::fs::write(&path, data).unwrap();
files.push(path);
}
(FontDb::with_font_dirs(vec![dir]), files)
}
/// The glyphs of `text` in the bundled Source Sans 3 Regular, as outlines at 30 pt.
fn glyphs(db: &FontDb, text: &str) -> Vec<BezPath> {
let face = db.face("Source Sans 3", "Regular").unwrap();
text.chars()
.enumerate()
.map(|(i, c)| Affine::translate((40.0 + 30.0 * i as f64, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for(c)))
.collect()
}
fn keys(shapes: &[BezPath]) -> BTreeSet<u64> {
shapes.iter().filter_map(shape_key).collect()
}
/// `paths` as a search compares them, each matched whole.
fn whole(paths: Vec<BezPath>) -> Vec<super::Shape> {
paths.into_iter().map(super::Shape::whole).collect()
}
fn unloaded(db: &FontDb, family: &str) -> bool {
db.unloaded_installed_faces().iter().any(|f| f.family == family)
}
#[test]
fn an_installed_face_whose_glyphs_match_is_found_and_loaded() {
let (db, files) = installed("found", &["Retype Copy A"]);
assert!(unloaded(&db, "Retype Copy A"));
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.skipped), (1, 0));
let face = found.faces.first().expect("the installed copy matches");
assert_eq!((face.family.as_str(), face.style.as_str()), ("Retype Copy A", "Regular"));
assert_eq!(face.path(), Some(files[0].as_path()));
// Loaded now, as it was read.
assert!(db.loaded_faces().iter().any(|f| f.id() == face.id()));
assert!(!unloaded(&db, "Retype Copy A"));
assert_eq!(found.json(), json!({"read": 1, "skipped": 0}));
// A later Retype compares it ahead of the other loaded faces, however many are loaded.
assert_eq!(super::found(&db).first().map(|f| f.id()), Some(face.id()));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let candidates = super::super::candidate_faces(&db, &s.doc().unwrap().doc, &[]);
assert_eq!(candidates.first().map(|f| f.id()), Some(face.id()));
// Only this database's faces.
assert!(super::found(&FontDb::with_font_dirs(vec![])).is_empty());
}
#[test]
fn a_matching_face_loads_without_the_family_s_other_files() {
let dir = vectorcraft_testkit::temp_dir("retype-installed-family");
for style in ["Regular", "Bold"] {
let data =
vectorcraft_text::test_fonts::named_copy(false, ("Retype Copy N", style, "Version 1.000", &format!("RetypeCopyN-{style}"))).unwrap();
std::fs::write(dir.join(format!("RetypeCopyN-{style}.ttf")), data).unwrap();
}
let db = FontDb::with_font_dirs(vec![dir]);
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 1));
let style = found.faces[0].style.clone();
let loaded: Vec<String> = db.loaded_faces().iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style.clone()).collect();
assert_eq!(loaded, std::slice::from_ref(&style), "only the face that matched is loaded");
let left: Vec<String> = db.unloaded_installed_faces().into_iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style).collect();
assert_eq!(left.len(), 1);
assert_ne!(left[0], style);
}
#[test]
fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() {
use vectorcraft_text::test_fonts::named_copy;
let names = ("Retype Twin", "Regular", "Version 1.000", "RetypeTwin-Regular");
let db = FontDb::with_font_dirs(vec![]);
// Inter's glyphs, loaded under the names a file of Source Sans 3's glyphs has too.
db.add_font(named_copy(true, names).unwrap());
let dir = vectorcraft_testkit::temp_dir("retype-installed-twin");
let path = dir.join("RetypeTwin-Regular.ttf");
std::fs::write(&path, named_copy(false, names).unwrap()).unwrap();
let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap();
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
let keys = keys(&shapes);
let loaded = super::load(&db, &read);
assert_ne!(loaded.id(), read.id(), "the face loaded first is kept");
let fit = |ix: &super::super::RetypeIndex, k: usize| !ix.matches(refs[k]).is_empty();
let index = || super::super::RetypeIndex::build_unloaded(&db, read.clone(), &keys);
let (fits, _) = super::still_fit(&db, &read, &loaded, index(), &keys, &[], vec![0, 1], &fit);
assert!(fits.is_empty(), "Inter's R and x are not these");
let (fits, _) = super::still_fit(&db, &read, &read, index(), &keys, &[], vec![0, 1], &fit);
assert_eq!(fits, [0, 1]);
}
#[test]
fn an_installed_face_no_shape_matches_is_read_and_not_loaded() {
let (db, _) = installed("none", &["Retype Copy B"]);
let shapes = [kurbo::Circle::new((40.0, 40.0), 20.0).to_path(0.1)];
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 0));
assert!(unloaded(&db, "Retype Copy B"), "a face that matches nothing stays unloaded");
// No shape: no file is read.
let none = search(&db, &[], false).unwrap();
assert_eq!((none.read, none.skipped), (0, 0));
}
#[test]
fn plain_shapes_alone_read_no_installed_font() {
// A hyphen is a bar: many fonts have a glyph of its shape, so it tells no font apart.
let (db, _) = installed("plain", &["Retype Copy L"]);
let mut shapes = glyphs(&db, "-");
shapes.push(kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1));
assert!(shapes.iter().all(vectorcraft_text::retype::is_plain));
let refs: Vec<&BezPath> = shapes.iter().collect();
for every in [false, true] {
let found = search(&db, &refs, every).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (0, 0, 0));
}
assert!(unloaded(&db, "Retype Copy L"));
// Beside a shape that is not plain, the search reads the file for that shape.
shapes.extend(glyphs(&db, "q"));
let refs: Vec<&BezPath> = shapes.iter().collect();
assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1);
}
#[test]
fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() {
let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]);
let mut shapes = glyphs(&db, "k");
// More contours than any glyph's key counts: no face can match it.
let mut dots = BezPath::new();
for i in 0..49 {
dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1));
}
assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots));
shapes.push(dots);
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read");
}
#[test]
fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() {
let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]);
let shapes = glyphs(&db, "ab");
let refs: Vec<&BezPath> = shapes.iter().collect();
let first = search(&db, &refs, false).unwrap();
assert_eq!((first.read, first.faces.len()), (1, 1), "the second file is not read");
let (db, _) = installed("every-all", &["Retype Copy E", "Retype Copy F"]);
let all = search(&db, &refs, true).unwrap();
assert_eq!((all.read, all.faces.len()), (2, 2));
let mut families: Vec<&str> = all.faces.iter().map(|f| f.family.as_str()).collect();
families.sort_unstable();
assert_eq!(families, ["Retype Copy E", "Retype Copy F"]);
}
#[test]
fn faces_read_are_kept_for_split_shapes_only() {
let (db, _) = installed("kept-whole", &["Retype Kept Whole A", "Retype Kept Whole B", "Retype Kept Whole C"]);
// The k matches in the first file and the circle in none, so every file is read; the later
// files hold the k's glyph without completing a shape. With every shape whole, none is kept.
let mut shapes = glyphs(&db, "k");
shapes.push(kurbo::Circle::new((300.0, 100.0), 7.3).to_path(0.1));
assert!(shape_key(&shapes[1]).is_some(), "the circle has a key to look glyphs up by");
let refs: Vec<&BezPath> = shapes.iter().collect();
super::KEPT_PARTIAL.with(|n| n.set(0));
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (3, 1));
assert_eq!(super::KEPT_PARTIAL.with(std::cell::Cell::get), 0, "no face read is kept");
}
#[test]
fn faces_past_the_limits_are_skipped_and_counted() {
let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
let len = files.iter().map(|f| std::fs::metadata(f).unwrap().len()).max().unwrap();
// Files longer than the limit for one file.
let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: usize::MAX, faces: usize::MAX };
let all = |_: &vectorcraft_text::FontFace| true;
let small = search_within(&db, &refs, true, Limits { file: len / 2, ..open }, &all).unwrap();
assert_eq!((small.read, small.skipped, small.faces.len()), (0, 2, 0));
// Bytes for one file only.
let one = search_within(&db, &refs, true, Limits { read: len + len / 2, ..open }, &all).unwrap();
assert_eq!((one.read, one.skipped, one.faces.len()), (1, 1, 1));
// Glyphs for no face.
let (db, _) = installed("limits-glyphs", &["Retype Copy I"]);
let few = search_within(&db, &refs, true, Limits { glyphs: 10, ..open }, &all).unwrap();
assert_eq!((few.read, few.skipped, few.faces.len()), (0, 1, 0));
assert!(unloaded(&db, "Retype Copy I"));
// Faces found up to the cap: the faces after it are not compared, and count as skipped.
let (db, _) = installed("limits-faces", &["Retype Copy O", "Retype Copy P", "Retype Copy Q"]);
let capped = search_within(&db, &refs, true, Limits { faces: 1, ..open }, &all).unwrap();
assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1));
}
#[test]
fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() {
let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
// The order the search reads them in: smallest first.
let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len();
files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b)));
let (first, second) = (len(&files[0]), len(&files[1]));
let grown = files[0].clone();
// The first file grows past the limit for one file as its reading starts, after the listing.
let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| {
if done == 0 {
let mut data = std::fs::read(&grown).unwrap();
data.resize(data.len() + second as usize + 1, 0);
std::fs::write(&grown, data).unwrap();
}
});
// Bytes for both files as listed: the grown file's reading takes one more than the limit for
// one file, which leaves too little for the second.
let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX };
let token = vectorcraft_doc::cancel::CancelToken::new();
let all = |_: &vectorcraft_text::FontFace| true;
let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0));
}
#[test]
fn the_glyph_budget_counts_the_glyphs_drawn() {
let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap();
let mapped = face.mapped_chars().len();
let drawn = vectorcraft_text::retype::encoded_glyphs(&face);
assert!(drawn < mapped, "{drawn} of {mapped}");
// A budget below the face's characters and at the glyphs drawn: the face is compared.
let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX };
let found = search_within(&db, &refs, true, open, &|_| true).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1));
}
#[test]
fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() {
let (db, _) = installed("list-run", &["Retype Copy List"]);
db.add_font(
vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(),
);
let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect();
let search = super::RetypeSearch {
command: "type.retypeFonts",
doc: 1,
shapes: whole(glyphs(&db, "Rx")),
faces: super::Faces::Given(loaded.clone()),
tolerance: 0.0,
};
let found = search.run_in(&db).unwrap();
let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect();
// The loaded face first, then the installed one, each once.
assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]);
assert_eq!((found.installed.read, found.installed.skipped), (1, 0));
}
#[test]
fn faces_a_list_turns_down_are_loaded_and_take_no_place() {
let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
// Two places, and the first face found is turned down: the next two are listed.
let found = super::search_listed(&db, &refs, 2, &|f| f.family != "Retype Copy R").unwrap();
let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
families.sort_unstable();
assert_eq!(families, ["Retype Copy S", "Retype Copy T"]);
assert_eq!((found.read, found.skipped), (3, 0));
assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded");
// Only the faces listed are compared ahead of the other loaded faces later.
let ahead: Vec<String> = super::found(&db).iter().map(|f| f.family.clone()).collect();
assert!(ahead.iter().any(|f| f == "Retype Copy S") && !ahead.iter().any(|f| f == "Retype Copy R"), "{ahead:?}");
}
#[test]
fn a_cancel_stops_the_search_between_files() {
let (db, _) = installed("cancel-between", &["Retype Copy U", "Retype Copy V", "Retype Copy W"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
let token = vectorcraft_doc::cancel::CancelToken::new();
let stop = token.clone();
// The cancel comes as the second file starts: it is read, the third is not.
let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| {
if done == 1 {
stop.cancel();
}
});
let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || search(&db, &refs, true));
assert!(matches!(r, Err(crate::EngineError::Cancelled)));
let left = ["Retype Copy U", "Retype Copy V", "Retype Copy W"].iter().filter(|f| unloaded(&db, f)).count();
assert_eq!(left, 1, "two files were read and loaded, the third was not");
}
#[test]
fn a_run_away_from_the_command_loads_the_faces_it_finds() {
let (db, _) = installed("run", &["Retype Copy X"]);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let ids: Vec<u64> =
glyphs(&db, "Wk").iter().map(|p| s.execute("path.create", &json!({"d": p.to_svg()})).unwrap()["id"].as_u64().unwrap()).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
// Off: nothing to run.
for cmd in ["type.retype", "type.retypeFonts"] {
assert!(super::RetypeRun::prepare(&s, cmd, &json!({"installed": false})).unwrap().is_none());
}
// The command's params are checked as it checks them.
assert!(super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 0})).is_err());
assert!(super::RetypeRun::prepare(&s, "type.retype", &json!({"fonts": 1})).is_err());
assert!(super::RetypeRun::prepare(&s, "type.text", &json!({})).is_err());
// An unknown key fails before any search, as the command fails on it.
for cmd in ["type.retype", "type.retypeFonts"] {
let e = super::RetypeRun::prepare(&s, cmd, &json!({"typo": true})).err().map(|e| e.to_string()).unwrap_or_default();
assert!(e.contains("typo"), "{cmd}: {e}");
assert!(s.execute(cmd, &json!({"typo": true})).is_err());
}
// Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read.
let run = super::RetypeRun::prepare(&s, "type.retype", &json!({})).unwrap().unwrap();
assert_eq!(run.command(), "type.retype");
assert_eq!(run.params(), &json!({}));
assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0}));
assert!(unloaded(&db, "Retype Copy X"));
// The list compares every installed face: the copy is read and loaded.
let run = super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 5})).unwrap().unwrap();
assert_eq!(run.params(), &json!({"count": 5}));
assert!(run.current(&s));
let found = run.run_in(&db).unwrap();
assert_eq!(found.json(), json!({"read": 1, "skipped": 0}));
// The loaded faces that match are handed in with it, ahead of it.
let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}");
assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}");
assert!(families.contains(&"Source Sans 3"), "{families:?}");
assert!(!unloaded(&db, "Retype Copy X"));
// A change of selection or content: it no longer applies.
s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap();
assert!(!run.current(&s));
s.execute("select.set", &json!({"ids": ids})).unwrap();
assert!(run.current(&s));
s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap();
assert!(!run.current(&s));
}
#[test]
fn plain_shapes_alone_start_no_run_away_from_the_command() {
// A rectangle and a bar are plain: the search reads no installed font for them, so the
// command runs at once.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
let bar = s.execute("shape.rectangle", &json!({"x": 10, "y": 100, "width": 4, "height": 60})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [rect, bar]})).unwrap();
for (cmd, p) in [("type.retype", json!({})), ("type.retype", json!({"tolerance": 0.05})), ("type.retypeFonts", json!({}))] {
assert!(super::RetypeRun::prepare(&s, cmd, &p).unwrap().is_none(), "{cmd} {p}");
}
}
#[test]
fn what_a_search_found_is_handed_to_the_next_command_in_its_document() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let uid = s.doc().unwrap().uid;
let handed = |doc| super::RetypeFound { doc, installed: super::Installed { read: 7, skipped: 3, ..Default::default() } };
// Taken instead of a search of the installed fonts, also with installed false.
handed(uid).hand_in(&mut s);
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
assert_eq!(r["installed"], json!({"read": 7, "skipped": 3}), "{r}");
// Used once.
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
// Another document's is dropped.
handed(uid + 1).hand_in(&mut s);
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
assert!(s.retype_hand_off.is_none(), "taken");
// Retype takes it too, whether or not a loaded font matches the rectangle.
handed(uid).hand_in(&mut s);
let _ = s.execute("type.retype", &json!({"installed": false}));
assert!(s.retype_hand_off.is_none());
}
#[test]
fn a_canceled_search_stops_before_reading_a_file() {
let (db, _) = installed("cancel", &["Retype Copy J"]);
let shapes = glyphs(&db, "z");
let refs: Vec<&BezPath> = shapes.iter().collect();
let token = vectorcraft_doc::cancel::CancelToken::new();
token.cancel();
let r = vectorcraft_doc::cancel::scope(&token, None, || search(&db, &refs, false));
assert!(matches!(r, Err(crate::EngineError::Cancelled)));
assert!(unloaded(&db, "Retype Copy J"), "nothing was loaded");
}
/// The shapes of `text` set in Source Sans 3 and outlined, as `type.retype` collects them.
fn pieces(text: &str) -> Vec<super::super::Piece> {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let id =
s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let d = &s.doc().unwrap().doc;
let node = d.node(vectorcraft_doc::NodeId(group)).unwrap();
let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]);
super::super::collect(node, None, 0, &mut barrier, &mut truncated, &mut pieces);
pieces
}
#[test]
fn retype_fills_the_shapes_no_loaded_font_matches_from_the_installed_fonts() {
let (db, _) = installed("retype", &["Retype Copy K"]);
let pieces = pieces("Wk-");
assert_eq!(pieces.len(), 3);
let groups = vec![vec![]; pieces.len()];
// The first shape is taken as matched already: the others are looked for.
let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()]));
let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0);
assert!(!found[0].is_empty() && found[1].is_empty() && found[2].is_empty());
let left = super::super::left_shapes(&pieces, &groups, &found);
assert_eq!(left.len(), 2);
let installed = super::search_for(&db, &left, 0.0, false).unwrap();
assert_eq!(installed.read, 1);
// The faces found join the index, and every shape is matched again.
let all_keys = keys(&pieces.iter().map(|pc| pc.path.clone()).collect::<Vec<_>>());
let extra = super::super::RetypeIndex::build(&db, installed.faces.iter().cloned(), &all_keys);
let found = super::super::match_pieces(&pieces, &groups, &[&keep, &extra], 0.0);
let whole = |k: usize| found[k].first().expect("one part").clone();
assert_eq!(whole(0).first().map(|m| m.face.family.as_str()), Some("Source Sans 3"), "a matched shape keeps its match");
// and gets the face found too, so its line can be set in the face the others match.
assert!(whole(0).iter().any(|m| m.face.family == "Retype Copy K" && m.ch == 'W'), "the W also matches the face found");
let k = whole(1);
let m = k.first().expect("the installed copy matches the k");
assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", 'k'));
assert!(db.loaded_faces().iter().any(|f| f.id() == m.face.id()), "the match is in a loaded face");
// The hyphen, a plain shape, matches the font the k found.
let hyphen = whole(2);
let m = hyphen.first().expect("the installed copy matches the hyphen");
assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", '-'));
}
/// `path` flattened into lines `tol` from its curves, each contour started at its second point
/// and run backwards: an outline built nothing like the font's.
fn simplified(path: &BezPath, tol: f64) -> BezPath {
let mut contours: Vec<Vec<kurbo::Point>> = vec![];
kurbo::flatten(path.iter(), tol, |el| match el {
kurbo::PathEl::MoveTo(q) => contours.push(vec![q]),
kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q),
_ => {}
});
let mut out = BezPath::new();
for mut c in contours {
if c.len() > 1 && c.first() == c.last() {
c.pop();
}
c.rotate_left(1);
c.reverse();
out.move_to(c[0]);
for q in &c[1..] {
out.line_to(*q);
}
out.close_path();
}
out
}
#[test]
fn an_installed_face_is_found_through_the_glyphs_of_a_split_shape_and_through_near_matches() {
// A word outlined as one compound path: the whole shape is no glyph, and its glyphs are.
let (db, _) = installed("split", &["Retype Copy Split"]);
let mut word = BezPath::new();
for g in glyphs(&db, "Wk") {
word.extend(g.iter());
}
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
assert_eq!(found.read, 1);
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Retype Copy Split"], "the face the split's glyphs match is found");
assert!(!unloaded(&db, "Retype Copy Split"));
// A simplified outline: no installed glyph matches it exactly, and one does within a tolerance.
let (db, _) = installed("near", &["Retype Copy Near"]);
let r = simplified(&glyphs(&db, "R")[0], 0.05);
let shape = [super::Sought::unpainted(&r, &[])];
let exact = super::search_for(&db, &shape, 0.0, false).unwrap();
assert_eq!((exact.read, exact.faces.len()), (1, 0));
assert!(unloaded(&db, "Retype Copy Near"));
let near = super::search_for(&db, &shape, 0.02, false).unwrap();
let families: Vec<&str> = near.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Retype Copy Near"], "the face the outline nearly matches is found");
assert!(!unloaded(&db, "Retype Copy Near"));
}
#[test]
fn a_split_shape_whose_glyphs_are_in_different_installed_faces_finds_them_all() {
// A W of Source Sans 3 and a k of Inter, outlined as one compound path, with a copy of each
// font installed: neither face holds both glyphs.
let dir = vectorcraft_testkit::temp_dir("retype-installed-split-two");
for (inter, family) in [(false, "Retype Mix S"), (true, "Retype Mix I")] {
let postscript = format!("{}-Regular", family.replace(' ', ""));
let data = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", "Version 1.000", &postscript)).unwrap();
std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap();
}
let db = FontDb::with_font_dirs(vec![dir]);
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
assert_eq!(found.read, 2);
let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
families.sort_unstable();
assert_eq!(families, ["Retype Mix I", "Retype Mix S"], "the faces of both glyphs are found");
assert!(!unloaded(&db, "Retype Mix S") && !unloaded(&db, "Retype Mix I"));
}
#[test]
fn a_split_shape_completes_with_the_loaded_faces_it_is_searched_beside() {
// A W of Source Sans 3 and a k of Inter, outlined as one compound path. Source Sans 3 is the
// loaded face compared first; the only other face is an installed copy of Inter.
let dir = vectorcraft_testkit::temp_dir("retype-installed-beside");
let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Beside I", "Regular", "Version 1.000", "RetypeBesideI-Regular")).unwrap();
std::fs::write(dir.join("RetypeBesideI-Regular.ttf"), data).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let shapes = [super::Sought::unpainted(&word, &groups)];
let (keys, near) = super::keys_of(&shapes, 0.0);
let first = super::super::RetypeIndex::build_near(&db, db.face("Source Sans 3", "Regular"), &keys, &near);
let found = super::search_beside(&db, &shapes, &[&first], 0.0, false).unwrap();
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Source Sans 3", "Retype Beside I"], "the installed face completes the loaded face's glyphs");
}
#[test]
fn one_loaded_face_per_glyph_completes_a_split_shape_however_many_hold_it() {
// A W of Source Sans 3 and a k of Inter in one compound path. More loaded copies of Source
// Sans 3 than a search finds faces hold the W; an installed copy of Inter holds the k.
let n = vectorcraft_text::retype::MAX_FACES + 4;
let dir = vectorcraft_testkit::temp_dir("retype-installed-many");
let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Many I", "Regular", "Version 1.000", "RetypeManyI-Regular")).unwrap();
std::fs::write(dir.join("RetypeManyI-Regular.ttf"), data).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
for i in 0..n {
let family = format!("Retype Many {i}");
db.add_font(
vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("RetypeMany{i}-Regular"))).unwrap(),
);
}
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
let shapes = [super::Sought::unpainted(&word, &groups)];
let (keys, near) = super::keys_of(&shapes, 0.0);
let copies: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Many ")).collect();
assert_eq!(copies.len(), n);
let indexes: Vec<super::super::RetypeIndex> = copies
.chunks(vectorcraft_text::retype::MAX_FACES)
.map(|g| super::super::RetypeIndex::build_near(&db, g.iter().cloned(), &keys, &near))
.collect();
let beside: Vec<&super::super::RetypeIndex> = indexes.iter().collect();
let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap();
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families.len(), 2, "{families:?}");
assert_eq!(families.last(), Some(&"Retype Many I"));
}
#[test]
fn a_split_shape_completes_with_loaded_faces_past_the_first_and_installed_ones() {
// A W of Source Sans 3 and a k of Inter in one compound path. Past the faces compared first
// (the bundled ones), a loaded copy of Inter holds the k and an installed copy of Source Sans 3
// the W.
let dir = vectorcraft_testkit::temp_dir("retype-installed-kept");
let data = vectorcraft_text::test_fonts::named_copy(false, ("Retype Kept S", "Regular", "Version 1.000", "RetypeKeptS-Regular")).unwrap();
std::fs::write(dir.join("RetypeKeptS-Regular.ttf"), data).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
let compared: Vec<u32> = db.loaded_faces().iter().map(|f| f.id()).collect();
db.add_font(vectorcraft_text::test_fonts::named_copy(true, ("Retype Kept I", "Regular", "Version 1.000", "RetypeKeptI-Regular")).unwrap());
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let shapes = [super::Sought::unpainted(&word, &groups)];
let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[], 0.0, &compared).unwrap();
assert!(rest.is_empty() && done == [false]);
assert_eq!(kept.len(), 1, "the group with the k is kept for the installed fonts");
let beside: Vec<&super::super::RetypeIndex> = kept.iter().collect();
let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap();
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Retype Kept I", "Retype Kept S"], "the loaded copy's k and the installed copy's W");
}
#[test]
fn an_installed_face_whose_glyphs_paint_otherwise_than_the_shape_is_not_found() {
// Two o's moved onto each other in one compound path filled by the even-odd rule: the overlap
// is unpainted, and two glyphs set side by side would paint it.
let paths = |db: &FontDb| {
let face = db.face("Source Sans 3", "Regular").unwrap();
let o = Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o'));
let mut word = BezPath::new();
for x in [40.0, 49.0] {
word.extend((Affine::translate((x, 100.0)) * o.clone()).iter());
}
word
};
let (db, _) = installed("paint", &["Retype Copy Paint"]);
let word = paths(&db);
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let even_odd = super::Sought { path: &word, groups: &groups, fill: Some(false), once: true };
let found = super::search_for(&db, &[even_odd], 0.0, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 0), "the o's paint the overlap");
assert!(unloaded(&db, "Retype Copy Paint"));
// Without a fill to compare, the same glyphs are found.
let (db, _) = installed("paint-none", &["Retype Copy Unpainted"]);
let word = paths(&db);
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
assert_eq!(found.faces.len(), 1);
}
#[test]
fn retype_reads_no_installed_font_for_plain_shapes_alone() {
let (db, _) = installed("retype-plain", &["Retype Copy M"]);
let pieces = pieces("W-");
let groups = vec![vec![]; pieces.len()];
let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()]));
let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0);
let left = super::super::left_shapes(&pieces, &groups, &found);
assert_eq!(left.len(), 1, "the hyphen is left");
let installed = super::search_for(&db, &left, 0.0, false).unwrap();
assert_eq!((installed.read, installed.faces.len()), (0, 0));
assert!(unloaded(&db, "Retype Copy M"));
}
#[test]
fn installed_must_be_a_bool_or_null() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for cmd in ["type.retype", "type.retypeFonts"] {
for bad in [json!(1), json!("yes"), json!([])] {
let e = s.execute(cmd, &json!({"installed": bad})).unwrap_err().to_string();
assert!(e.contains("`installed` must be true, false or null"), "{cmd} {bad}: {e}");
}
}
// false: no installed font is read, and the result says so.
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
}
/// A database with no installed fonts and `n` copies of the bundled Source Sans 3 Regular loaded,
/// named `{tag} 0` to `{tag} n-1`, after `inter` copies of Inter named `{tag} Inter 0` and on.
fn loaded_copies(tag: &str, inter: usize, n: usize) -> FontDb {
let db = FontDb::with_font_dirs(vec![]);
let copies = (0..inter).map(|i| (true, format!("{tag} Inter {i}"))).chain((0..n).map(|i| (false, format!("{tag} {i}"))));
for (inter, family) in copies {
let postscript = format!("{}-Regular", family.replace(' ', ""));
db.add_font(vectorcraft_text::test_fonts::named_copy(inter, (&family, "Regular", "Version 1.000", &postscript)).unwrap());
}
db
}
#[test]
fn loaded_faces_past_the_ones_compared_first_are_compared_too() {
let n = vectorcraft_text::retype::MAX_FACES + 4;
let db = loaded_copies("Retype Rest", 0, n);
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
// Every loaded face that matches, more than one index takes.
let rest = super::loaded_rest(&db, &refs, &[]).unwrap();
for i in 0..n {
assert!(rest.iter().any(|f| f.family == format!("Retype Rest {i}")), "copy {i} of {}", rest.len());
}
// The faces compared already are left out.
let last = format!("Retype Rest {}", n - 1);
let compared: Vec<u32> = db.loaded_faces().iter().filter(|f| f.family != last).map(|f| f.id()).collect();
let rest = super::loaded_rest(&db, &refs, &compared).unwrap();
assert_eq!(rest.iter().map(|f| f.family.as_str()).collect::<Vec<_>>(), [last.as_str()]);
// A plain shape alone compares none.
let bar = [kurbo::Rect::new(0.0, 0.0, 80.0, 10.0).to_path(0.1)];
assert!(super::loaded_rest(&db, &[&bar[0]], &[]).unwrap().is_empty());
}
#[test]
fn a_split_shape_completes_with_loaded_faces_past_the_ones_compared_first() {
// A W of Source Sans 3 and a k of Inter in one compound path. Source Sans 3 and Inter are
// compared first; past them, a loaded copy of Inter holds the k.
let db = loaded_copies("Retype Rest Split", 1, 0);
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let shapes = [super::Sought::unpainted(&word, &groups)];
let (keys, near) = super::keys_of(&shapes, 0.0);
let source = db.face("Source Sans 3", "Regular").unwrap();
let compared = [source.id(), inter.id()];
let first = super::super::RetypeIndex::build_near(&db, [source], &keys, &near);
let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[&first], 0.0, &compared).unwrap();
assert!(kept.is_empty(), "no split shape is left");
let families: Vec<&str> = rest.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Retype Rest Split Inter 0"], "the copy completes the glyphs of the face compared first");
assert_eq!(done, [true]);
}
#[test]
fn files_past_the_glyph_budget_are_skipped_without_being_read() {
let (db, mut files) = installed("budget-spent", &["Retype Copy E1", "Retype Copy E2"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
// The order the search reads them in: smallest first.
let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len();
files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b)));
assert_eq!(db.unloaded_installed_faces().len(), 2);
let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap();
let drawn = vectorcraft_text::retype::encoded_glyphs(&face);
// The second file holds no font after the listing: had it been read, it would give no face
// to skip.
std::fs::write(&files[1], vec![0u8; len(&files[1]) as usize]).unwrap();
let limits = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX };
let found = search_within(&db, &refs, true, limits, &|_| true).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (1, 1, 1));
}
#[test]
fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_first() {
let db = loaded_copies("Retype Run Rest", vectorcraft_text::retype::MAX_FACES, 1);
let shapes = glyphs(&db, "Rx");
// The Inter copies are compared first: none matches, and the copy loaded after them does.
let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect();
assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES);
let search =
super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces: super::Faces::Given(faces), tolerance: 0.0 };
let found = search.run_in(&db).unwrap();
assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in");
assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it");
// Every loaded face was compared: the command does not compare them again.
assert!(db.loaded_faces().iter().all(|f| found.installed.scanned.contains(&f.id())));
// A face compared first that matches is handed in too, as loading others may move it past
// the faces the command compares first.
let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect();
let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: super::Faces::Given(copy), tolerance: 0.0 }
.run_in(&db)
.unwrap();
assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0"));
}
#[test]
fn a_full_list_counts_skipped_installed_faces_only_when_a_shape_would_start_a_search() {
let (db, _) = installed("full-list", &["Retype Copy Full"]);
for i in 0..super::super::fonts::MAX_COUNT {
let family = format!("Retype Full {i}");
let postscript = format!("RetypeFull{i}-Regular");
db.add_font(vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap());
}
let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Full ")).collect();
// A hyphen is plain: it fills the list and would start no search, so nothing is skipped.
let hyphen = glyphs(&db, "-");
let refs: Vec<&BezPath> = hyphen.iter().collect();
let (ranked, found) = super::super::fonts::rank_fonts(&db, faces.clone(), &refs, true, None).unwrap();
assert_eq!(ranked.len(), super::super::fonts::MAX_COUNT);
assert_eq!((found.read, found.skipped), (0, 0));
// A shape that is not plain would: the installed face counts as skipped.
let shapes = glyphs(&db, "-q");
let refs: Vec<&BezPath> = shapes.iter().collect();
let (_, found) = super::super::fonts::rank_fonts(&db, faces, &refs, true, None).unwrap();
assert_eq!((found.read, found.skipped), (0, 1));
assert!(unloaded(&db, "Retype Copy Full"));
}
#[test]
fn what_is_handed_in_and_not_taken_can_be_dropped() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let doc = s.doc().unwrap().uid;
super::RetypeFound { doc, installed: super::Installed::default() }.hand_in(&mut s);
assert!(s.retype_hand_off.is_some());
super::RetypeFound::drop_handed(&mut s);
assert!(s.retype_hand_off.is_none());
}
+33 -19
View File
@@ -123,11 +123,13 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() {
#[test]
fn a_combining_mark_starts_no_line() {
// A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline.
// The calls that leave a shape an outline leave the installed fonts out, so what this machine
// has installed does not change the result.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
assert!(e.contains("no selected shape matches"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
// A shape that is both a mark (tilde below) and a character (small tilde) starts its line as
@@ -145,7 +147,7 @@ fn a_combining_mark_starts_no_line() {
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0;
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!(r["texts"], json!(["ab"]), "{r}");
assert_eq!(r["unmatched"], json!([mark]));
// After a base, the mark is retyped with it.
@@ -160,7 +162,7 @@ fn a_combining_mark_starts_no_line() {
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}");
// A mark that is also another character (dot below, dot above) becomes that character there.
let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
@@ -183,7 +185,7 @@ fn a_combining_mark_starts_no_line() {
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}");
assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}");
// A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and
@@ -193,7 +195,7 @@ fn a_combining_mark_starts_no_line() {
pair.sort_unstable();
let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [dot, word]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!(r["texts"], json!(["ab"]), "{r}");
let mut left: Vec<u64> = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
left.sort_unstable();
@@ -246,7 +248,8 @@ fn marks_first_after_a_split_leave_other_lines_their_tracking() {
s.execute("select.set", &json!({"ids": moved})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// The installed fonts left out: what this machine has installed does not change the result.
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
let texts = r["texts"].as_array().unwrap();
let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}"));
assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}");
@@ -374,7 +377,7 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() {
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches");
assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nothing matches");
}
#[test]
@@ -488,7 +491,8 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() {
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// The installed fonts left out: what this machine has installed does not change the result.
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}");
assert_eq!(r["unmatched"], json!([a]));
}
@@ -551,7 +555,8 @@ fn a_drawn_dot_or_bar_beside_type_stays_art() {
// A bar that is exactly a hyphen of the font, somewhere else: the worst case.
let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50}));
s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// The installed fonts left out: what this machine has installed does not change the result.
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!(r["texts"], json!(["AB"]), "{r}");
let un = r["unmatched"].as_array().unwrap();
assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}");
@@ -754,7 +759,8 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() {
simplify_every_path(&mut s, 0.05);
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
// The installed fonts left out: what this machine has installed does not change the result.
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
assert!(e.contains("no selected shape matches"), "no exact match: {e}");
for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] {
let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string();
@@ -825,8 +831,9 @@ fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30}));
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap();
// Nothing is left to retype: both stay outlines, as the lone bar beside art does.
let e = s.execute("type.retype", &json!({})).unwrap_err();
// Nothing is left to retype: both stay outlines, as the lone bar beside art does. The installed
// fonts are left out, so what this machine has installed does not change the result.
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err();
assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}");
}
@@ -1363,7 +1370,8 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() {
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
// The installed fonts left out: what this machine has installed does not change the result.
let e = match s.execute("type.retype", &json!({"installed": false})) {
Ok(r) => panic!("the period became type: {r}"),
Err(e) => e.to_string(),
};
@@ -1423,7 +1431,8 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() {
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
// The installed fonts left out: what this machine has installed does not change the result.
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
assert!(e.contains("(1 checked)"), "reported once: {e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
@@ -1440,7 +1449,8 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() {
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
// The installed fonts left out: what this machine has installed does not change the result.
let e = match s.execute("type.retype", &json!({"installed": false})) {
Ok(r) => panic!("the overlapping o's became type: {r}"),
Err(e) => e.to_string(),
};
@@ -1481,7 +1491,8 @@ fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() {
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({}));
// The installed fonts left out: what this machine has installed does not change the result.
let r = s.execute("type.retype", &json!({"installed": false}));
if opacity == 1.0 {
let r = r.unwrap();
assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}");
@@ -1502,8 +1513,9 @@ fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() {
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
// The installed fonts left out: what this machine has installed does not change the result.
for tolerance in [0.0, 0.05] {
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) {
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance, "installed": false})) {
panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}");
}
}
@@ -1564,7 +1576,8 @@ fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter");
// The installed fonts left out: what this machine has installed does not change the result.
assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nonzero, contour {turned} turned paints the counter");
s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}");
@@ -1591,7 +1604,8 @@ fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c, r]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
// The installed fonts left out: what this machine has installed does not change the result.
let e = match s.execute("type.retype", &json!({"installed": false})) {
Ok(r) => panic!("the A became type without its period: {r}"),
Err(e) => e.to_string(),
};
+308 -14
View File
@@ -90,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
list_installed
),
cmd!(
query "script.startup.run",
"Run Startup Scripts",
[],
None,
"{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry",
always,
startup_run
),
cmd!(
query "script.grants",
"List Script File Permissions",
@@ -104,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Revoke Script File Permissions",
[],
None,
"{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}",
"{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}",
always,
grants_revoke
),
@@ -149,6 +158,21 @@ const NOT_TEXT: &str = "the script is not UTF-8 text";
pub const TOO_LARGE: &str = "the script is too large to run";
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let request = prepare(s, p)?;
run_prepared(s, request)
}
fn run_prepared(s: &mut Session, request: script::Request) -> Result<Value> {
let name = s.script_start(request)?;
if s.script_frames {
return Ok(json!({"running": true, "name": name}));
}
s.script_run_to_end()
}
/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that
/// keeps it from starting.
fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
let optional_str = |key: &str| match p.get(key) {
None => Ok(None),
Some(Value::String(t)) => Ok(Some(t.as_str())),
@@ -207,7 +231,7 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
};
let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string());
let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language));
let request = script::Request {
Ok(script::Request {
name,
name_given: given_name.is_some(),
file: path.map(str::to_string),
@@ -217,12 +241,7 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
fuel,
locale,
answers,
};
let name = s.script_start(request)?;
if s.script_frames {
return Ok(json!({"running": true, "name": name}));
}
s.script_run_to_end()
})
}
fn stop(s: &mut Session, _: &Value) -> Result<Value> {
@@ -342,6 +361,278 @@ impl Session {
}
}
/// The error of a startup script that is no longer a `.jsx` file of the Startup Scripts folder, or
/// cannot be read, when its turn comes.
pub const STARTUP_UNREADABLE: &str = "the startup script could not be read";
impl Session {
/// Have `script.startup.run` run the scripts of the folder `dir`. The folder is only read, and
/// never made.
pub fn attach_startup_scripts_dir(&mut self, dir: std::path::PathBuf) {
self.startup_scripts_dir = Some(dir);
}
/// The Startup Scripts folder ([`Session::attach_startup_scripts_dir`]); none on the web.
pub fn startup_scripts_dir(&self) -> Option<&std::path::Path> {
self.startup_scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
/// Why `script.startup.run` runs nothing now: `off` (the `runStartupScripts` preference),
/// `safeMode`, or `noFolder` (no Startup Scripts folder); `None` when it runs the folder.
pub fn startup_skip(&self) -> Option<&'static str> {
if !self.prefs.run_startup_scripts {
Some("off")
} else if vectorcraft_plugins::safe_mode::active() {
Some("safeMode")
} else if self.startup_scripts_dir().is_none() {
Some("noFolder")
} else {
None
}
}
/// The startup script that ran has ended: the launch marker no longer names it.
pub(crate) fn startup_ended(&mut self) {
if let Some(token) = self.startup_loading.take() {
vectorcraft_plugins::safe_mode::loaded(token);
}
}
/// The running script is a startup script (`script.startup.run`), not the script queued after
/// them.
pub fn startup_script_running(&self) -> bool {
self.startup_loading.is_some()
}
/// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a
/// file, with the launch marker naming it while it runs. → the run's name, or the error that kept
/// it from starting, which the Script Console also shows.
fn start_startup(&mut self, path: &std::path::Path, fuel: u64) -> std::result::Result<String, String> {
let name = file_name_of(path);
let text = self.startup_text(path);
let (text, real) = match text {
Ok(read) => read,
Err(message) => {
self.note_unread(&name, &message);
return Err(message);
}
};
let item = startup_item(path);
self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item));
let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language));
let request = script::Request {
name: name.clone(),
name_given: false,
file: Some(path.to_string_lossy().into_owned()),
checked_real: Some(real),
source: text,
args: serde_json::Map::new(),
fuel,
locale,
answers: vec![],
};
let runs = self.script_runs;
self.script_start(request).map_err(|e| {
self.startup_ended();
let message = e.to_string();
// A run refused before it began, such as with an undo group open, has no console entry yet.
if self.script_runs == runs {
self.note_unread(&name, &message);
}
message
})
}
/// The text of the startup script at `path` and its real path, or the error that keeps it from
/// running.
fn startup_text(&self, path: &std::path::Path) -> std::result::Result<(String, std::path::PathBuf), String> {
let unreadable = || STARTUP_UNREADABLE.to_string();
let root = self.startup_scripts_dir().ok_or_else(unreadable)?;
let mut real = std::fs::canonicalize(root).map_err(|_| unreadable())?;
real.push(path.file_name().ok_or_else(unreadable)?);
// One byte more than a script may have shows that the file is too large.
let bytes = script::startup::read(root, path, script::MAX_SOURCE_BYTES + 1).ok_or_else(unreadable)?;
if bytes.len() > script::MAX_SOURCE_BYTES {
return Err(TOO_LARGE.to_string());
}
Ok((script_text(&bytes).map_err(|e| e.to_string())?, real))
}
/// With no script running, starts the next run `script.startup.run` queued: the next startup
/// script that starts, or the script queued after them. A run that cannot start is kept for
/// [`Self::take_startup_failures`], and the next one starts on a later pump. → the reply of the script queued
/// after them when it ran to its end at once.
pub(crate) fn start_queued(&mut self) -> Option<Value> {
// Held aside while a run starts, so that the queue does not count as a running script then.
let mut queue = std::mem::take(&mut self.script_queue);
// Each run starts in the file access scope of the request that queued it, which the run
// keeps, and not in the scope of the frame that starts it.
let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture);
let mut reply = None;
if self.script_key.is_none()
&& let Some(next) = queue.pop_front()
{
match next {
script::startup::Queued::Startup { path, fuel } => {
if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) {
self.startup_failures.push((file_name_of(&path), e));
}
}
script::startup::Queued::Then(params) => {
let prepared = self.script_queue_then.take();
match scope.clone().run(|| match prepared {
Some(request) => run_prepared(self, request),
None => run(self, &params),
}) {
Ok(_) if self.script_key.is_some() => {}
Ok(v) => reply = Some(v),
Err(e) => self.startup_failures.push((then_name(&params), e.to_string())),
}
}
}
}
if queue.is_empty() {
self.script_queue_scope = None;
self.script_queue_then = None;
}
self.script_queue = queue;
reply
}
/// The runs `script.startup.run` queued that could not start since the last call, as (name,
/// error), in order.
pub fn take_startup_failures(&mut self) -> Vec<(String, String)> {
std::mem::take(&mut self.startup_failures)
}
}
/// The file name of `path`, or the whole path when it has none.
fn file_name_of(path: &std::path::Path) -> String {
path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned())
}
/// The name a failure of the script `params` (`script.run`'s) names it by: `name`, else the file
/// name of `path`, else "script".
fn then_name(params: &Value) -> String {
let given = |key: &str| params.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty());
match (given("name"), given("path")) {
(Some(name), _) => name.to_string(),
(None, Some(path)) => file_name_of(std::path::Path::new(path)),
(None, None) => "script".to_string(),
}
}
/// The launch marker's entry for the startup script at `path`: its file and its file name.
fn startup_item(path: &std::path::Path) -> vectorcraft_plugins::safe_mode::Item {
let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
vectorcraft_plugins::safe_mode::Item { id: None, file: Some(path.to_string_lossy().into_owned()), name }
}
fn startup_run(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "script.startup.run";
let reason = match p.get("reason").and_then(Value::as_str) {
Some(r @ ("launch" | "menu")) => r,
_ => {
let key = "reason";
return Err(bad(C, format!("`{key}` must be one of {}", "launch, menu")));
}
};
let then = match p.get("then") {
None => None,
Some(v @ Value::Object(_)) => Some(v.clone()),
Some(_) => {
let key = "then";
return Err(bad(C, format!("`{key}` must be an object")));
}
};
let fuel = match p.get("maxFuel") {
None => script::DEFAULT_FUEL,
Some(v) => v.as_u64().filter(|n| (1..=script::MAX_FUEL).contains(n)).ok_or_else(|| EngineError::BadParams {
cmd: C.into(),
msg: format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL),
})?,
};
if s.script_running() {
return Err(EngineError::Busy);
}
// A chosen script that cannot start ends the request before any startup script runs, and its
// parameters are checked as `script.run` checks them.
if let Some(then) = &then {
super::params::check_params("script.run", then)?;
}
let root = match (s.startup_skip(), s.startup_scripts_dir()) {
(None, Some(root)) => root.to_path_buf(),
(why, _) => {
let mut out = json!({"reason": reason, "skipped": true, "why": why.unwrap_or("noFolder")});
if let Some(then) = then {
out["then"] = run(s, &then)?;
}
return Ok(out);
}
};
let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?;
if let Some(request) = &prepared {
let mut preflight = Session::new();
if let Err(error) = preflight.script_start(request.clone()) {
s.script_report = None;
return Err(error);
}
}
let folder = root.to_string_lossy().into_owned();
// The folder is the app's: a refusal names it as the request may see it.
crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?;
let listing = script::startup::list(&root);
let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let (disabled, scripts): (Vec<_>, Vec<_>) =
listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path)));
let disabled: Vec<String> = disabled.iter().map(|p| name_of(p)).collect();
if s.script_frames {
s.script_queue =
scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect();
s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture());
s.script_queue_then = prepared;
let queued = s.script_queue.len();
s.startup_failures.clear();
let then = s.start_queued();
let failed: Vec<Value> = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect();
let mut out = json!({
"reason": reason,
"skipped": false,
"running": s.script_running(),
"queued": queued,
"failed": failed,
"disabled": disabled,
"truncated": listing.truncated,
"unreadable": listing.unreadable,
});
if let Some(then) = then {
out["then"] = then;
}
return Ok(out);
}
let (mut ran, mut failed) = (vec![], vec![]);
for path in scripts {
let name = name_of(&path);
match s.start_startup(&path, fuel).map_err(EngineError::Other).and_then(|_| s.script_run_to_end()) {
Ok(_) => ran.push(name),
Err(e) => failed.push(json!({"name": name, "error": e.to_string()})),
}
}
let mut out = json!({
"reason": reason,
"skipped": false,
"ran": ran,
"failed": failed,
"disabled": disabled,
"truncated": listing.truncated,
"unreadable": listing.unreadable,
});
if let Some(request) = prepared {
out["then"] = run_prepared(s, request)?;
}
Ok(out)
}
/// The file name a reply names `path` by when the file is outside the automation read roots; `None`
/// when a reply may name it whole.
fn hidden_name(path: &str) -> Option<String> {
@@ -384,16 +675,19 @@ fn grants(s: &mut Session, _: &Value) -> Result<Value> {
fn grants_revoke(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "script.grants.revoke";
// A path is matched as given, or with its links followed when no grant holds it as given, so a
// grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the
// automation read roots, a network path among them) is compared as written, without looking it up.
let path_of = |key: &str| match p.get(key) {
None => Ok(None),
// A path the request may not read (outside the automation read roots, a network path among
// them) is compared as written, without looking it up.
Some(Value::String(t)) if !t.is_empty() => Ok(Some(
crate::file_access::check_read(t)
Some(Value::String(t)) if !t.is_empty() => {
let real = crate::file_access::check_read(t)
.ok()
.and_then(|()| std::fs::canonicalize(t).ok())
.map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()),
)),
.map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned())
.filter(|real| real != t);
Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::<Vec<_>>()))
}
Some(_) => Err(bad(C, format!("`{key}` must be a path"))),
};
let (script_path, path) = (path_of("script")?, path_of("path")?);
+31 -7
View File
@@ -497,6 +497,32 @@ impl Session {
/// and with a target that has no stroke row, since `stroke.set` gives such a target a plain
/// stroke.
pub fn brushed_strokes_profiled(&self) -> Option<bool> {
let st = self.active()?;
let strokes: Vec<&StrokeLayer> = self.edited_strokes(false)?.into_iter().map(|s| s.filter(|s| s.brush.is_some())).collect::<Option<_>>()?;
if strokes.is_empty() {
return None;
}
// The library is read only when every stroke names a brush.
let lib = vectorcraft_brush::library(&st.doc);
strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some()))
}
/// Does any of the strokes that `stroke.set` edits without `ids` or `item` have a width
/// profile? The strokes are the ones [`Session::brushed_strokes_profiled`] reads, with or without
/// a brush. Type without an active Appearance row is left out, since `stroke.set` gives its
/// characters no profile. False with nothing selected, with an object inside a symbol instance
/// selected, and with a target that has no stroke row, which a profile from `stroke.set` would
/// give a plain stroke.
pub fn edited_strokes_profiled(&self) -> bool {
self.edited_strokes(true)
.and_then(|strokes| strokes.into_iter().collect::<Option<Vec<_>>>())
.is_some_and(|strokes| strokes.iter().any(|s| s.profile.is_some()))
}
/// The strokes that `stroke.set` edits without `ids` or `item`, one for each target, `None` for
/// a target without a stroke row (see [`Session::brushed_strokes_profiled`]). Type without an
/// active Appearance row is skipped with `skip_type`, and makes the result `None` without it.
fn edited_strokes(&self, skip_type: bool) -> Option<Vec<Option<&StrokeLayer>>> {
const C: &str = "stroke.set";
let st = self.active()?;
if st.selected_symbol_part().is_some() {
@@ -514,16 +540,14 @@ impl Session {
let n = st.doc.node(*id)?;
let row = each?.resolve(&n.appearance, false, C).ok()?;
if row.is_none() && matches!(n.kind, NodeKind::Text(_)) {
if skip_type {
continue;
}
return None;
}
strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?);
strokes.push(n.appearance.stroke_at(row));
}
if strokes.is_empty() {
return None;
}
// The library is read only when every stroke names a brush.
let lib = vectorcraft_brush::library(&st.doc);
strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some()))
Some(strokes)
}
}
+195
View File
@@ -0,0 +1,195 @@
//! An object's tags: name and value pairs scripts keep on page items (`object.tags`,
//! `object.tag.add`, `object.tag.set`, `object.tag.remove`, `object.tag.removeAll`). The native file
//! keeps them; other formats do not write them.
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, MAX_TAG_TEXT, MAX_TAGS, Node, ObjectTag};
use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, ids_param, targets, text_param, u64_req};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "object.tags",
"Attributes",
[],
None,
"{id} → {tags: [{tag, name, value}]} the object's tags in order; `tag` tells each apart from the others while its name and value change",
has_doc,
list
),
cmd!(
"object.tag.add",
"Attributes",
[],
None,
"{id, name?: string, value?: string} adds a tag after the object's others (\"\" for a name or value left out), as one undo step; an object has at most 64 tags, each name and value at most 65,536 bytes → {tag}",
has_doc,
add
),
cmd!(
"object.tag.set",
"Attributes",
[],
None,
"{id, tag, name?: string, value?: string} changes the tag's name or value, as one undo step; a value it already has changes nothing → {changed: bool}",
has_doc,
set
),
cmd!("object.tag.remove", "Attributes", [], None, "{id, tag} deletes the tag, as one undo step → {}", has_doc, remove),
cmd!(
"object.tag.removeAll",
"Attributes",
[],
None,
"{ids?|id?} deletes every tag of the objects in ids or the selection, as one undo step → {changed: objects}",
has_doc,
remove_all
),
]
}
/// The page item `p`'s `id` names: an object of the document, not a layer or a ruler guide.
fn object(s: &Session, p: &Value, c: &str) -> Result<NodeId> {
let id = NodeId(u64_req(p, "id", c)?);
let d = &s.doc()?.doc;
match d.node(id) {
Some(n) if is_page_item(n) => Ok(id),
Some(_) => Err(bad(c, format!("object {} is a layer or a ruler guide, which has no tags", id.0))),
None => Err(bad(c, format!("no object {}", id.0))),
}
}
fn is_page_item(n: &Node) -> bool {
!matches!(n.kind, vectorcraft_doc::NodeKind::Layer { .. }) && !n.is_ruler_guide()
}
/// The tags of `n`.
pub(crate) fn tags_of(n: &Node) -> &[ObjectTag] {
n.extras().attrs.as_deref().map_or(&[], |a| a.tags.as_slice())
}
/// The tag `p`'s `tag` names on object `id`: its index among the object's tags.
fn tag_index(d: &Document, id: NodeId, p: &Value, c: &str) -> Result<usize> {
let tag = u64_req(p, "tag", c)?;
let n = d.node(id).ok_or_else(|| bad(c, format!("no object {}", id.0)))?;
tags_of(n).iter().position(|t| t.id == tag).ok_or_else(|| bad(c, format!("object {} has no tag {tag}", id.0)))
}
/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. `None`
/// when `p` leaves it out; a null is an error.
fn tag_text<'a>(p: &'a Value, key: &str, c: &str) -> Result<Option<&'a str>> {
if p.get(key).is_some_and(Value::is_null) {
return Err(bad(c, format!("`{key}` must be a string")));
}
let t = text_param(p, key, c)?;
if t.is_some_and(|t| t.len() > MAX_TAG_TEXT) {
return Err(bad(c, format!("a tag's {key} is longer than 65,536 bytes")));
}
Ok(t)
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.tags";
let id = object(s, p, C)?;
let d = &s.doc()?.doc;
let tags = d.node(id).map(tags_of).unwrap_or_default();
Ok(json!({"tags": tags.iter().map(|t| json!({"tag": t.id, "name": t.name, "value": t.value})).collect::<Vec<_>>()}))
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.tag.add";
let id = object(s, p, C)?;
let name = tag_text(p, "name", C)?.unwrap_or_default().to_string();
let value = tag_text(p, "value", C)?.unwrap_or_default().to_string();
let count = s.doc()?.doc.node(id).map_or(0, |n| tags_of(n).len());
if count >= MAX_TAGS {
return Err(bad(C, format!("object {} has 64 tags, the most an object has", id.0)));
}
let tag = s.edit("Attributes", |d, _| {
// A document-wide id: a tag deleted earlier in the run never shares it.
let tag = d.alloc_tag_id(id).ok_or_else(|| bad(C, "the document has no tag ids left"))?;
let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?;
n.edit_attrs(|a| a.tags.push(ObjectTag { id: tag, name, value }));
Ok(tag)
})?;
Ok(json!({"tag": tag}))
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.tag.set";
let id = object(s, p, C)?;
let name = tag_text(p, "name", C)?;
let value = tag_text(p, "value", C)?;
if name.is_none() && value.is_none() {
return Err(bad(C, "give name or value"));
}
let at = tag_index(&s.doc()?.doc, id, p, C)?;
let same = s
.doc()?
.doc
.node(id)
.and_then(|n| tags_of(n).get(at))
.is_some_and(|t| name.is_none_or(|v| t.name == v) && value.is_none_or(|v| t.value == v));
if same {
return Ok(json!({"changed": false}));
}
s.edit("Attributes", |d, _| {
let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?;
n.edit_attrs(|a| {
if let Some(t) = a.tags.get_mut(at) {
if let Some(v) = name {
v.clone_into(&mut t.name);
}
if let Some(v) = value {
v.clone_into(&mut t.value);
}
}
});
Ok(())
})?;
Ok(json!({"changed": true}))
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.tag.remove";
let id = object(s, p, C)?;
let at = tag_index(&s.doc()?.doc, id, p, C)?;
s.edit("Attributes", |d, _| {
let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?;
let gone = n.edit_attrs(|a| (at < a.tags.len()).then(|| a.tags.remove(at).id));
if let Some(t) = gone {
d.raise_next_id(t.saturating_add(1));
}
Ok(())
})?;
Ok(json!({}))
}
fn remove_all(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.tag.removeAll";
ids_param(p, "ids", C)?;
let ids = targets(s, p)?;
let d = &s.doc()?.doc;
for id in &ids {
if d.node(*id).is_none() {
return Err(bad(C, format!("no object {}", id.0)));
}
}
let tagged: BTreeSet<NodeId> = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !tags_of(n).is_empty())).collect();
if !tagged.is_empty() {
s.edit("Attributes", |d, _| {
let mut last = 0;
for id in &tagged {
if let Some(n) = d.node_mut(*id) {
last = n.edit_attrs(|a| a.tags.drain(..).map(|t| t.id).fold(last, u64::max));
}
}
d.raise_next_id(last.saturating_add(1));
Ok(())
})?;
}
Ok(json!({"changed": tagged.len()}))
}
+13 -4
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a Line truncated
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\" (on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle), keepLineGap?: bool = false (as text.setStyle), tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each c Line truncated
has_doc,
set_range_style
),
@@ -103,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Step Type",
[],
None,
"{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}",
"{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object. On area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle → {ids}",
has_doc,
type_step
),
@@ -1213,6 +1213,7 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
},
};
let story = switch_or(p, "story", false, C)?;
let keep_line_gap = switch_or(p, "keepLineGap", false, C)?;
if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Err(bad(C, "`story` styles the whole story: give no `start` or `end`"));
}
@@ -1256,7 +1257,11 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) };
set.extend(styled.iter().flat_map(super::fonts::run_fonts));
}
refresh_bounds(t);
// With Block on, the leading goes to the frame's line gap.
match change.leading.filter(|_| !keep_line_gap).and_then(|l| super::typecmd::styled_start(t, a, b).map(|at| (at, l))) {
Some((at, l)) => super::typecmd::refresh_with_leading(t, at, l),
None => refresh_bounds(t),
}
n = if *f == id { t.runs.len() } else { n };
}
Ok(n)
@@ -2077,7 +2082,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
}
}
edit::replace_range_styled(&mut t.runs, a, b, &runs);
refresh_bounds(t);
// With Block on, the step goes to the frame's line gap.
match runs.first().filter(|_| matches!(step, Step::Leading)) {
Some(first) => super::typecmd::refresh_with_leading(t, a, first.style.leading),
None => refresh_bounds(t),
}
}
Ok(())
})?;
+35 -2
View File
@@ -500,13 +500,33 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
};
each_text_mut(d, &mut |t| {
let mut changed = false;
// The first character whose leading the new definition changed.
let mut leading_at = None;
// Substitute the old definition only for leading generated by Block.
let block = t.dynamic_text && matches!(t.kind, vectorcraft_doc::TextKind::Area { .. });
let block_metrics = super::typecmd::block_fit_metrics(t).map(|(points, gap, _)| (gap / points, super::typecmd::BLOCK_SIZES.0 / points));
let old_leading = old
.get("leading")
.filter(|_| block && old.get("leading") != new.get("leading"))
.and_then(|v| serde_json::from_value::<Option<f64>>(v.clone()).ok());
match kind {
Kind::Char => {
let mut off = 0;
for r in &mut t.runs {
if r.style.style_name == target {
if let Some(l) = old_leading
.filter(|_| block_metrics.is_some_and(|(gap, minimum)| r.style.leading == Some((r.style.size + gap).max(minimum))))
{
r.style.leading = l;
}
let was = r.style.leading;
r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new);
changed = true;
if r.style.leading != was && leading_at.is_none() {
leading_at = Some(off);
}
}
off += r.text.len();
}
}
Kind::Para => {
@@ -519,7 +539,11 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
}
}
if changed {
refresh_bounds(t);
// With Block on, a leading the new definition gives goes to the frame's line gap.
match leading_at {
Some(at) => super::typecmd::refresh_with_given_leading(t, at),
None => refresh_bounds(t),
}
}
Ok(())
})
@@ -857,6 +881,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let attrs = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?;
let normal = kind.attrs(d, kind.normal()).unwrap_or_default();
let clear = bool_or(p, "clearOverrides", false);
// The style sets a leading, or clearing overrides gives the text Normal's.
let sets_leading = kind == Kind::Char && (attrs.contains_key("leading") || (clear && normal.contains_key("leading")));
let style_name = (name != kind.normal()).then(|| name.clone());
// A Type tool range or whole text objects.
let text_range = super::typecmd::TextRange::parse(p, &c)?;
@@ -883,6 +909,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
s.edit_named("Apply {name}", &name, name == kind.normal(), |d, _| {
for id in &ids {
let Some(t) = text_mut(d, *id) else { continue };
// The first character given the style's leading.
let mut leading_at = None;
match kind {
Kind::Char => {
let len = vectorcraft_text::edit::runs_len(&t.runs);
@@ -903,6 +931,7 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
if let Some(e) = err {
return Err(e);
}
leading_at = sets_leading.then(|| super::typecmd::styled_start(t, a.min(b), a.max(b))).flatten();
}
Kind::Para => {
let mut v = t.paragraph_styles();
@@ -916,7 +945,11 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
t.set_paragraph_styles(v);
}
}
refresh_bounds(t);
// With Block on, a leading the style sets goes to the frame's line gap.
match leading_at {
Some(at) => super::typecmd::refresh_with_given_leading(t, at),
None => refresh_bounds(t),
}
}
Ok(())
})?;
+48 -3
View File
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Area Type Options…",
["Type"],
None,
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error; a leading change on the text also sets lineGap, as type.dynamicText says) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
has_selection,
area_options
),
@@ -140,7 +140,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", keepLineGap?: bool = false (true: Dynamic Text (Block) keeps the frame's line gap, as Reset Panel does), tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap (text.areaOptions lineGap) to the new leading less the size of the first character changed, within -1296..1296 pt, so every line spreads or tightens by the change, unless keepLineGap is true; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
has_doc,
set_style
),
@@ -335,6 +335,11 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
// Edits that changed the paragraph count keep one paragraph style per paragraph.
t.normalize_paras();
block::block_fit(t);
refresh_fitted(t);
}
/// The part of [`refresh_bounds`] after Block has fitted the lines.
fn refresh_fitted(t: &mut TextObject) {
auto_height(t);
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
t.cached_bounds = Some(lay.bounds);
@@ -342,6 +347,36 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t)));
}
/// [`refresh_bounds`] after a change that set the leading of the character at `at` to `leading`
/// (in text space; None: Auto): on area type with Block on the change goes to the frame's line gap
/// ([`block::leading_to_line_gap`]), and the lines are fitted again only when the gap changed.
pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Option<f64>) {
if block::leading_to_line_gap(t, at, leading) {
refresh_fitted(t);
} else {
refresh_bounds(t);
}
}
/// The first character a style change over `a..b` of `t` reaches, with both ends on character
/// boundaries as [`vectorcraft_text::edit::style_range`] sets them; None when the range styles no
/// character (empty, or inside one character, in text that is not empty).
pub(crate) fn styled_start(t: &TextObject, a: usize, b: usize) -> Option<usize> {
let plain = t.plain_text();
let (a, b) = (vectorcraft_text::edit::floor_char(&plain, a), vectorcraft_text::edit::floor_char(&plain, b));
(a != b || plain.is_empty()).then_some(a.min(b))
}
/// [`refresh_with_leading`] with the leading the character at `at` was just given (a character
/// style, Text Tweaker).
pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) {
if block::given_leading_to_line_gap(t, at) {
refresh_fitted(t);
} else {
refresh_bounds(t);
}
}
/// [`refresh_bounds`] for a document that is opening: the first frame takes the layout
/// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again.
pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) {
@@ -955,6 +990,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
{
return Err(bad(C, "nothing to change"));
}
let keep_line_gap = switch_or(p, "keepLineGap", false, C)?;
let range = TextRange::parse(p, C)?;
let ids = text_targets(s, p, C)?;
let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some());
@@ -1032,7 +1068,14 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
let span = para_span(range, t);
t.edit_paras(span, |pa| pa.justify = j);
}
refresh_bounds(t);
// With Block on, the leading goes to the frame's line gap; an empty range styles nothing.
let changed = leading.filter(|_| !keep_line_gap).and_then(|l| {
range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).and_then(|(a, b)| styled_start(t, a, b))).map(|at| (at, l))
});
match changed {
Some((at, l)) => refresh_with_leading(t, at, l),
None => refresh_bounds(t),
}
}
// Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given,
// not in a scaled label's own units).
@@ -1478,6 +1521,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod area_tests;
mod block;
pub(super) use block::SIZES as BLOCK_SIZES;
pub(super) use block::fit_metrics as block_fit_metrics;
pub(crate) use block::needed_room;
#[cfg(test)]
mod block_tests;
+96 -18
View File
@@ -2,11 +2,11 @@
//! typed is set to the frame's width by changing its font size, after every edit
//! ([`super::refresh_bounds`]).
use vectorcraft_doc::{TextKind, TextObject, TextRun};
use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun};
/// The font size range a line's first character is fitted within, in document points (the
/// Character panel's).
const SIZES: (f64, f64) = (0.1, 1296.0);
pub(crate) const SIZES: (f64, f64) = (0.1, 1296.0);
/// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures
/// the lines and runs at most one more area layout.
@@ -56,6 +56,19 @@ pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 {
vectorcraft_text::edit::style_at(runs, byte).size
}
/// The run that holds the character at `byte` (not the one before it), else the last run.
fn run_at(runs: &[TextRun], byte: usize) -> Option<&TextRun> {
let mut off = 0;
for r in runs {
let end = off + r.text.len();
if (off..end).contains(&byte) {
return Some(r);
}
off = end;
}
runs.last()
}
/// The stored size of each line's first character, in one pass over the runs.
fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec<f64> {
let mut out = Vec::with_capacity(lines.len());
@@ -122,6 +135,71 @@ pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> {
.reduce(|a, b| if b.0 > a.0 { b } else { a })
}
/// Whether every character's leading is the one Block gives it: its size plus the frame's line
/// gap (in text space, at least the least size), as [`block_fit`] sets it.
fn block_leadings(t: &TextObject, points: f64) -> bool {
let gap = t.area.block_gaps().1 / points;
let min_leading = SIZES.0 / points;
t.runs.iter().all(|r| r.style.leading == Some((r.style.size + gap).max(min_leading)))
}
/// A leading change on area type with Block on ([`TextObject::dynamic_text`]), called after the
/// change is applied to the characters: Block sets each character's leading to its size plus the
/// frame's line gap, so the change goes to the line gap instead. The lines are fitted, so the
/// character at `at` has the size Block gives it (a size set by the same change included); the gap
/// is then the leading `leading` gives that character (in text space; None: Auto) less its size, in
/// document points and kept within [`vectorcraft_doc::AreaOptions::LINE_GAP`]. That moves the gap
/// by the change to the character's leading, so every line spreads or tightens by the same amount.
/// A new gap moves the lines, which in a shaped frame changes the room each one has and so the size
/// Block gives the character, so the lines are fitted again and the gap worked out again from the
/// new size, at most [`BLOCK_PASSES`] times. True when the lines are fitted for the final gap, so the
/// caller lays the text out without fitting it again. Point type, type on a path and area type with
/// Block off are left as they are.
pub(crate) fn leading_to_line_gap(t: &mut TextObject, at: usize, leading: Option<f64>) -> bool {
if !t.dynamic_text || !matches!(t.kind, TextKind::Area { .. }) {
return false;
}
let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false };
t.normalize_paras();
let para = t.plain_text().get(..at).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count());
for _ in 0..BLOCK_PASSES {
block_fit(t);
// A frame Block could not fit leaves the characters as they were.
if !block_leadings(t, points) {
return false;
}
let Some(run) = run_at(&t.runs, at) else { return true };
let size = run.style.size;
let new = match leading {
Some(l) => l,
None => {
// Auto leading as the layout sets it: the paragraph's Auto Leading share of the em size
// the font height reference gives the character. An inline graphic keeps its size.
let em = if run.inline.is_some() { size } else { vectorcraft_text::FontDb::global().em_size(&run.style, t.vertical) };
t.para_at(para).effective_leading(&CharStyle { size: em, leading: None, ..run.style.clone() })
}
};
let gap = (new - size) * points;
if !gap.is_finite() {
return true;
}
let (lo, hi) = vectorcraft_doc::AreaOptions::LINE_GAP;
let next = gap.clamp(lo, hi);
if (next - t.area.line_gap).abs() <= 1e-9 {
return true;
}
t.area.line_gap = next;
}
false
}
/// [`leading_to_line_gap`] with the leading the character at `at` was just given (a character
/// style, Text Tweaker), read before Block sets it again.
pub(crate) fn given_leading_to_line_gap(t: &mut TextObject, at: usize) -> bool {
let Some(leading) = run_at(&t.runs, at).map(|r| r.style.leading) else { return false };
leading_to_line_gap(t, at, leading)
}
/// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing
/// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down
/// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its
@@ -140,6 +218,21 @@ fn tenths(points: f64) -> f64 {
((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1)
}
pub(crate) fn fit_metrics(t: &TextObject) -> Option<(f64, f64, f64)> {
if !t.dynamic_text {
return None;
}
let TextKind::Area { frame } = &t.kind else { return None };
let (_, line_gap) = t.area.block_gaps();
let b = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))?;
let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?;
let a = &t.area;
let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) };
let cells = cells.max(1) as f64;
let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells;
(cell.is_finite() && cell > 1e-9).then_some((points, line_gap, cell))
}
/// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word
/// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line
/// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to
@@ -150,24 +243,9 @@ fn tenths(points: f64) -> f64 {
/// has no size. A line that still wraps at its first fit is made smaller, in at most
/// [`BLOCK_PASSES`] more passes. True when the text changed.
pub(crate) fn block_fit(t: &mut TextObject) -> bool {
if !t.dynamic_text {
return false;
}
let TextKind::Area { frame } = &t.kind else { return false };
let (_, line_gap) = t.area.block_gaps();
let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false };
let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false };
let Some((points, line_gap, cell)) = fit_metrics(t) else { return false };
let before = t.runs.clone();
// The room along a line in one cell of the frame, before indents.
let a = &t.area;
let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) };
let cells = cells.max(1) as f64;
let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells;
if !(cell.is_finite() && cell > 1e-9) {
return t.runs != before;
}
let db = vectorcraft_text::FontDb::global();
let text = t.plain_text();
let lines = typed_lines(&text);
@@ -31,6 +31,29 @@ fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn editing_a_character_style_keeps_manual_leading_when_block_has_no_room() {
for command in ["charStyle.setAttrs", "charStyle.edit"] {
for manual_leading in [42.0, 12.0] {
let mut s = session();
let id = area(&mut s, 50.0, 400.0, "Inset");
s.execute("text.areaOptions", &json!({"inset": 30})).unwrap();
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap();
s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap();
s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap();
assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading));
let params = if command == "charStyle.edit" {
json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}})
} else {
json!({"name": "Body", "attrs": {"leading": 60}})
};
s.execute(command, &params).unwrap();
assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading), "{command}: {manual_leading}");
}
}
}
/// The size of the character at `byte`.
fn size_at(t: &TextObject, byte: usize) -> f64 {
super::block::size_at(&t.runs, byte)
@@ -672,6 +695,109 @@ fn point_type_with_nothing_to_fit_is_left_as_it_is() {
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
}
/// The distances between the baselines of `t`'s lines.
fn baseline_steps(t: &TextObject) -> Vec<f64> {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
lay.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect()
}
/// Block owns each character's leading (its size plus the line gap): a leading change from
/// `text.setStyle`, `text.setRangeStyle` or `type.step` on area type with Block on changes the
/// line gap by the difference from the first character's leading, in one undo step, and sticks.
#[test]
fn a_leading_change_with_block_on_moves_the_line_gap() {
let mut s = session();
let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one");
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
let t = text(&s, id);
let (first, second) = (t.runs[0].style.size, size_at(&t, 4));
let steps = baseline_steps(&t);
let n = undo_len(&s);
// The whole object: the first character's leading becomes the leading given.
s.execute("text.setStyle", &json!({"ids": [id], "leading": first + 6.0})).unwrap();
assert_eq!(undo_len(&s), n + 1, "one undo step");
let t = text(&s, id);
assert!((t.area.line_gap - 6.0).abs() < 1e-9, "line gap {}", t.area.line_gap);
assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 6.0).abs() < 1e-9)), "{:?}", t.runs);
assert_block(&t);
let wider = baseline_steps(&t);
assert!(wider.iter().zip(&steps).all(|(w, s)| (w - s - 6.0).abs() < 1e-6), "every line spreads: {steps:?} -> {wider:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s, id).area.line_gap, 0.0);
// A range: measured from the leading of its first character.
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second - 3.0})).unwrap();
let t = text(&s, id);
assert!((t.area.line_gap + 3.0).abs() < 1e-9, "line gap {}", t.area.line_gap);
assert!(baseline_steps(&t).iter().zip(&steps).all(|(w, s)| w < s), "every line tightens");
// Alt+Up/Down steps by the Size/Leading increment.
let inc = s.prefs.type_size_increment;
s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap();
assert!((text(&s, id).area.line_gap - (inc - 3.0)).abs() < 1e-9);
// Auto: the first character's Auto leading, 120% of its size.
s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto"})).unwrap();
let t = text(&s, id);
assert!((t.area.line_gap - t.runs[0].style.size * 0.2).abs() < 1e-6, "line gap {}", t.area.line_gap);
// The leading the first character already has changes nothing.
let n = undo_len(&s);
let lead = text(&s, id).runs[0].style.leading.unwrap();
s.execute("text.setStyle", &json!({"ids": [id], "leading": lead})).unwrap();
assert_eq!(undo_len(&s), n, "no undo step");
// The gap stays within its range.
s.execute("text.setStyle", &json!({"ids": [id], "leading": 5000})).unwrap();
assert_eq!(text(&s, id).area.line_gap, vectorcraft_doc::AreaOptions::LINE_GAP.1);
// From a gap that holds every leading at its least, the leading given still applies.
s.execute("text.areaOptions", &json!({"lineGap": -1296})).unwrap();
s.execute("text.setStyle", &json!({"ids": [id], "leading": 1})).unwrap();
let lead = text(&s, id).runs[0].style.leading.unwrap();
assert!((lead - 1.0).abs() < 1e-6, "leading {lead}");
s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap();
// A size set with the leading: the gap follows the size Block gives the first character, on an
// empty line (whose size Block keeps) too.
s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 50})).unwrap();
let lead = text(&s, id).runs[0].style.leading.unwrap();
assert!((lead - 50.0).abs() < 1e-6, "leading {lead}");
s.execute("text.setText", &json!({"text": "\nwords"})).unwrap();
s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 30})).unwrap();
let t = text(&s, id);
assert_eq!(size_at(&t, 0), 20.0, "the empty line keeps the size set");
assert!((t.runs[0].style.leading.unwrap() - 30.0).abs() < 1e-6, "{:?}", t.runs[0].style);
s.execute("text.setText", &json!({"text": "BIG\na much longer second line\nmid one"})).unwrap();
s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap();
// Scaled type: the leading given and the line gap are in document points.
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
let points = text(&s, id).style_scale().unwrap().points;
s.execute("text.setStyle", &json!({"ids": [id], "leading": 150})).unwrap();
let t = text(&s, id);
let (size, lead) = (t.runs[0].style.size * points, t.runs[0].style.leading.unwrap() * points);
assert!((lead - 150.0).abs() < 1e-6, "leading {lead}");
assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap);
}
/// Without Block (point type, and area type with Block off) a leading change sets the
/// characters' leading and leaves the line gap.
#[test]
fn a_leading_change_without_block_sets_the_leading() {
let mut s = session();
let id = area(&mut s, 300.0, 400.0, "one\ntwo");
s.execute("text.areaOptions", &json!({"lineGap": 5})).unwrap();
s.execute("text.setStyle", &json!({"ids": [id], "leading": 30})).unwrap();
let t = text(&s, id);
assert_eq!(t.area.line_gap, 5.0);
assert!(t.runs.iter().all(|r| r.style.leading == Some(30.0)));
let id = point(&mut s, "one\ntwo", json!({}));
s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap();
let t = text(&s, id);
assert_eq!(t.area.line_gap, 0.0);
assert_eq!(t.runs[0].style.leading, Some(12.0 * 1.2 + s.prefs.type_size_increment));
}
#[test]
fn long_text_fits_in_a_bounded_number_of_layouts() {
let mut s = session();
@@ -698,3 +824,155 @@ fn long_text_fits_in_a_bounded_number_of_layouts() {
let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8;
assert!(used <= bound, "point type: {used} layouts");
}
/// Area type with Block on, its lines at different sizes, and a line gap of 0.
fn block_text(s: &mut Session) -> u64 {
let id = area(s, 300.0, 400.0, "BIG\na much longer second line\nmid one");
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
assert_eq!(text(s, id).area.line_gap, 0.0);
id
}
/// The leading of the one-byte character at `byte` (`style_at` reads the character before a run
/// end, so it is asked for the end of the character).
fn leading_at(t: &TextObject, byte: usize) -> Option<f64> {
vectorcraft_text::edit::style_at(&t.runs, byte + 1).leading
}
/// `text.setRangeStyle {leading}` on a range of Block text moves the line gap by the change to
/// the leading of the range's first character, and the range keeps the leading given.
#[test]
fn a_range_leading_change_with_block_on_moves_the_line_gap() {
let mut s = session();
let id = block_text(&mut s);
let second = vectorcraft_text::edit::style_at(&text(&s, id).runs, 5).size;
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second + 5.0})).unwrap();
let t = text(&s, id);
assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap);
assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4));
assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads");
// Reset Panel's form: the leading is set and Block keeps the line gap.
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap();
assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9);
s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto", "keepLineGap": true})).unwrap();
assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9);
assert!(s.execute("text.setStyle", &json!({"ids": [id], "leading": 30, "keepLineGap": 1})).is_err(), "keepLineGap takes a bool");
}
/// A range inside one character styles nothing, so it leaves the line gap.
#[test]
fn a_leading_on_a_range_inside_one_character_leaves_the_line_gap() {
let mut s = session();
let id = area(&mut s, 300.0, 400.0, "\u{e9}t\u{e9}\nsecond line");
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap();
let gap = text(&s, id).area.line_gap;
let range = json!({"start": 0, "end": 1});
let mut setstyle = json!({"ids": [id], "leading": 50});
let mut setrange = json!({"id": id, "leading": 50});
let mut apply = json!({"name": "Loose", "id": id});
for p in [&mut setstyle, &mut setrange, &mut apply] {
p.as_object_mut().unwrap().extend(range.as_object().unwrap().clone());
}
for (c, p) in [("text.setStyle", setstyle), ("text.setRangeStyle", setrange), ("charStyle.apply", apply)] {
s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}"));
assert_eq!(text(&s, id).area.line_gap, gap, "{c}");
}
}
/// `type.step {attribute: "leading"}` (Alt+Up/Down) on Block text moves the line gap by the step.
#[test]
fn a_leading_step_with_block_on_moves_the_line_gap() {
let mut s = session();
let id = block_text(&mut s);
let inc = s.prefs.type_size_increment;
s.execute("type.step", &json!({"attribute": "leading", "by": -1, "id": id, "start": 0, "end": 3})).unwrap();
let t = text(&s, id);
assert!((t.area.line_gap + inc).abs() < 1e-9, "line gap {}", t.area.line_gap);
assert!(leading_at(&t, 0).is_some_and(|l| (l - t.runs[0].style.size + inc).abs() < 1e-9));
}
/// A character style edited to set a leading while Block text uses it moves the line gap; a style
/// without a leading leaves the gap.
#[test]
fn a_character_style_edited_to_a_leading_with_block_on_moves_the_line_gap() {
let mut s = session();
let id = block_text(&mut s);
s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Plain", "id": id})).unwrap();
assert_eq!(text(&s, id).area.line_gap, 0.0, "no leading in the style");
s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 60}})).unwrap();
let t = text(&s, id);
assert!((t.area.line_gap - (60.0 - t.runs[0].style.size)).abs() < 1e-6, "edit: line gap {}", t.area.line_gap);
assert!(leading_at(&t, 0).is_some_and(|l| (l - 60.0).abs() < 1e-6));
assert_spread(&t);
// Once Block has given the characters other leadings than the style's (a new line gap here), a
// new leading in the style still applies: Block's leadings are not overrides.
s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap();
let gap = text(&s, id).area.line_gap;
s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 70}})).unwrap();
let t = text(&s, id);
assert!(t.area.line_gap != gap, "the line gap moved");
assert!(leading_at(&t, 0).is_some_and(|l| (l - 70.0).abs() < 1e-6), "{:?}", leading_at(&t, 0));
assert_spread(&t);
}
/// Every character's leading is its size plus the frame's line gap (at least the least size), so
/// every line spread or tightened by the same amount.
fn assert_spread(t: &TextObject) {
let gap = t.area.line_gap;
let least = super::block::SIZES.0;
assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - (r.style.size + gap).max(least)).abs() < 1e-6)), "{:?}", t.runs);
}
/// A character style that sets a leading, applied to Block text, moves the line gap.
#[test]
fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() {
let mut s = session();
let id = block_text(&mut s);
s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Loose", "id": id})).unwrap();
let t = text(&s, id);
assert!((t.area.line_gap - (50.0 - t.runs[0].style.size)).abs() < 1e-6, "apply: line gap {}", t.area.line_gap);
assert!(leading_at(&t, 0).is_some_and(|l| (l - 50.0).abs() < 1e-6));
assert_spread(&t);
// Clearing overrides gives the text the leading of the Normal style.
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"leading": 44}})).unwrap();
s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap();
s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Plain", "id": id, "clearOverrides": true})).unwrap();
let t = text(&s, id);
assert!(leading_at(&t, 0).is_some_and(|l| (l - 44.0).abs() < 1e-6), "clear: {:?}", leading_at(&t, 0));
assert!((t.area.line_gap - (44.0 - t.runs[0].style.size)).abs() < 1e-6, "clear: line gap {}", t.area.line_gap);
assert_spread(&t);
}
/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value;
/// Block then gives every other character its size plus that gap.
#[test]
fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() {
let mut s = session();
let id = block_text(&mut s);
s.execute("addon.type.textTweaker", &json!({"attribute": "leading", "from": 40, "to": 45, "ids": [id]})).unwrap();
let t = text(&s, id);
assert!((t.area.line_gap - (40.0 - t.runs[0].style.size)).abs() < 1e-6, "line gap {}", t.area.line_gap);
assert!(leading_at(&t, 0).is_some_and(|l| (l - 40.0).abs() < 1e-6));
assert_spread(&t);
}
/// The Eyedropper copies a whole character style, so the leading it copies onto Block text is not
/// a leading change: the line gap stays, and Block gives every character its size plus the gap.
#[test]
fn an_eyedropper_copy_onto_block_text_keeps_the_line_gap() {
let mut s = session();
let source = point(&mut s, "source", json!({}));
s.execute("text.setStyle", &json!({"ids": [source], "leading": 33})).unwrap();
let id = block_text(&mut s);
let gap = text(&s, id).area.line_gap;
s.execute("appearance.copyFrom", &json!({"source": source, "ids": [id]})).unwrap();
let t = text(&s, id);
assert_eq!(t.area.line_gap, gap);
assert_spread(&t);
}
+1 -1
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Dynamic Text",
["Type"],
None,
"{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}",
"{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}",
has_dynamic_type,
dynamic_text
),
+209 -19
View File
@@ -21,7 +21,7 @@ use vectorcraft_render::encode::quantize::{self, Dither, Indexed, PaletteOptions
use vectorcraft_render::encode::web::{self, ColorSort};
use vectorcraft_render::encode::{gif, jpeg, png};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name_from};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, text_param, unique_name_from};
const C: &str = "document.exportForWeb";
@@ -45,6 +45,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
preview
),
cmd!(
"document.exportForWeb.saveColorTable",
"Save Color Table",
[],
None,
"{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. An empty path, jpg and png24 are an error; the document and the settings do not change",
has_doc,
save_color_table
),
cmd!(
query "webExport.loadColorTable",
"Load Color Table",
[],
None,
"{path | dataBase64: a color table file (.act: 768 bytes of 256 colors, or 772 bytes with the number of colors used, 1–256, and the transparent entry's index), …the settings of document.exportForWeb (preset?, format?: gif|png8…)} the settings with the table loaded: its colors other than the transparent entry become colorTable.customPalette, colors becomes the number of colors it uses (at least 2), the table's other edits (locked, transparent, deleted, shifted, webShift and sort) are cleared and webSnap becomes 0 →{colors: [\"#rrggbb\"…] (the colors it uses, in file order), transparentIndex (null for none; an index past the colors used names none), settings}. Give exactly one of path and dataBase64; another file size, a count of 0 or above 256, jpg and png24 are errors; nothing is remembered",
always,
load_color_table
),
cmd!(
query "webExport.optimizeToFileSize",
"Optimize to File Size",
@@ -1253,24 +1271,7 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
if !(kbps.is_finite() && kbps > 0.0) {
return Err(bad(P, format!("kbps must be a positive number, not {kbps}")));
}
let st = s.doc()?;
let doc = &st.doc;
let failed = vectorcraft_render::decode_failures();
let r = render(doc, &settings).map_err(|e| bad(P, e))?;
let warnings = undecoded(failed);
let areas = doc.slice_layout();
let selected = super::slices::selected_slices(doc, &st.selection);
let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(P, e))?;
let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1);
let o = match p.get("slice").and_then(Value::as_u64) {
Some(n) => {
let c = cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(P, format!("no slice {n} in the image (see slice.list)")))?;
let [x0, y0, x1, y1] = c.px;
optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, &settings)
}
None => optimize(doc, &r.rgba, r.width, r.height, &settings),
}
.map_err(|e| bad(P, e))?;
let Shown { o, images, warnings } = shown(s, &settings, p, P, true)?;
let mut out = json!({
"format": settings.format.id(), "width": o.width, "height": o.height, "bytes": o.bytes.len(),
"seconds": download_seconds(o.bytes.len(), kbps), "kbps": kbps, "slices": images, "warnings": warnings,
@@ -1294,6 +1295,195 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The file Save writes with some settings, as the preview shows it.
struct Shown {
o: Optimized,
/// The images an export writes (0 when they were not counted).
images: usize,
/// The export's warnings.
warnings: Vec<&'static str>,
}
/// What Save writes with `settings` for the whole image, or for the slice `p.slice` names (1-based,
/// from `slice.list`), for the command `cmd`. A `slice` that is not a whole number from 1 up is an
/// error. With `count_images` false and no `slice`, the slices are not looked up: `images` is 0,
/// and selected slices with none selected are not an error.
fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str, count_images: bool) -> Result<Shown> {
let slice = match p.get("slice") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, "`slice` is a slice number from `slice.list`"))?),
};
let st = s.doc()?;
let doc = &st.doc;
let failed = vectorcraft_render::decode_failures();
let r = render(doc, settings).map_err(|e| bad(cmd, e))?;
let warnings = undecoded(failed);
let areas = doc.slice_layout();
let cells = if count_images || slice.is_some() {
let selected = super::slices::selected_slices(doc, &st.selection);
cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))?
} else {
vec![]
};
let images = if count_images {
cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1)
} else {
0
};
let o = match slice {
Some(n) => {
let c =
cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(cmd, format!("no slice {n} in the image (see slice.list)")))?;
let [x0, y0, x1, y1] = c.px;
optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, settings)
}
None => optimize(doc, &r.rgba, r.width, r.height, settings),
}
.map_err(|e| bad(cmd, e))?;
Ok(Shown { o, images, warnings })
}
// ---------- color table files ----------
/// The extension of a color table file.
pub const COLOR_TABLE_EXT: &str = "act";
/// The size of a color table file with its color count and transparent entry: 256 RGB triples
/// (768 bytes), then the two numbers, each two bytes, most significant byte first.
pub const ACT_LEN: usize = 772;
/// The size of a color table file of 256 RGB triples alone.
const ACT_COLORS_LEN: usize = 768;
/// The transparent entry of a color table file that has none.
const ACT_NO_TRANSPARENT: u16 = 0xFFFF;
/// The error for bytes that are not a color table file.
const NOT_A_TABLE: &str = "not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors";
/// A color table file (`.act`) of `colors`, a palette format's color table in file order: each
/// color as written, red, green and blue, one byte each; zero bytes up to 256 colors; the number
/// of colors and the index of the transparent entry (`0xFFFF` for none), two bytes each, most
/// significant byte first. Colors past the 256th are left out.
pub fn act_bytes(colors: &[TableColor]) -> Vec<u8> {
let colors = &colors[..colors.len().min(256)];
let mut out = vec![0u8; ACT_LEN];
for (slot, c) in out.as_chunks_mut::<3>().0.iter_mut().zip(colors) {
*slot = c.color;
}
// At most 256 colors: both numbers fit in two bytes.
let count = colors.len() as u16;
let transparent = colors.iter().position(|c| c.transparent).map_or(ACT_NO_TRANSPARENT, |i| i as u16);
out[ACT_COLORS_LEN..ACT_COLORS_LEN + 2].copy_from_slice(&count.to_be_bytes());
out[ACT_COLORS_LEN + 2..].copy_from_slice(&transparent.to_be_bytes());
out
}
/// The colors of a color table file and its transparent entry.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ActTable {
/// The colors the file uses, in its order.
pub colors: Vec<[u8; 3]>,
/// The index of the transparent entry, when the file names one of `colors`.
pub transparent: Option<usize>,
}
/// Read a color table file: 768 bytes are 256 colors; 772 bytes add the number of colors used
/// (1 to 256) and the transparent entry's index. A transparent index past the colors used names
/// no entry. Any other size, or a count of 0 or above 256, is an error.
pub fn read_act(bytes: &[u8]) -> std::result::Result<ActTable, String> {
let (count, transparent) = match bytes.len() {
ACT_COLORS_LEN => (256, None),
ACT_LEN => {
let at = |i: usize| usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]]));
(at(ACT_COLORS_LEN), Some(at(ACT_COLORS_LEN + 2)))
}
_ => return Err(NOT_A_TABLE.into()),
};
if !(1..=256).contains(&count) {
return Err(NOT_A_TABLE.into());
}
let colors: Vec<[u8; 3]> = bytes[..count * 3].as_chunks::<3>().0.to_vec();
Ok(ActTable { colors, transparent: transparent.filter(|i| *i < count) })
}
/// `settings` with the color table `t` loaded: its colors other than the transparent entry become
/// the fixed palette (`colorTable.customPalette`), and `colors` becomes the number of colors the
/// file uses (at least 2). The table's other edits (locked, transparent, deleted, shifted and
/// web-shifted colors, and its sort) are cleared and Web Snap is set to 0, so every loaded color is
/// written as it is, in the file's order. A table whose only color is its transparent entry loads
/// that color.
pub fn with_table(settings: &WebSettings, t: &ActTable) -> WebSettings {
let mut s = settings.clone();
let mut palette: Vec<String> = t.colors.iter().enumerate().filter(|(i, _)| Some(*i) != t.transparent).map(|(_, c)| hex(*c)).collect();
if palette.is_empty() {
palette = t.colors.iter().map(|c| hex(*c)).collect();
}
s.colors = (t.colors.len() as u16).clamp(2, 256);
s.web_snap = 0;
s.color_table = ColorTable { custom_palette: palette, ..ColorTable::default() };
s
}
/// `cmd`'s error for a format without a color table.
fn no_table(cmd: &str, f: WebFormat) -> super::EngineError {
let format = f.id();
bad(cmd, format!("`{format}` has no color table: use gif or png8"))
}
fn save_color_table(s: &mut Session, p: &Value) -> Result<Value> {
const P: &str = "document.exportForWeb.saveColorTable";
let settings = s.web_settings(p).map_err(|e| bad(P, e))?;
if !settings.format.palette() {
return Err(no_table(P, settings.format));
}
let path = text_param(p, "path", P)?;
if path.is_some_and(|p| p.trim().is_empty()) {
return Err(bad(P, "`path` is empty: give a file path, or leave it out for `dataBase64`"));
}
let path = path.map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() });
let Shown { o, warnings, .. } = shown(s, &settings, p, P, false)?;
let bytes = act_bytes(&o.colors);
let mut out = json!({
"colors": o.colors.len().min(256),
"transparentIndex": o.colors.iter().position(|c| c.transparent),
"bytes": bytes.len(),
"warnings": warnings,
});
match path {
Some(path) => {
super::fileio::write_file(&path, &bytes)?;
out["path"] = json!(path);
}
None => out["dataBase64"] = json!(vectorcraft_format::base64_encode(&bytes)),
}
Ok(out)
}
fn load_color_table(s: &mut Session, p: &Value) -> Result<Value> {
const L: &str = "webExport.loadColorTable";
let settings = s.web_settings(p).map_err(|e| bad(L, e))?;
if !settings.format.palette() {
return Err(no_table(L, settings.format));
}
// One byte more than a color table shows a file that is too long.
let bytes = match (text_param(p, "path", L)?, text_param(p, "dataBase64", L)?) {
(Some(path), None) => super::fileio::read_file_head(path, ACT_LEN + 1)?,
(None, Some(b64)) => {
// Text past the base64 of the longest table makes the file too long.
if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > ACT_LEN.div_ceil(3) * 4 {
return Err(bad(L, NOT_A_TABLE));
}
super::scripts::decode_head(b64, ACT_LEN + 1).ok_or_else(|| bad(L, "bad dataBase64"))?
}
_ => return Err(bad(L, "give exactly one of `path` and `dataBase64`")),
};
let t = read_act(&bytes).map_err(|e| bad(L, e))?;
let loaded = with_table(&settings, &t);
Ok(json!({
"colors": t.colors.iter().map(|c| hex(*c)).collect::<Vec<_>>(),
"transparentIndex": t.transparent,
"settings": loaded.to_json(),
}))
}
// ---------- Optimize to File Size ----------
/// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image
+12 -2
View File
@@ -53,6 +53,9 @@ pub struct DocState {
pub interaction: Option<Interaction>,
/// Edits made while this is open are one undo step (a scrubbed numeric field).
pub undo_group: Option<UndoGroup>,
/// The built-in effect the edit in progress applies ([`crate::Session::edit_effect`]): the
/// undo step it records keeps it ([`DocState::push_undo`]).
pub(crate) effect_step: Option<&'static str>,
/// For Object → Transform → Transform Again (⌘D): what the last transformation was. A
/// transform command keeps the `copy`, `typeAreas` and `patterns` it used, and `strokes` and
/// `corners` when it scales; a drag keeps the params of its last preview with the values that
@@ -410,6 +413,7 @@ impl DocState {
symbol_edit_return: Default::default(),
interaction: None,
undo_group: None,
effect_step: None,
last_transform: None,
last_selection_cmd: None,
recalled_selection: RecalledSelection::default(),
@@ -593,7 +597,9 @@ impl DocState {
Some(l) if l.selection == it.selection => l.selection.clone(),
_ => it.selection,
};
let effect = std::mem::replace(&mut self.effect_step, it.effect);
self.push_undo(it.label, it.doc, selection);
self.effect_step = effect;
if let Some(paints) = it.color_mode_paints
&& let Some(e) = self.history.undo.last_mut()
{
@@ -609,8 +615,10 @@ impl DocState {
}
/// Record an undo step: `doc` and `selection` as they were before an edit (the document now is
/// the one after it). In an undo group only the group's first edit records one: the edits
/// after it extend that step.
/// after it extend that step. A new step named after the effect in [`DocState::effect_step`]
/// keeps that effect ([`HistoryEntry::effect`]); a step an undo group names keeps none.
pub(crate) fn push_undo(&mut self, mut label: String, doc: Arc<Document>, selection: Arc<Selection>) {
let mut effect = self.effect_step;
if let Some(g) = &mut self.undo_group {
let recorded = |first: &Arc<Document>| self.history.undo.last().is_some_and(|l| Arc::ptr_eq(&l.doc, first));
if g.first.as_ref().is_some_and(recorded) {
@@ -621,9 +629,11 @@ impl DocState {
g.first = Some(doc.clone());
if let Some(l) = &g.label {
label = l.clone();
effect = None;
}
}
let e = HistoryEntry::kept(label, doc, selection, &self.doc);
let mut e = HistoryEntry::kept(label, doc, selection, &self.doc);
e.effect = effect.filter(|id| crate::history::effect_step_label(id) == Some(e.label.as_str()));
self.history.undo.push(e);
self.history.clear_redo();
self.history.trim();
+19
View File
@@ -25,6 +25,9 @@ pub struct HistoryEntry {
next: usize,
/// The template and name `label` was made from ([`Session::edit_named`]).
pub(crate) named: Option<NamedStep>,
/// The built-in effect the step applied or edited, when the step is named after it
/// ([`Session::edit_effect`]).
pub(crate) effect: Option<&'static str>,
/// A number no other step takes ([`History::step`]).
serial: u64,
/// Original and changed new-art paints, only for steps that change them: a document color mode
@@ -49,6 +52,7 @@ impl Clone for HistoryEntry {
next_bytes: self.next_bytes,
next: self.next,
named: self.named.clone(),
effect: self.effect,
serial: self.serial,
color_mode_paints: self.color_mode_paints.clone(),
color_mode_bytes: self.color_mode_bytes,
@@ -63,6 +67,12 @@ fn next_serial() -> u64 {
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
/// The name of the undo step that applies or edits built-in effect `id`: its menu label without
/// the ellipsis. `None` for an id no built-in effect has.
pub(crate) fn effect_step_label(id: &str) -> Option<&'static str> {
vectorcraft_render::effects::built_in_effect(id).map(|(_, label)| label.trim_end_matches('…'))
}
/// A step name made by filling the `{name}` placeholder of a template with a name
/// ([`Session::edit_named`]).
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -95,6 +105,7 @@ impl HistoryEntry {
next_bytes,
next: std::ptr::from_ref(next) as usize,
named: None,
effect: None,
serial: next_serial(),
color_mode_paints: None,
color_mode_bytes: 0,
@@ -109,6 +120,13 @@ impl HistoryEntry {
self.named.as_ref().filter(|n| n.label() == self.label)
}
/// The id of the built-in effect the step applied or edited, while the step's label is still
/// the effect's name: `None` for any other step, and for one whose label was changed since it
/// was recorded.
pub fn effect(&self) -> Option<&'static str> {
self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str()))
}
/// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the
/// document before the undo, whose next state is now `now` (that step's document). Its figures
/// are that step's the other way round when `doc` is still the document they were taken
@@ -128,6 +146,7 @@ impl HistoryEntry {
next_bytes: costs.bytes,
next: Arc::as_ptr(now) as usize,
named: None,
effect: None,
serial: next_serial(),
color_mode_paints: None,
color_mode_bytes: 0,
+3
View File
@@ -4,6 +4,9 @@ use super::{Affine, Arc, Document, NodeId, Selection, Value};
#[derive(Clone, Debug)]
pub struct Interaction {
pub label: String,
/// The built-in effect the last preview applied or edited ([`crate::Session::edit_effect`]):
/// the step the interaction records keeps it when `label` is the effect's name.
pub(crate) effect: Option<&'static str>,
pub doc: Arc<Document>,
/// The selection the previews start from (shared, so a preview frame copies nothing).
pub selection: Arc<Selection>,
+20
View File
@@ -30,6 +30,7 @@ pub use cmd::clipboard::{Clipboard, SourceLayer};
pub use cmd::create::constrain_click;
pub use cmd::distortcmds::{perspective_click, width_point_pair};
pub use cmd::flare::flare_settings;
pub use cmd::gradient::StopOwner;
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
pub use cmd::params::{check_keys, check_params};
pub use cmd::pathops::auto_simplify_level;
@@ -218,6 +219,9 @@ 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 Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder
/// ([`Session::attach_startup_scripts_dir`]).
startup_scripts_dir: Option<std::path::PathBuf>,
/// The folder of File Info's metadata templates; `None`: no folder
/// ([`Session::attach_metadata_templates_dir`]).
metadata_templates_dir: Option<std::path::PathBuf>,
@@ -310,6 +314,9 @@ pub struct Session {
/// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or
/// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]).
pub(crate) trace_hand_off: Option<cmd::Traced>,
/// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or
/// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]).
pub(crate) retype_hand_off: Option<cmd::RetypeFound>,
/// Whether a click or drag of the place cursor asks the frontend to place its file
/// ([`UiRequest::Place`]) instead of running `file.place`: the desktop app sets it to read the
/// file off the UI thread. False: the file is placed at once.
@@ -338,6 +345,19 @@ pub struct Session {
/// `script.run` starts the job and returns, and the frontend advances it once per frame
/// ([`Session::script_pump`]). Off, `script.run` advances it to its end.
pub script_frames: bool,
/// The runs `script.startup.run` queued in the app, each started when the run before it ends
/// ([`Session::script_pump`]).
pub(crate) script_queue: std::collections::VecDeque<script::startup::Queued>,
/// The file access scope of the request that queued [`Self::script_queue`], in which each queued
/// run starts and is read.
pub(crate) script_queue_scope: Option<file_access::ScopeHandle>,
pub(crate) script_queue_then: Option<script::Request>,
/// While a startup script runs: the launch marker's entry naming it
/// ([`vectorcraft_plugins::safe_mode::loading`]).
pub(crate) startup_loading: Option<vectorcraft_plugins::safe_mode::Loading>,
/// The queued runs that could not start, as (name, error), until the frontend takes them
/// ([`Session::take_startup_failures`]).
pub(crate) startup_failures: Vec<(String, String)>,
/// Each open document's highest next id a run has seen, by [`DocState::uid`].
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
/// While a slice of a script runs in this session.
+5
View File
@@ -71,6 +71,10 @@ pub struct Prefs {
pub show_tool_cards: bool,
/// Other Script… warns before it runs a chosen script.
pub show_external_script_warning: bool,
/// General › Run Startup Scripts: the `.jsx` files of the Startup Scripts folder run when the
/// app starts and before each script chosen from File › Scripts (`script.startup.run`). Off by
/// default.
pub run_startup_scripts: bool,
pub anti_aliased_artwork: bool,
pub select_same_tint_percent: bool,
pub show_home_screen: bool,
@@ -496,6 +500,7 @@ impl Default for Prefs {
show_tool_tips: true,
show_tool_cards: false,
show_external_script_warning: true,
run_startup_scripts: false,
anti_aliased_artwork: true,
select_same_tint_percent: false,
show_home_screen: true,
+6 -2
View File
@@ -66,6 +66,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session};
mod tags;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
/// The error for an object that was deleted, or that came from an earlier run.
@@ -1353,7 +1355,7 @@ fn selection_of(h: &Host, uid: u64) -> Answer {
/// `[]`. Every one must be an object of that document that can be selected.
fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId>, HostError> {
let list: Vec<&Data> = match v {
Data::Null | Data::Undefined => Vec::new(),
Data::Null => Vec::new(),
Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))),
Data::Array(a) => a.iter().collect(),
d => vec![d],
@@ -2211,6 +2213,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
.into_iter()
.map(|m| later(l, "Document", m)),
);
document.push(("tags".into(), get(l, tags::doc_tags)));
classes.push(class("Document", None, document, None));
classes.push(class(
"PageItems",
@@ -2231,6 +2234,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("parent", get(l, item_parent)),
("name", property(l, item_name, item_set_name)),
("note", property(l, item_note, item_set_note)),
("tags", get(l, tags::item_tags)),
("hidden", property(l, item_hidden, item_set_hidden)),
("locked", property(l, item_locked, item_set_locked)),
("selected", property(l, item_selected, item_set_selected)),
@@ -2259,7 +2263,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
"layer",
"pixelAligned",
"sliced",
"tags",
"uRL",
"uuid",
"visibilityVariable",
@@ -2283,6 +2286,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]),
None,
));
classes.extend(tags::classes(l));
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?;
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
realm.define_host_globals(vec![
+306
View File
@@ -0,0 +1,306 @@
//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Tags/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Tag/> describe them: name and value pairs on a
//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0.
//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items,
//! and cannot add a tag, since a tag belongs to a page item.
//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and
//! `getByName` gives the first tag with the name.
//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags.
//! - A tag that was deleted, or whose page item was, throws an error on every member.
use std::ops::ControlFlow;
use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag};
use super::{
Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get,
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc,
};
use crate::NodeId;
use serde_json::json;
use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref};
/// The error for a tag that was deleted, or that came from an earlier run.
pub const STALE_TAG: &str = "Stale tag";
/// The error of `Document.tags.add()`.
pub const NO_OWNER: &str = "A tag is added to a page item's tags, not to the document's";
/// What a `Tags` collection lists the tags of.
#[derive(Clone, Copy)]
enum Owner {
Item(Item),
Doc(Doc),
}
/// The owner of the `Tags` collection `d` names.
fn owner_of(h: &Host, d: &Data) -> std::result::Result<Owner, HostError> {
let Some(handle) = handle_of(d, "Tags") else { return Err(HostError::Type("this is not a Tags collection".into())) };
match handle.as_slice() {
[run, uid] => find_doc(h, *run, *uid).map(Owner::Doc).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())),
[run, uid, high, low] => Ok(Owner::Item(resolve_item(h, *run, *uid, *high, *low)?)),
_ => Err(HostError::Type("this is not a Tags collection".into())),
}
}
/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must
/// still be in its document.
fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some()));
if !alive {
return Err(HostError::Error(STALE_ITEM.into()));
}
Ok(Item { doc, id })
}
/// Calls `f` with each tag `owner` lists, in order, and the page item it is on, until `f` breaks.
/// The tags are borrowed from the document, not copied. `Document.tags` charges the run by the
/// number of page items read.
fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> ControlFlow<()>) -> std::result::Result<(), HostError> {
match owner {
Owner::Item(item) => with_doc(h, item.doc, |_, st| {
if let Some(n) = st.doc.node(item.id) {
for t in crate::cmd::tags::tags_of(n) {
if f(item.id, t).is_break() {
break;
}
}
}
Ok(())
}),
Owner::Doc(doc) => with_doc(h, doc, |_, st| {
let ids = page_items(h, st);
h.charge_call(ids.len() as u64)?;
for id in ids.iter() {
if let Some(n) = st.doc.node(*id) {
for t in crate::cmd::tags::tags_of(n) {
if f(*id, t).is_break() {
return Ok(());
}
}
}
}
Ok(())
}),
}
}
/// The first tag `owner` lists for which `pick` holds: its page item and its id.
fn find(h: &Host, owner: Owner, mut pick: impl FnMut(&ObjectTag) -> bool) -> std::result::Result<Option<(NodeId, u64)>, HostError> {
let mut found = None;
each(h, owner, |id, t| {
if pick(t) {
found = Some((id, t.id));
return ControlFlow::Break(());
}
ControlFlow::Continue(())
})?;
Ok(found)
}
fn doc_of_owner(owner: Owner) -> Doc {
match owner {
Owner::Item(i) => i.doc,
Owner::Doc(d) => d,
}
}
fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
let [high, low] = id_parts(id);
let [tag_high, tag_low] = id_parts(NodeId(tag));
host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low])
}
/// `PageItem.tags`.
pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer {
let item = item_of(h, arg(a, 0))?;
let [high, low] = id_parts(item.id);
Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low]))
}
/// `Document.tags`.
pub(super) fn doc_tags(h: &Host, a: &[Data]) -> Answer {
let doc = doc_of(h, arg(a, 0), "Document")?;
Ok(host_ref("Tags", &[float(h.run), float(doc.uid)]))
}
// ---- Tags ----
fn tags_length(h: &Host, a: &[Data]) -> Answer {
let owner = owner_of(h, arg(a, 0))?;
let mut count = 0u64;
each(h, owner, |_, _| {
count += 1;
ControlFlow::Continue(())
})?;
Ok(num(float(count)))
}
fn tags_parent(h: &Host, a: &[Data]) -> Answer {
match owner_of(h, arg(a, 0))? {
Owner::Item(item) => Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))),
Owner::Doc(doc) => Ok(doc_ref(h, doc.uid)),
}
}
fn tags_at(h: &Host, a: &[Data]) -> Answer {
let owner = owner_of(h, arg(a, 0))?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
let mut left = i;
let found = find(h, owner, |_| {
let here = left == 0;
left = left.wrapping_sub(1);
here
})?;
Ok(found.map_or(Data::Undefined, |(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)))
}
fn tags_by_name(h: &Host, a: &[Data]) -> Answer {
let owner = owner_of(h, arg(a, 0))?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
let found = find(h, owner, |t| t.name == *name)?;
found.map(|(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
}
fn tags_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => tags_by_name(h, a),
Data::Number(_) => match tags_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// `tags.add()`: a new tag with an empty name and value after the item's other tags.
fn tags_add(h: &Host, a: &[Data]) -> Answer {
let item = match owner_of(h, arg(a, 0))? {
Owner::Item(item) => item,
Owner::Doc(_) => return Err(HostError::Error(NO_OWNER.into())),
};
edit_item(h, item, "object.tag.add", &json!({"id": item.id.0}))?;
// The new tag is the item's last. Its id is read from the document, since the command's answer
// gives it as a number, which is exact only up to 2^53.
let tag = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).last().map(|t| t.id)));
let tag = tag.ok_or_else(|| HostError::Error("the tag was not added".into()))?;
Ok(tag_ref(h, item.doc, item.id, tag))
}
/// `tags.removeAll()`: deletes every tag in the collection, in one command.
fn tags_remove_all(h: &Host, a: &[Data]) -> Answer {
let owner = owner_of(h, arg(a, 0))?;
let mut ids: Vec<u64> = Vec::new();
each(h, owner, |id, _| {
if ids.last() != Some(&id.0) {
ids.push(id.0);
}
ControlFlow::Continue(())
})?;
if !ids.is_empty() {
let doc = doc_of_owner(owner);
on_doc(h, doc.uid, true, |h| command(h, "object.tag.removeAll", &json!({"ids": ids})))?;
}
Ok(Data::Undefined)
}
// ---- Tag ----
/// A tag: its page item and its id there.
#[derive(Clone, Copy)]
struct TagRef {
item: Item,
tag: u64,
}
/// The tag `d` names, which must still be on its page item.
fn tag_of(h: &Host, d: &Data) -> std::result::Result<(TagRef, ObjectTag), HostError> {
let Some(handle) = handle_of(d, "Tag") else { return Err(HostError::Type("this is not a Tag".into())) };
let [run, uid, high, low, tag_high, tag_low] = handle.as_slice() else { return Err(HostError::Type("this is not a Tag".into())) };
let item = resolve_item(h, *run, *uid, *high, *low)?;
let tag = id_of(*tag_high, *tag_low).ok_or_else(|| HostError::Error(STALE_TAG.into()))?.0;
let found = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).iter().find(|t| t.id == tag).cloned()));
let t = found.ok_or_else(|| HostError::Error(STALE_TAG.into()))?;
Ok((TagRef { item, tag }, t))
}
fn tag_name(h: &Host, a: &[Data]) -> Answer {
Ok(text(tag_of(h, arg(a, 0))?.1.name))
}
fn tag_value(h: &Host, a: &[Data]) -> Answer {
Ok(text(tag_of(h, arg(a, 0))?.1.value))
}
/// Sets the tag's `key` (`name` or `value`) to the string the script gives, with no command when
/// it already has it.
fn set_text(h: &Host, a: &[Data], key: &str) -> Answer {
let Data::String(v) = arg(a, 1) else { return Err(HostError::Type(format!("{key} must be a string"))) };
if v.len() > MAX_TAG_TEXT {
return Err(HostError::Range(format!("a tag's {key} is longer than 65,536 bytes")));
}
let (t, now) = tag_of(h, arg(a, 0))?;
let same = if key == "name" { now.name == *v } else { now.value == *v };
if !same {
edit_item(h, t.item, "object.tag.set", &json!({"id": t.item.id.0, "tag": t.tag, key: v}))?;
}
Ok(Data::Undefined)
}
fn tag_set_name(h: &Host, a: &[Data]) -> Answer {
set_text(h, a, "name")
}
fn tag_set_value(h: &Host, a: &[Data]) -> Answer {
set_text(h, a, "value")
}
fn tag_parent(h: &Host, a: &[Data]) -> Answer {
let (t, _) = tag_of(h, arg(a, 0))?;
Ok(with_doc(h, t.item.doc, |_, st| item_ref(h, st, t.item.id)))
}
fn tag_remove(h: &Host, a: &[Data]) -> Answer {
let (t, _) = tag_of(h, arg(a, 0))?;
edit_item(h, t.item, "object.tag.remove", &json!({"id": t.item.id.0, "tag": t.tag}))?;
Ok(Data::Undefined)
}
/// `Tags.typename`, which throws like every other member once the collection's owner is gone.
fn tags_typename(h: &Host, a: &[Data]) -> Answer {
owner_of(h, arg(a, 0))?;
Ok(text("Tags"))
}
/// `Tag.typename`, which throws like every other member once the tag is gone.
fn tag_typename(h: &Host, a: &[Data]) -> Answer {
tag_of(h, arg(a, 0))?;
Ok(text("Tag"))
}
/// The `Tags` and `Tag` classes.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
let tags: Vec<(String, HostMember)> = named(vec![
("typename", get(l, tags_typename)),
("length", get(l, tags_length)),
("parent", get(l, tags_parent)),
("index", method(l, tags_index)),
("getByName", method(l, tags_by_name)),
("add", method(l, tags_add)),
("removeAll", method(l, tags_remove_all)),
]);
let tag = named(vec![
("typename", get(l, tag_typename)),
("name", property(l, tag_name, tag_set_name)),
("value", property(l, tag_value, tag_set_value)),
("parent", get(l, tag_parent)),
("remove", method(l, tag_remove)),
]);
vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)]
}
+18 -4
View File
@@ -1080,14 +1080,28 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
/// `path`, of both when both are given and of every grant when neither is (`script.grants.revoke`).
/// → how many were removed.
pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result<usize> {
/// The spellings of each are tried in order, the script's first, and the first pair that some grant
/// holds is the one removed, so a grant kept under the spellings given first is removed without the
/// grants of later ones. → how many were removed.
pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result<usize> {
let store = data_dir.with_file_name(GRANTS_FILE);
let _lock = lock_store(&store)?;
let grants = try_read_store(&store)?;
let before = grants.len();
let kept: Vec<serde_json::Value> =
grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect();
// `None` matches any value; `Some(name)` only that name.
fn spellings(names: Option<&[String]>) -> Vec<Option<&str>> {
match names {
None => vec![None],
Some(names) => names.iter().map(|n| Some(n.as_str())).collect(),
}
}
let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| {
script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p)
};
let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p)));
let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair)));
let Some(pair) = pair else { return Ok(0) };
let kept: Vec<serde_json::Value> = grants.into_iter().filter(|g| !matches(g, pair)).collect();
let removed = before - kept.len();
if removed > 0 {
write_store(&store, kept)?;
+3 -3
View File
@@ -237,7 +237,7 @@ fn hidden(entry: &std::fs::DirEntry) -> bool {
/// Does Windows mark the file or folder of `m` hidden or system?
#[cfg(windows)]
fn hidden_meta(m: &std::fs::Metadata) -> bool {
pub(super) fn hidden_meta(m: &std::fs::Metadata) -> bool {
use std::os::windows::fs::MetadataExt as _;
const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4;
m.file_attributes() & HIDDEN_OR_SYSTEM != 0
@@ -245,13 +245,13 @@ fn hidden_meta(m: &std::fs::Metadata) -> bool {
/// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name.
#[cfg(not(windows))]
fn hidden_meta(_: &std::fs::Metadata) -> bool {
pub(super) fn hidden_meta(_: &std::fs::Metadata) -> bool {
false
}
/// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows
/// marks hidden or system, which a listing leaves out.
fn plain(path: &Path, folder: bool, shown: bool) -> bool {
pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
std::fs::symlink_metadata(path)
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
}
+53 -7
View File
@@ -72,6 +72,7 @@ use crate::{
pub mod files;
pub mod folder;
pub mod startup;
/// The most bytes of source a run takes, as a file or as `source`.
pub const MAX_SOURCE_BYTES: usize = 8 << 20;
@@ -186,6 +187,7 @@ pub(crate) fn refused_text(id: &str) -> String {
}
/// A request to run a script.
#[derive(Clone)]
pub(crate) struct Request {
/// The run's name; unless `name_given`, a `#script` line in the script replaces it.
pub name: String,
@@ -1716,9 +1718,10 @@ fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u
}
impl Session {
/// Is a script running? While one is, the commands that change anything are refused.
/// Is a script running, or a run `script.startup.run` queued waiting to start at the next
/// [`Self::script_pump`]? While one is, the commands that change anything are refused.
pub fn script_running(&self) -> bool {
self.script_key.is_some()
self.script_key.is_some() || !self.script_queue.is_empty()
}
/// The named engine of the running script.
@@ -1931,9 +1934,10 @@ impl Session {
}
}
/// Asks the running script to stop; it is rolled back at the next slice. False with none running.
/// Asks the running script to stop; it is rolled back at the next slice. Between two runs
/// `script.startup.run` queued, the next one stops as it starts. False with none running.
pub fn script_request_stop(&mut self) -> bool {
if self.script_key.is_none() {
if !self.script_running() {
return false;
}
self.script_stop.set();
@@ -1941,9 +1945,16 @@ impl Session {
}
/// Stops the running script at once and puts everything back, with the report of a stopped run
/// ([`Self::script_report`]). False with none running.
/// ([`Self::script_report`]). Between two runs `script.startup.run` queued, the queued runs are
/// not started, and the report stays the last run's. False with none running or queued.
pub fn script_abandon(&mut self) -> bool {
let Some(key) = self.script_key.take() else { return false };
// The runs queued after it are not started.
let queued = !self.script_queue.is_empty();
self.script_queue.clear();
self.script_queue_scope = None;
self.script_queue_then = None;
self.startup_ended();
let Some(key) = self.script_key.take() else { return queued };
let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
self.script_gone(key, console::Ending::Stopped);
return true;
@@ -1975,6 +1986,16 @@ impl Session {
cmd::compositefonts::sync(self);
}
/// A script named `name` that did not start because its file could not be read as a script:
/// the Script Console gets a run with a start line, `message` as its error and an end line.
pub(crate) fn note_unread(&mut self, name: &str, message: &str) {
self.script_runs += 1;
let name = console::line_name(name);
for entry in [console::Entry::Start, console::Entry::Error(format!("{name}: {message}")), console::Entry::End(console::Ending::Error)] {
self.script_console.push(console::ConsoleLine { run: self.script_runs, name: name.clone(), entry }, false);
}
}
/// A script can't start while a document holds a drag in progress or an undo group, which its
/// one undo step could not take in.
fn settle_for_script(&mut self) -> Result<()> {
@@ -2194,8 +2215,33 @@ impl Session {
}
/// Advances the running script by one slice. `None` while it is still running; otherwise the
/// run has ended: its report, or the error that ended it, with the documents put back.
/// run has ended: its report, or the error that ended it, with the documents put back. When
/// `script.startup.run` queued more runs, the next one starts at the pump after that, so the
/// ended run's report ([`Self::script_report`]) stays until then; a queued run that cannot start
/// is kept for [`Self::take_startup_failures`].
pub fn script_pump(&mut self) -> Option<Result<Value>> {
if self.script_key.is_none() {
// A stop asked for between two runs stops the run that starts now, which clears it.
let stop = self.script_stop.is_set();
self.start_queued();
if stop && (self.script_key.is_some() || !self.script_queue.is_empty()) {
self.script_stop.set();
} else {
self.script_stop.clear();
}
return None;
}
// Held aside while the run ends, so that its commit does not see the queue as a running script.
let queue = std::mem::take(&mut self.script_queue);
let result = self.pump_one();
self.script_queue = queue;
let result = result?;
self.startup_ended();
Some(result)
}
/// [`Self::script_pump`] for the running script alone.
fn pump_one(&mut self) -> Option<Result<Value>> {
let key = self.script_key.take()?;
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
self.script_gone(key, console::Ending::Internal);
+126
View File
@@ -0,0 +1,126 @@
//! The Startup Scripts folder: the `.jsx` files `script.startup.run` runs, one after another, when
//! the app starts and before a script chosen from File › Scripts runs ([`list`]), and the read of
//! one of them when its turn comes ([`read`]).
//!
//! Only the folder's own files are taken, never its subfolders. A listing follows no link: a
//! symbolic link or a Windows junction is left out, and so is a folder that is itself a link. Names
//! that start with a dot, files Windows marks hidden or system, names that are not Unicode, names
//! longer than [`folder::MAX_NAME_BYTES`] and files whose extension is not `.jsx` are left out too.
//! The files are sorted by name without regard to case, then by name.
//!
//! The limits are the Scripts folder's ([`folder::MAX_ENTRIES`], [`folder::MAX_SCRIPTS`] and
//! [`folder::MAX_SCAN`]), VectorCraft's own values. A listing that reaches one keeps what it found
//! and says so ([`Listing::truncated`]).
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;
use super::folder;
/// What a Startup Scripts folder holds.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Listing {
/// The scripts, in the order they run.
pub scripts: Vec<PathBuf>,
/// Some scripts may be missing: a limit was reached or an entry could not be read.
pub truncated: bool,
/// The folder is there and could not be read, or is a link.
pub unreadable: bool,
}
/// Does the file name `name` name a startup script: a `.jsx` file (in any case) whose name does not
/// start with a dot and has at most [`folder::MAX_NAME_BYTES`] bytes?
pub fn takes(name: &str) -> bool {
!name.starts_with('.')
&& name.len() <= folder::MAX_NAME_BYTES
&& Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx"))
}
/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist
/// gives an empty listing.
pub fn list(root: &Path) -> Listing {
let start = std::time::Instant::now();
list_with(root, &folder::Limits::default(), &mut || start.elapsed())
}
/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones);
/// `elapsed` says how long the listing has taken.
pub fn list_with(root: &Path, limits: &folder::Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing {
let unreadable = Listing { unreadable: true, ..Listing::default() };
match std::fs::symlink_metadata(root) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(),
Err(_) => return unreadable,
Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable,
Ok(_) => {}
}
if root.to_str().is_none() {
return unreadable;
}
let Ok(entries) = std::fs::read_dir(root) else { return unreadable };
let mut listing = Listing::default();
let mut names: Vec<String> = vec![];
for (visited, entry) in entries.enumerate() {
if visited >= limits.entries || elapsed() > limits.time {
listing.truncated = true;
break;
}
let Ok(entry) = entry else {
listing.truncated = true;
continue;
};
let Ok(name) = entry.file_name().into_string() else { continue };
if !takes(&name) {
continue;
}
let Ok(kind) = entry.file_type() else {
listing.truncated = true;
continue;
};
if !kind.is_file() || kind.is_symlink() || entry.metadata().is_ok_and(|m| folder::hidden_meta(&m)) {
continue;
}
names.push(name);
}
names.sort_by(|a, b| (a.to_lowercase(), a).cmp(&(b.to_lowercase(), b)));
if names.len() > limits.scripts {
listing.truncated = true;
names.truncate(limits.scripts);
}
listing.scripts = names.into_iter().map(|n| root.join(n)).collect();
listing
}
/// Is `path` a startup script a listing of `root` can hold now: a file [`takes`] names, directly in
/// `root`, where neither `root` nor the file is a link and the file is not marked hidden or system?
pub fn holds(root: &Path, path: &Path) -> bool {
if path.parent() != Some(root) {
return false;
}
let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false };
takes(name) && folder::plain(root, true, false) && folder::plain(path, false, true)
}
/// The first `max` bytes of the startup script at `path`, or `None` when [`holds`] does not hold for
/// it before the read and again after it, or it cannot be read.
pub fn read(root: &Path, path: &Path, max: usize) -> Option<Vec<u8>> {
if !holds(root, path) {
return None;
}
let file = std::fs::File::open(path).ok()?;
if !file.metadata().is_ok_and(|m| m.is_file()) {
return None;
}
let mut bytes = vec![];
file.take(max as u64).read_to_end(&mut bytes).ok()?;
holds(root, path).then_some(bytes)
}
/// A run `script.startup.run` queued for the app, which starts it when the run before it ends.
#[derive(Clone, Debug, PartialEq)]
pub enum Queued {
/// A startup script, read when its turn comes, with its `maxFuel`.
Startup { path: PathBuf, fuel: u64 },
/// The script that runs after the startup scripts, as `script.run`'s parameters.
Then(serde_json::Value),
}
+7
View File
@@ -111,6 +111,7 @@ impl Session {
plugin_loads: Default::default(),
plugin_loads_in_background: false,
scripts_dir: None,
startup_scripts_dir: None,
metadata_templates_dir: None,
new_doc_profile_dir: None,
proof_setup_dir: None,
@@ -139,6 +140,7 @@ impl Session {
place_queue_loads: 0,
image_hand_off: None,
trace_hand_off: None,
retype_hand_off: None,
place_cursor_requests: false,
package_hand_off: None,
screens_hand_off: None,
@@ -177,6 +179,11 @@ impl Session {
script_console: Default::default(),
script_runs: 0,
script_frames: false,
script_queue: Default::default(),
script_queue_scope: None,
script_queue_then: None,
startup_loading: None,
startup_failures: vec![],
script_high_water: Default::default(),
script_in_run: false,
script_copy_first: cfg!(target_arch = "wasm32"),
+26
View File
@@ -200,6 +200,29 @@ impl Session {
Ok(v)
}
/// Run `f`, an edit that applies or edits built-in effect `effect`. The undo step it records,
/// when named after the effect, keeps the effect's id ([`crate::HistoryEntry::effect`]), so a
/// frontend names it as the Effect menu names the effect. Run as an interaction's preview
/// itself, not as one command of a batch the preview runs, the step the interaction records
/// keeps it instead, while that preview is the last one. A later edit of an undo group keeps
/// none.
pub(crate) fn edit_effect<T>(&mut self, effect: &str, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
let id = vectorcraft_render::effects::built_in_effect(effect).map(|(id, _)| id);
let previewed = self.previewing && self.depth == 1;
let outer = std::mem::replace(&mut self.doc_mut()?.effect_step, id);
let v = f(self);
if let Ok(st) = self.doc_mut() {
st.effect_step = outer;
if v.is_ok()
&& previewed
&& let Some(it) = &mut st.interaction
{
it.effect = id;
}
}
v
}
/// Change only the selection (not an undo step).
pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.revealing(|s| s.select_unwatched(f))
@@ -510,6 +533,7 @@ impl Session {
}
st.interaction = Some(Interaction {
label: label.to_string(),
effect: None,
doc: st.doc.clone(),
selection: Arc::new(st.selection.clone()),
preview: None,
@@ -569,6 +593,8 @@ impl Session {
it.color_mode_paints = None;
it.deferred_color_mode = None;
it.plane_placed = false;
// The effect the preview below applies or edits marks the step, not an earlier one's.
it.effect = None;
if selection_changed {
st.selection.clone_from(&it.selection);
}
+2 -1
View File
@@ -92,7 +92,7 @@ impl Session {
fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?;
// A clipboard import is a query that replaces the clipboard, which the end of a run sets too.
if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
if self.depth == 0 && self.script_running() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
return Err(EngineError::Busy);
}
// A step of a batch a script runs is held to the same rule as the script's own commands.
@@ -454,6 +454,7 @@ impl Session {
st.doc = doc;
st.selection = selection;
st.interaction = interaction;
st.effect_step = None;
if let Some(history) = history {
st.history = history;
}
+1
View File
@@ -183,6 +183,7 @@ mod script_folder;
mod script_include;
mod script_io;
mod script_run;
mod script_tags;
mod script_xmp;
mod scripts;
mod segment_nudge;
+33
View File
@@ -270,6 +270,39 @@ fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() {
assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke");
}
/// `edited_strokes_profiled` reads the same strokes, with or without a brush: one profiled member
/// counts, and a group's own uniform stroke, which `stroke.set` edits instead, hides its members'
/// profiles. With an object without a stroke row among the targets the answer is false, since a
/// profile from `stroke.set` would give that object a plain stroke. Type without an Appearance row
/// is left out.
#[test]
fn edited_strokes_profiled_reads_the_strokes_stroke_set_edits() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
assert!(!s.edited_strokes_profiled(), "neither has a profile");
run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"}));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
assert!(s.edited_strokes_profiled(), "the second one has a profile");
let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert!(s.edited_strokes_profiled(), "a group without its own stroke: its members'");
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert!(!s.edited_strokes_profiled(), "the group's own uniform stroke");
let c = rect(&mut s, 400.0);
run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1}));
run(&mut s, "select.set", json!({"ids": [b.0]}));
assert!(s.edited_strokes_profiled(), "the profiled member alone");
run(&mut s, "select.set", json!({"ids": [b.0, c.0]}));
assert!(!s.edited_strokes_profiled(), "an object without a stroke row");
let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Hi"}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [t.0, b.0]}));
assert!(s.edited_strokes_profiled(), "type is left out");
run(&mut s, "select.set", json!({"ids": []}));
assert!(!s.edited_strokes_profiled(), "nothing selected");
}
/// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count.
#[test]
fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() {
+67 -1
View File
@@ -2,7 +2,7 @@
//! shared between steps, and past a memory budget the oldest steps go (never the last few).
use serde_json::json;
use vectorcraft_doc::{Appearance, Node};
use vectorcraft_doc::{Appearance, Node, NodeId};
use vectorcraft_geom::shapes;
use crate::*;
@@ -461,3 +461,69 @@ fn color_mode_paint_snapshots_count_toward_the_history_budget() {
original.appearance.unwrap().effects[0].params["retainedTemplateData"]
);
}
/// A step that applies an effect keeps the effect, through undo and redo too. A step named like an
/// effect by anything else keeps none: a plain edit, an undo group named like the effect, and a
/// group another command started that an effect only extends.
#[test]
fn only_steps_an_effect_records_keep_the_effect() {
let mut s = session_with_rects(2);
let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect()));
assert_eq!(last(&s), Some(("Add".into(), None)), "a plain edit named like Pathfinder › Add");
s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap();
assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.redo.last().and_then(|e| e.effect()), Some("stylize.feather"), "an undone step");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a redone step");
s.begin_named_undo_group(Some("Feather".into()));
s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap();
s.end_undo_group(false);
assert_eq!(last(&s), Some(("Feather".into(), None)), "a group named like the effect");
s.begin_undo_group();
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.transform"})).unwrap();
s.end_undo_group(false);
assert_eq!(last(&s), Some(("Transform".into(), None)), "a group a transform started");
// An interaction's step keeps the effect its last preview applied, and none when a later
// preview replaced it with another command.
s.begin_interaction("Feather").unwrap();
s.preview("effect.apply", &json!({"effect": "stylize.feather"})).unwrap();
s.commit_interaction().unwrap();
assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a kept preview");
s.begin_interaction("Transform").unwrap();
s.preview("effect.apply", &json!({"effect": "distort.transform"})).unwrap();
s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap();
s.commit_interaction().unwrap();
assert_eq!(last(&s), Some(("Transform".into(), None)), "a replaced preview");
s.begin_interaction("Feather").unwrap();
s.preview("command.batch", &json!({"commands": [{"command": "effect.apply", "params": {"effect": "stylize.feather"}}]})).unwrap();
s.commit_interaction().unwrap();
assert_eq!(last(&s), Some(("Feather".into(), None)), "a batch the preview ran");
}
/// An `effect.setParams` step keeps the effect it edited only when every target has that effect at
/// the index: with one target lacking it, the step keeps none, and the target that has it is still
/// edited.
#[test]
fn effect_options_keep_the_effect_only_when_every_target_has_it() {
let mut s = session_with_rects(2);
let ids: Vec<u64> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[0]], "item": null})).unwrap();
let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect()));
let radius = |s: &Session| {
let d = &s.doc().unwrap().doc;
d.node(NodeId(ids[0])).unwrap().appearance.effects[0].params["radius"].as_f64()
};
s.begin_interaction("Feather").unwrap();
s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 7}})).unwrap();
s.commit_interaction().unwrap();
assert_eq!(last(&s), Some(("Feather".into(), None)), "one target without the effect");
assert_eq!(radius(&s), Some(7.0), "the target with the effect is edited");
s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[1]], "item": null})).unwrap();
s.begin_interaction("Feather").unwrap();
s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 9}})).unwrap();
s.commit_interaction().unwrap();
assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "every target with the effect");
assert_eq!(radius(&s), Some(9.0));
}
+334
View File
@@ -775,6 +775,8 @@ fn an_arc_drag_shows_the_protractor() {
let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count();
for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] {
key(&mut s, ToolKey::Escape);
// With the last path selected, a press on its anchors would edit it instead of drawing.
s.execute("select.set", &json!({"ids": []})).unwrap();
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap();
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
@@ -1372,3 +1374,335 @@ fn path_quick_pen_replaces_the_points_after_keep() {
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]);
}
/// A selected path drawn with `path.quickPen` from `start` through `pieces`, with the Quick Pen
/// chosen and no path being drawn.
fn selected_quick_pen_path(s: &mut Session, start: (f64, f64), pieces: Value) -> NodeId {
let r = s.execute("path.quickPen", &json!({"start": [start.0, start.1], "pieces": pieces})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
quick_pen(s);
id
}
fn points(s: &Session) -> Vec<Point> {
only_path(s).anchors.iter().map(|a| a.p).collect()
}
fn shift_click(s: &mut Session, x: f64, y: f64) {
let v = view();
let mods = Mods { shift: true, ..Mods::default() };
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent { mods, ..PointerEvent::new(kind, x, y) }, v).unwrap();
}
}
/// Is segment `i` of `sp` a circular arc: do its points a quarter and three quarters along lie on
/// the circle through its ends and its middle?
fn segment_is_circular(sp: &SubPath, i: usize) -> bool {
use vectorcraft_geom::ParamCurve;
let seg = sp.segment(i);
let (a, b, c) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0));
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
let sq = |p: Point| p.x * p.x + p.y * p.y;
let center = pt(
(sq(a) * (b.y - c.y) + sq(b) * (c.y - a.y) + sq(c) * (a.y - b.y)) / d,
(sq(a) * (c.x - b.x) + sq(b) * (a.x - c.x) + sq(c) * (b.x - a.x)) / d,
);
let r = center.distance(a);
[0.25, 0.75].iter().all(|&t| (seg.eval(t).distance(center) - r).abs() < r * 1e-3)
}
/// With no path being drawn, a drag on an anchor of the selected path moves that anchor alone, in
/// one undo step: at the corner between a line and an arc, the line stays a line and the arc a
/// circular arc.
#[test]
fn a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc() {
let mut s = session();
selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100, "action": "sharpArc", "turn": 90}]));
assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]);
let undo = undo_steps(&s);
press(&mut s, &[(200.0, 100.0), (200.0, 80.0), (200.0, 50.0)]);
assert_eq!(undo_steps(&s), undo + 1);
let sp = only_path(&s);
assert_eq!(sp.anchors.iter().map(|a| a.p).collect::<Vec<_>>(), [pt(100.0, 100.0), pt(200.0, 50.0), pt(300.0, 100.0)]);
assert!(sp.segment_is_line(0), "{:?}", sp.anchors);
assert!(!sp.segment_is_line(1) && segment_is_circular(&sp, 1), "{:?}", sp.anchors);
assert_eq!(paths(&s).len(), 1, "no new path");
}
/// A drag on a segment of the selected path moves that segment's two ends.
#[test]
fn a_drag_on_a_segment_moves_its_ends() {
let mut s = session();
selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}]));
press(&mut s, &[(200.0, 300.0), (200.0, 280.0), (200.0, 250.0)]);
assert_eq!(points(&s), [pt(100.0, 250.0), pt(300.0, 250.0), pt(300.0, 400.0)]);
assert_eq!(paths(&s).len(), 1);
}
/// A drag that starts on an end of the selected open path moves that end; a click there still
/// goes on drawing from it.
#[test]
fn a_drag_on_an_open_end_moves_it() {
let mut s = session();
let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}]));
press(&mut s, &[(300.0, 300.0), (320.0, 320.0), (350.0, 350.0)]);
assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0)]);
assert!(s.doc().unwrap().selection.partial(id).is_some(), "the dragged end is selected");
click(&mut s, 350.0, 350.0);
assert!(s.doc().unwrap().selection.partial(id).is_none(), "drawing goes on with the path selected whole");
click(&mut s, 350.0, 450.0);
assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0), pt(350.0, 450.0)]);
}
/// A press let go past the drag distance moves what it holds even when no drag event went that
/// far: an inner anchor moves, and an open end moves instead of going on drawing.
#[test]
fn a_release_past_the_drag_distance_moves_the_anchor() {
let mut s = session();
selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}]));
let undo = undo_steps(&s);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 102.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap();
assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 100.0)]);
assert_eq!(undo_steps(&s), undo + 1);
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap();
assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 200.0)]);
assert_eq!(undo_steps(&s), undo + 2);
assert_eq!(paths(&s).len(), 1, "no new path");
}
/// A drag on an anchor or a segment that comes back to where it started moves nothing and records
/// no undo step.
#[test]
fn a_drag_back_to_its_start_records_no_undo_step() {
let mut s = session();
selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}]));
let undo = undo_steps(&s);
for at in [(200.0, 100.0), (250.0, 100.0)] {
press(&mut s, &[at, (at.0, at.1 + 50.0), at]);
assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "press at {at:?}");
assert_eq!(undo_steps(&s), undo, "press at {at:?}");
}
// Choosing another tool during such a drag records none either.
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 100.0), v).unwrap();
s.select_tool("selection", v).unwrap();
assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]);
assert_eq!(undo_steps(&s), undo);
}
/// When another command changes the selection while the press is down, neither a click nor a drag
/// selects or moves the anchor the press found.
#[test]
fn a_selection_change_during_an_edit_press_stops_it() {
let mut s = session();
let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}]));
let v = view();
for drag in [false, true] {
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let undo = undo_steps(&s);
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap();
s.execute("select.none", &json!({})).unwrap();
let y = if drag { 150.0 } else { 100.0 };
if drag {
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, y), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, y), v).unwrap();
assert!(s.doc().unwrap().selection.objects.is_empty(), "drag: {drag}");
assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}");
assert_eq!(undo_steps(&s), undo, "drag: {drag}");
}
}
/// When another command edits the path while the press is down, neither a drag nor a release past
/// the drag distance moves the anchor the press found.
#[test]
fn an_edit_during_an_edit_press_stops_the_move() {
let mut s = session();
let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}]));
let v = view();
for (drag, x) in [(true, 90.0), (false, 80.0)] {
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": x, "y": 90})).unwrap();
let undo = undo_steps(&s);
if drag {
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap();
assert_eq!(points(&s), [pt(x, 90.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}");
assert_eq!(undo_steps(&s), undo, "drag: {drag}");
}
}
/// An edit made by another command during an anchor drag stays: the rest of the drag and the
/// release move nothing more, and one undo step holds the move as last shown with the edit.
#[test]
fn an_edit_during_an_anchor_drag_stays() {
let mut s = session();
let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}]));
let undo = undo_steps(&s);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 210.0), v).unwrap();
assert_eq!(points(&s), [pt(90.0, 90.0), pt(200.0, 150.0), pt(300.0, 100.0)], "the edit and the move as last shown");
assert_eq!(undo_steps(&s), undo + 1);
assert!(!s.in_interaction(), "the step is committed");
// Escape after such an edit keeps it too.
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 150.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 80, "y": 80})).unwrap();
key(&mut s, ToolKey::Escape);
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap();
assert_eq!(points(&s), [pt(80.0, 80.0), pt(200.0, 150.0), pt(300.0, 150.0)]);
assert!(!s.in_interaction(), "the step is committed");
}
/// When another command edits the path while a click is down, the click neither selects the
/// anchor nor goes on drawing from the open end it found.
#[test]
fn an_edit_during_an_edit_click_does_nothing() {
let mut s = session();
let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}]));
let v = view();
for (x, moved_y) in [(200.0, 90.0), (300.0, 80.0)] {
s.pointer(&PointerEvent::new(PointerKind::Down, x, 100.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 100, "y": moved_y})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, x, 100.0), v).unwrap();
assert!(s.doc().unwrap().selection.partial(id).is_none(), "no anchor selected after a click at x = {x}");
}
// The open end was not taken up, so the next click starts a new path.
click(&mut s, 400.0, 200.0);
assert_eq!(paths(&s).len(), 2);
}
/// A click on an anchor selects it alone, Shift-click adds another, and Delete (`edit.clear`, the
/// context menu's Delete) then removes both.
#[test]
fn clicks_select_anchors_for_delete() {
let mut s = session();
let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]));
let undo = undo_steps(&s);
click(&mut s, 200.0, 100.0);
let picked = |s: &Session| s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::<Vec<_>>();
assert_eq!(picked(&s), [(0, 1)]);
shift_click(&mut s, 300.0, 100.0);
assert_eq!(picked(&s), [(0, 1), (0, 2)]);
shift_click(&mut s, 300.0, 100.0);
assert_eq!(picked(&s), [(0, 1)], "Shift-click takes it out again");
shift_click(&mut s, 300.0, 100.0);
assert_eq!(undo_steps(&s), undo, "selecting is no edit");
s.execute("edit.clear", &json!({})).unwrap();
let left: Vec<Point> = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect();
assert!(!left.contains(&pt(200.0, 100.0)) && !left.contains(&pt(300.0, 100.0)), "{left:?}");
}
/// The first Shift-click on an anchor of a path selected whole selects that anchor alone.
#[test]
fn a_first_shift_click_selects_the_anchor_alone() {
let mut s = session();
let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}]));
assert!(s.doc().unwrap().selection.partial(id).is_none(), "the path is selected whole");
shift_click(&mut s, 200.0, 100.0);
let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::<Vec<_>>();
assert_eq!(picked, [(0, 1)]);
}
/// A drag on a segment moves its two ends alone, also when they are selected with another anchor.
#[test]
fn a_segment_drag_moves_only_its_ends() {
let mut s = session();
let pieces = json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}, {"x": 100, "y": 400}, {"x": 100, "y": 500}]);
let id = selected_quick_pen_path(&mut s, (100.0, 300.0), pieces);
click(&mut s, 300.0, 300.0);
shift_click(&mut s, 300.0, 400.0);
shift_click(&mut s, 100.0, 400.0);
let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::<Vec<_>>();
assert_eq!(picked, [(0, 1), (0, 2), (0, 3)]);
press(&mut s, &[(300.0, 350.0), (320.0, 350.0), (350.0, 350.0)]);
assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 300.0), pt(350.0, 400.0), pt(100.0, 400.0), pt(100.0, 500.0)]);
assert_eq!(paths(&s).len(), 1);
}
/// A drag on a segment whose two ends are already selected as anchors selects the segment, so
/// Delete then cuts that connection and keeps both anchors.
#[test]
fn a_segment_drag_from_its_selected_ends_selects_the_segment() {
let mut s = session();
let pieces = json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]);
let id = selected_quick_pen_path(&mut s, (100.0, 100.0), pieces);
click(&mut s, 200.0, 100.0);
shift_click(&mut s, 300.0, 100.0);
let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::<Vec<_>>();
assert_eq!(picked, [(0, 1), (0, 2)]);
press(&mut s, &[(250.0, 100.0), (250.0, 120.0), (250.0, 150.0)]);
assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)]);
let segments = s.doc().unwrap().selection.segments.get(&id).cloned().unwrap_or_default().into_iter().collect::<Vec<_>>();
assert_eq!(segments, [(0, 1)], "the segment is selected");
s.execute("edit.clear", &json!({})).unwrap();
let left: Vec<Point> = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect();
for p in [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)] {
assert!(left.contains(&p), "{p:?} stays: {left:?}");
}
}
/// A click on an open end of another path, in front of the selected path, that lies on a segment
/// of the selected path goes on drawing from that end.
#[test]
fn an_open_end_on_a_selected_segment_continues_its_path() {
let mut s = session();
let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}]));
let r = s.execute("shape.line", &json!({"x1": 200, "y1": 200, "x2": 200, "y2": 300})).unwrap();
let other = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
click(&mut s, 200.0, 300.0);
click(&mut s, 250.0, 250.0);
let all = paths(&s);
assert_eq!(all.len(), 2, "no new path");
let ends: Vec<Point> = all.iter().find(|(id, _)| *id == other).unwrap().1.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(200.0, 200.0), pt(200.0, 300.0), pt(250.0, 250.0)]);
}
/// Escape during a drag puts the anchor back, and the release then changes nothing.
#[test]
fn escape_takes_back_an_anchor_drag() {
let mut s = session();
selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}]));
let (before, undo) = (points(&s), undo_steps(&s));
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap();
assert_ne!(points(&s), before, "the drag previews");
key(&mut s, ToolKey::Escape);
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap();
assert_eq!(points(&s), before);
assert_eq!(undo_steps(&s), undo);
assert_eq!(paths(&s).len(), 1);
}
/// While a path is being drawn, a press on one of its points adds a piece as before; the editing
/// starts only after Escape ends the path.
#[test]
fn a_press_while_drawing_adds_a_piece() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
click(&mut s, 200.0, 200.0);
press(&mut s, &[(200.0, 100.0), (220.0, 90.0), (250.0, 80.0)]);
assert_eq!(points(&s).len(), 4, "a piece added");
key(&mut s, ToolKey::Escape);
press(&mut s, &[(200.0, 100.0), (200.0, 70.0), (200.0, 50.0)]);
let got = points(&s);
assert_eq!(got.len(), 4);
assert!(got[1].distance(pt(200.0, 50.0)) < 1e-9, "{got:?}");
}
+12
View File
@@ -909,6 +909,18 @@ fn assigning_the_same_objects_clears_the_key_and_guides() {
assert!(s.active().unwrap().selection.guides.is_empty());
}
/// Assigning `undefined` or a value that is not a page item to the selection throws and keeps it.
#[test]
fn assigning_undefined_to_the_selection_throws_and_keeps_it() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
for source in ["var u; app.activeDocument.selection = u;", "app.activeDocument.selection = undefined;", "app.activeDocument.selection = 1;"] {
let e = failure(&mut s, source);
assert!(e.contains("TypeError"), "{source}: {e}");
assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "{source}");
}
}
#[test]
fn a_page_item_with_a_large_id_keeps_its_id() {
let mut s = Session::new();
+13
View File
@@ -389,3 +389,16 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() {
});
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_startup_listing_over_the_script_limit_keeps_the_first_names_in_order() {
let dir = vectorcraft_testkit::TempDir::new("startup-limit");
for name in ["d.jsx", "b.jsx", "e.jsx", "a.jsx", "c.jsx"] {
touch(&dir, name);
}
let limits = Limits { scripts: 3, ..Limits::default() };
let listing = crate::script::startup::list_with(&dir, &limits, &mut || Duration::ZERO);
let names: Vec<_> = listing.scripts.iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect();
assert_eq!(names, ["a.jsx", "b.jsx", "c.jsx"]);
assert!(listing.truncated);
}
+57
View File
@@ -652,6 +652,63 @@ fn a_grants_change_without_its_lock_changes_nothing() {
let _ = std::fs::remove_dir_all(base);
}
/// `script.grants.revoke` removes a grant by the path `script.grants` lists for it, also when a
/// link has since taken that path's place and leads elsewhere.
#[cfg(unix)]
#[test]
fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() {
let base = folder("grants-relinked");
let real = std::fs::canonicalize(&base).unwrap();
let (kept, other) = (real.join("kept.txt"), real.join("other.txt"));
write(&other, b"other");
let kept_path = kept.to_string_lossy().into_owned();
let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false});
write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes());
std::os::unix::fs::symlink(&other, &kept).unwrap();
let mut s = with_data(&base);
let listed = s.execute("script.grants", &json!({})).unwrap();
assert_eq!(listed["grants"][0]["path"], json!(kept_path));
let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap();
assert_eq!(r["removed"], 1, "{r}");
assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([]));
let _ = std::fs::remove_dir_all(base);
}
/// A grant kept for a path that is now a link to another granted path is revoked alone: the grant of
/// the link's target stays.
#[cfg(unix)]
#[test]
fn revoking_a_grant_whose_path_now_links_to_another_grant_keeps_the_other() {
let base = folder("grants-relinked-both");
let real = std::fs::canonicalize(&base).unwrap();
let (kept, other) = (real.join("kept.txt"), real.join("other.txt"));
write(&other, b"other");
let (kept_path, other_path) = (kept.to_string_lossy().into_owned(), other.to_string_lossy().into_owned());
let grant = |path: &str| json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": path, "write": false, "folder": false});
let stored = json!({"version": 1, "grants": [grant(&kept_path), grant(&other_path)]});
write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes());
std::os::unix::fs::symlink(&other, &kept).unwrap();
let mut s = with_data(&base);
let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap();
assert_eq!(r["removed"], 1, "{r}");
let left = s.execute("script.grants", &json!({})).unwrap();
let paths: Vec<Value> = left["grants"].as_array().into_iter().flatten().map(|g| g["path"].clone()).collect();
assert_eq!(paths, [json!(other_path)], "{left}");
// Another script's grant of the path as given does not keep this script's grant of the link's
// target from being removed.
let stored = json!({"version": 1, "grants": [
{"script": "/t.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false},
grant(&other_path)
]});
write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes());
let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap();
assert_eq!(r["removed"], 1, "{r}");
let left = s.execute("script.grants", &json!({})).unwrap();
let scripts: Vec<Value> = left["grants"].as_array().into_iter().flatten().map(|g| g["script"].clone()).collect();
assert_eq!(scripts, [json!("/t.jsx")], "{left}");
let _ = std::fs::remove_dir_all(base);
}
/// Reading and changing the grants file wait for a lock another handle holds only for a bounded
/// number of tries: then a listing and a change fail, with the file unchanged. A lock
/// released while it waits is taken.
+27
View File
@@ -393,6 +393,33 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not()
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() {
let dir = fresh_folder("generators");
let write = |name: &str, text: &str| {
let p = dir.join(name);
std::fs::write(&p, text).unwrap();
p.to_string_lossy().into_owned()
};
let mut s = two_docs();
let path = |p: &str| json!({"path": p});
let source = "function* ids(n) { for (let i = 0; i < n; i++) yield `id${i}`; }\n\
function* all() { yield* ids(2); yield* [vc.document ? 'doc' : 'none']; return 'end'; }\n\
const it = all(); let s;\nwhile (!(s = it.next()).done) vc.log(s.value);\nvc.log(s.value);\n";
let r = s.execute("script.run", &path(&write("gen.js", source))).unwrap();
assert_eq!(r["log"], json!(["id0", "id1", "doc", "end"]), "{r}");
let e = s.execute("script.run", &path(&write("gen.jsx", "function* g() {}"))).unwrap_err().to_string();
assert!(e.contains("SyntaxError"), "{e}");
// `yield` stays a name in a `.jsx` script.
let r = s.execute("script.run", &path(&write("name.jsx", "var yield = 4; vc.log(yield);"))).unwrap();
assert_eq!(r["log"], json!([4]), "{r}");
// An engine a `.jsx` run made has no generator built-ins for a later `.js` run.
s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap();
let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string();
assert!(e.contains("TypeError"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn every_script_reads_e4x_and_has_the_xml_objects() {
let dir = fresh_folder("e4x");
+286
View File
@@ -0,0 +1,286 @@
//! Tags on page items: `PageItem.tags`, `Document.tags`, `Tag`, and the `object.tag.*` commands
//! they run.
use serde_json::{Value, json};
use vectorcraft_doc::{MAX_TAG_TEXT, MAX_TAGS, ObjectTag};
use crate::*;
fn run(s: &mut Session, source: &str) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// The message of the run's failure.
fn failure(s: &mut Session, source: &str) -> String {
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
}
fn rect(s: &mut Session, x: f64, y: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap())
}
/// A document with two rectangles.
fn doc() -> (Session, NodeId, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let a = rect(&mut s, 10.0, 20.0);
let b = rect(&mut s, 100.0, 100.0);
(s, a, b)
}
fn undo_steps(s: &Session) -> usize {
s.active().unwrap().history.undo.len()
}
fn tags(s: &Session, id: NodeId) -> Vec<(String, String)> {
let d = &s.active().unwrap().doc;
crate::cmd::tags::tags_of(d.node(id).unwrap()).iter().map(|t| (t.name.clone(), t.value.clone())).collect()
}
fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
list.iter().map(|(n, v)| (n.to_string(), v.to_string())).collect()
}
#[test]
fn tags_are_added_named_read_and_removed_in_one_undo_step() {
let (mut s, a, _) = doc();
let before = undo_steps(&s);
let out = log(
&mut s,
"var item = app.activeDocument.pageItems[1], tags = item.tags;\
vc.log(tags.typename); vc.log(tags.length);\
var t = tags.add(); vc.log(t.typename); vc.log(t.name === '' && t.value === '');\
t.name = 'size'; t.value = 'XL';\
var u = tags.add(); u.name = 'size'; u.value = 'S';\
var w = tags.add(); w.name = '../a\\\\b'; w.value = 'kept';\
vc.log(tags.length); vc.log(tags.getByName('size').value); vc.log(tags[1].value); vc.log(tags.index(2).name);\
vc.log(tags.index('../a\\\\b').value); vc.log(tags[3] === undefined); vc.log(t.parent.typename); vc.log(tags.parent.typename);\
u.remove(); vc.log(tags.length); vc.log(tags[1].name);",
);
let expected = [json!("Tags"), json!(0), json!("Tag"), json!(true), json!(3), json!("XL"), json!("S"), json!("../a\\b")];
assert_eq!(out[..8], expected);
assert_eq!(out[8..], [json!("kept"), json!(true), json!("PathItem"), json!("PathItem"), json!(2), json!("../a\\b")]);
assert_eq!(tags(&s, a), pairs(&[("size", "XL"), ("../a\\b", "kept")]));
assert_eq!(undo_steps(&s), before + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(tags(&s, a).is_empty());
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(tags(&s, a).len(), 2);
log(&mut s, "app.activeDocument.pageItems[1].tags.removeAll();");
assert!(tags(&s, a).is_empty());
}
#[test]
fn document_tags_list_every_items_tags_and_add_none() {
let (mut s, a, b) = doc();
s.execute("object.tag.add", &json!({"id": b.0, "name": "b1", "value": "2"})).unwrap();
s.execute("object.tag.add", &json!({"id": a.0, "name": "a1", "value": "1"})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument; vc.log(d.tags.length); vc.log(d.tags[0].name); vc.log(d.tags[1].name);\
vc.log(d.tags.parent.typename); vc.log(d.tags.getByName('b1').parent.typename);",
);
// `pageItems` lists the topmost item first, and so does `Document.tags`.
assert_eq!(out, [json!(2), json!("b1"), json!("a1"), json!("Document"), json!("PathItem")]);
// A copy keeps its source's tags.
let copy = s.execute("edit.duplicate", &json!({"ids": [a.0]})).unwrap()["ids"][0].as_u64().map(NodeId).unwrap();
assert_eq!(tags(&s, copy), pairs(&[("a1", "1")]));
s.execute("edit.undo", &json!({})).unwrap();
let before = undo_steps(&s);
assert!(failure(&mut s, "app.activeDocument.tags.add();").contains("added to a page item's tags"));
assert_eq!(undo_steps(&s), before);
log(&mut s, "app.activeDocument.tags.removeAll();");
assert!(tags(&s, a).is_empty() && tags(&s, b).is_empty());
assert_eq!(undo_steps(&s), before + 1);
}
#[test]
fn bad_tag_values_throw_and_change_nothing() {
let (mut s, a, _) = doc();
s.execute("object.tag.add", &json!({"id": a.0, "name": "n", "value": "v"})).unwrap();
let before = undo_steps(&s);
let tag = "app.activeDocument.pageItems[1].tags[0]";
assert!(failure(&mut s, &format!("{tag}.name = 5;")).contains("TypeError: name must be a string"));
assert!(failure(&mut s, &format!("{tag}.value = null;")).contains("TypeError: value must be a string"));
let long = format!("{tag}.value = new Array({}).join('x');", MAX_TAG_TEXT + 2);
assert!(failure(&mut s, &long).contains("RangeError: a tag's value is longer than 65,536 bytes"));
assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.getByName('none');").contains("Not found"));
assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.index(true);").contains("TypeError"));
// A run that fails after changing a tag puts it back.
assert!(failure(&mut s, &format!("{tag}.value = 'w'; throw new Error('stop');")).contains("stop"));
assert_eq!(tags(&s, a), pairs(&[("n", "v")]));
// Setting what a tag already has runs no command.
log(&mut s, &format!("{tag}.name = 'n'; {tag}.value = 'v';"));
assert_eq!(undo_steps(&s), before);
}
#[test]
fn tags_work_on_an_item_and_with_tag_ids_above_2_to_the_53() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let big = (1u64 << 53) + 1;
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
let a = rect(&mut s, 10.0, 20.0);
assert_eq!(a.0, big);
let out = log(
&mut s,
"var all = app.activeDocument.pageItems[0].tags, t = all.add(); t.name = 'n'; t.value = 'v';\
var u = all.add(); u.name = 'm'; vc.log(all.length); vc.log(t.name); vc.log(all[1].name); vc.log(t.parent.typename);\
t.remove(); vc.log(all.length); vc.log(all[0].name);",
);
assert_eq!(out, [json!(2), json!("n"), json!("m"), json!("PathItem"), json!(1), json!("m")]);
assert_eq!(tags(&s, a), pairs(&[("m", "")]));
}
#[test]
fn an_object_takes_at_most_64_tags() {
let (mut s, a, _) = doc();
let out = log(&mut s, "var t = app.activeDocument.pageItems[1].tags; for (var i = 0; i < 64; i++) t.add(); vc.log(t.length);");
assert_eq!(out, [json!(MAX_TAGS)]);
let e = failure(&mut s, "app.activeDocument.pageItems[1].tags.add();");
assert!(e.contains("64 tags"), "{e}");
assert_eq!(tags(&s, a).len(), MAX_TAGS);
}
#[test]
fn a_tag_goes_stale_when_it_or_its_item_is_deleted() {
let (mut s, a, b) = doc();
s.execute("object.tag.add", &json!({"id": a.0, "name": "x"})).unwrap();
s.execute("object.tag.add", &json!({"id": b.0, "name": "y"})).unwrap();
let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.name;");
assert!(e.contains("Stale tag"), "{e}");
// `typename` throws too, on a deleted tag and on the tags of a deleted item (each failed run
// put the document back).
let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.typename;");
assert!(e.contains("Stale tag"), "{e}");
let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], all = i.tags; i.remove(); all.typename;");
assert!(e.contains("Stale page item"), "{e}");
let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0], all = i.tags; i.remove(); all.length;");
assert!(e.contains("Stale page item"), "{e}");
let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0]; i.remove(); t.value;");
assert!(e.contains("Stale page item"), "{e}");
// A tag added after another was deleted does not take the deleted one's place.
let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); t.name;");
assert!(e.contains("Stale tag"), "{e}");
// Nor after the run undoes the add: the undone document's next id does not give the tag's id
// out again.
let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all.add(); vc.run('edit.undo'); all.add().name = 'u'; t.name;");
assert!(e.contains("Stale tag"), "{e}");
// Nor when the deleted tag's id was ahead of the document's next id (a tag pasted from
// another document).
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let ahead = d.peek_next_id() + 2;
d.node_mut(a).unwrap().edit_attrs(|at| at.tags = vec![ObjectTag { id: ahead, name: "p".into(), value: String::new() }]);
let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); all.add(); all.add(); t.name;");
assert!(e.contains("Stale tag"), "{e}");
}
#[test]
fn tag_commands_check_their_params_and_skip_unchanged_edits() {
let (mut s, a, _) = doc();
let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "k"})).unwrap()["tag"].as_u64().unwrap();
let before = undo_steps(&s);
assert_eq!(s.execute("object.tag.set", &json!({"id": a.0, "tag": tag, "name": "k"})).unwrap()["changed"], false);
assert_eq!(s.execute("object.tag.removeAll", &json!({"ids": []})).unwrap()["changed"], 0);
assert_eq!(undo_steps(&s), before);
let too_long = "x".repeat(MAX_TAG_TEXT + 1);
for (id, p) in [
("object.tag.add", json!({"id": a.0, "name": too_long})),
("object.tag.add", json!({"id": a.0, "value": 3})),
("object.tag.add", json!({"id": a.0, "name": null})),
("object.tag.set", json!({"id": a.0, "tag": tag, "name": null, "value": "updated"})),
("object.tag.set", json!({"id": a.0, "tag": tag, "value": null})),
("object.tag.add", json!({"id": 999_999})),
("object.tag.add", json!({"id": "1"})),
("object.tag.set", json!({"id": a.0, "tag": tag})),
("object.tag.set", json!({"id": a.0, "tag": tag + 1, "name": "n"})),
("object.tag.remove", json!({"id": a.0, "tag": -1})),
("object.tag.removeAll", json!({"ids": [999_999]})),
("object.tags", json!({})),
] {
assert!(s.execute(id, &p).is_err(), "{id} {p}");
}
let layer = s.active().unwrap().doc.layers[0].id;
assert!(s.execute("object.tag.add", &json!({"id": layer.0})).is_err());
assert_eq!(undo_steps(&s), before);
assert_eq!(s.execute("object.tags", &json!({"id": a.0})).unwrap(), json!({"tags": [{"tag": tag, "name": "k", "value": ""}]}));
}
#[test]
fn tags_survive_native_save_and_open_and_hostile_ones_are_trimmed() {
let (mut s, a, b) = doc();
let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "size", "value": "XL"})).unwrap()["tag"].as_u64().unwrap();
let mut doc = (*s.active().unwrap().doc).clone();
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
let t = crate::cmd::tags::tags_of(back.node(a).unwrap());
assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::<Vec<_>>(), [("size", "XL")]);
// The tag keeps its id, so `object.tag.set` and `object.tag.remove` still find it.
assert_eq!(t[0].id, tag);
assert!(tag < back.peek_next_id());
// A file with too many tags, repeated ids and over-long text opens with them within the limits.
doc.node_mut(b).unwrap().edit_attrs(|at| {
at.tags = (0..MAX_TAGS + 10).map(|i| ObjectTag { id: 7, name: format!("t{i}"), value: String::new() }).collect();
at.tags.insert(0, ObjectTag { id: 1, name: "x".repeat(MAX_TAG_TEXT + 1), value: String::new() });
});
// The repeated ids get new ids from the next node id on.
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
let t = crate::cmd::tags::tags_of(back.node(b).unwrap());
assert_eq!(t[0].id, 7);
assert!(t[1..].iter().all(|t| t.id > tag && t.id < back.peek_next_id()));
// An id at the top of the node id range, and one past it: the new ids are the smallest the
// object's other tags do not have.
let top = (1u64 << 62) - 1;
doc.node_mut(a).unwrap().edit_attrs(|at| {
at.tags[0].id = u64::MAX;
at.tags.insert(0, ObjectTag { id: top, name: "top".into(), value: String::new() });
});
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
// Opening gives both new ids below the next node id, which stays within the node id range.
let fixed: Vec<u64> = crate::cmd::tags::tags_of(back.node(a).unwrap()).iter().map(|t| t.id).collect();
assert_eq!(fixed.len(), 2);
assert!(fixed.iter().all(|id| *id < back.peek_next_id()) && fixed[0] != fixed[1], "{fixed:?}");
assert_eq!(fixed, [top, 1]);
assert!(back.peek_next_id() <= 1 << 62, "{}", back.peek_next_id());
// No tag id is left for a new tag: one past the range would not be kept on opening, and one
// below it could be a deleted tag's.
assert_eq!(back.clone().alloc_tag_id(a), None);
let t = crate::cmd::tags::tags_of(back.node(b).unwrap());
assert_eq!(t.len(), MAX_TAGS);
assert_eq!(t[0].name, "t0");
// The first tag with the repeated id keeps it; the others get new ones.
assert_eq!(t[0].id, 7);
let mut ids: Vec<u64> = t.iter().map(|t| t.id).collect();
assert!(ids.iter().all(|id| *id < back.peek_next_id()));
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), MAX_TAGS);
}
#[test]
fn a_file_with_a_tag_id_that_is_not_a_whole_number_opens_and_the_tag_gets_a_new_id() {
let (s, a, _) = doc();
let mut doc = (*s.active().unwrap().doc).clone();
doc.node_mut(a).unwrap().edit_attrs(|at| {
at.tags =
["k0", "k1", "k2"].iter().enumerate().map(|(i, n)| ObjectTag { id: 424_240 + i as u64, name: (*n).into(), value: "v".into() }).collect();
});
let mut hostile = String::from_utf8(vectorcraft_format::save(&doc, false)).unwrap();
for (from, to) in [("\"id\":424240", "\"id\":-1"), ("\"id\":424241", "\"id\":1.5"), ("\"id\":424242", "\"id\":\"x\"")] {
assert!(hostile.contains(from), "{from}");
hostile = hostile.replace(from, to);
}
let back = vectorcraft_format::load(hostile.as_bytes()).unwrap();
let t = crate::cmd::tags::tags_of(back.node(a).unwrap());
assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::<Vec<_>>(), [("k0", "v"), ("k1", "v"), ("k2", "v")]);
let mut ids: Vec<u64> = t.iter().map(|t| t.id).collect();
assert!(ids.iter().all(|id| *id >= 1 && *id < back.peek_next_id()), "{ids:?}");
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), 3);
}
+18
View File
@@ -3250,6 +3250,24 @@ fn ending_deferred_typing_for_another_edit_keeps_the_typing() {
});
}
/// An effect applied while typing waits for its session to end keeps the typing as its own step
/// first, and the effect's own step still keeps the effect it applied.
#[test]
fn an_effect_applied_while_typing_waits_keeps_its_effect_on_its_step() {
let mut s = session();
s.prefs.real_time_drawing = false;
let v = ViewInfo::default();
let id = text(&mut s, "Hello");
s.select_tool("type", v).unwrap();
let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
click(&mut s, b.x1 - 1.0, b.center().y);
s.tool_text(" world", v).unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [id.0]})).unwrap();
assert_eq!(undo_labels(&s).iter().rev().take(2).collect::<Vec<_>>(), ["Feather", "Typing"]);
let h = s.doc().unwrap().history.undo.last().unwrap();
assert_eq!(h.effect(), Some("stylize.feather"));
}
/// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the
/// typed text: its interaction used to join the typing session and preview from the document
/// before the typing, so the new type came back as its placeholder text.
+216
View File
@@ -1142,3 +1142,219 @@ fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file()
assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none());
assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415)));
}
/// The bytes of a `document.exportForWeb.saveColorTable` reply without a path.
fn color_table_file(s: &mut Session, p: Value) -> (Value, Vec<u8>) {
let v = run(s, "document.exportForWeb.saveColorTable", p);
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
(v, bytes)
}
/// The color table file of `colors` (`#rrggbb`) and transparent entry `transparent`, as the
/// published layout gives it: 256 RGB triples (zero past the colors used), then the number of
/// colors and the transparent index (0xFFFF for none), two bytes each, most significant first.
fn act_layout(colors: &[&str], transparent: Option<u16>) -> Vec<u8> {
let mut out = vec![];
for c in colors {
let rgb = u32::from_str_radix(c.trim_start_matches('#'), 16).unwrap();
out.extend_from_slice(&[(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8]);
}
out.resize(768, 0);
out.extend_from_slice(&(colors.len() as u16).to_be_bytes());
out.extend_from_slice(&transparent.unwrap_or(0xFFFF).to_be_bytes());
out
}
/// Save Color Table writes the table the preview shows as a 772-byte color table file: the colors
/// as written, in file order, zero bytes after them, the count and the transparent entry.
#[test]
fn save_color_table_writes_the_act_layout() {
let mut s = two_colours();
for format in ["gif", "png8"] {
let p = json!({"format": format, "dither": "none", "transparency": false});
let pv = run(&mut s, "document.exportForWeb.preview", p.clone());
let colors: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect();
assert_eq!(colors.len(), 2, "{pv}");
let (v, bytes) = color_table_file(&mut s, p);
assert_eq!(bytes, act_layout(&colors, None), "{format}");
assert_eq!((v["colors"].as_u64(), v["transparentIndex"].is_null(), v["bytes"].as_u64()), (Some(2), true, Some(772)), "{v}");
}
// Transparent pixels: the trailer names the transparent entry.
let mut s = session(40.0, 30.0);
rect(&mut s, [10.0, 5.0, 10.0, 20.0], "#ff0000");
let p = json!({"format": "gif", "antiAlias": "none", "dither": "none"});
let pv = run(&mut s, "document.exportForWeb.preview", p.clone());
let table = pv["colors"].as_array().unwrap();
let at = table.iter().position(|c| c["transparent"] == true).expect("a transparent entry") as u16;
let colors: Vec<&str> = table.iter().map(|c| c["color"].as_str().unwrap()).collect();
let (v, bytes) = color_table_file(&mut s, p);
assert_eq!(bytes, act_layout(&colors, Some(at)));
assert_eq!(v["transparentIndex"].as_u64(), Some(u64::from(at)));
}
/// A color shifted by hand goes into the file as the color it is written as.
#[test]
fn save_color_table_writes_shifted_colors_as_written() {
let mut s = two_colours();
let p = json!({"format": "gif", "dither": "none", "transparency": false, "colorTable": {"shifted": {"#ff0000": "#123456"}}});
let (_, bytes) = color_table_file(&mut s, p);
let colors: Vec<[u8; 3]> = bytes[..6].chunks(3).map(|c| [c[0], c[1], c[2]]).collect();
assert!(colors.contains(&[0x12, 0x34, 0x56]) && !colors.contains(&[255, 0, 0]), "{colors:?}");
}
/// Save Color Table writes the file at `path`, adding `.act` to a name without an extension and
/// keeping another extension, and refuses formats without a color table and bad params.
#[test]
fn save_color_table_writes_the_path_and_refuses_bad_params() {
let dir = std::env::temp_dir().join(format!("vc-color-table-save-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = two_colours();
let p = json!({"format": "gif", "dither": "none"});
let (_, bytes) = color_table_file(&mut s, p.clone());
let bare = dir.join("table").to_string_lossy().into_owned();
let v = run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": bare})));
let written = format!("{bare}.act");
assert_eq!(v["path"].as_str(), Some(written.as_str()));
assert_eq!(std::fs::read(&written).unwrap(), bytes);
let other = dir.join("table.tbl").to_string_lossy().into_owned();
run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": other})));
assert_eq!(std::fs::read(&other).unwrap(), bytes);
for (bad, says) in [
(json!({"format": "jpg"}), "`jpg` has no color table"),
(json!({"format": "png24"}), "`png24` has no color table"),
(json!({"path": 5}), "`path` must be a string"),
(json!({"path": ""}), "`path` is empty"),
(json!({"path": " "}), "`path` is empty"),
(json!({"slice": "1"}), "`slice` is a slice number"),
(json!({"slice": 0}), "`slice` is a slice number"),
] {
let e = s.execute("document.exportForWeb.saveColorTable", &bad).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
let _ = std::fs::remove_dir_all(dir);
}
/// With Save for Web set to the selected slices and none selected, Save Color Table still writes
/// the whole image's table, the one the dialog's preview shows. A `slice` is still looked up among
/// the selected slices.
#[test]
fn save_color_table_of_the_whole_image_needs_no_selected_slice() {
let mut s = two_colours();
let slice = run(&mut s, "object.slice.create", json!({"x": 0, "y": 0, "width": 20, "height": 30}))["id"].as_u64().unwrap();
run(&mut s, "object.slice.select", json!({}));
let p = json!({"format": "gif", "dither": "none", "transparency": false});
let (_, whole) = color_table_file(&mut s, merge(&p, json!({"slices": "none"})));
let (v, bytes) = color_table_file(&mut s, merge(&p, json!({"slices": "selected"})));
assert_eq!(bytes, whole, "{v}");
let number = run(&mut s, "slice.list", json!({}))["slices"]
.as_array()
.unwrap()
.iter()
.find(|l| l["id"].as_u64() == Some(slice))
.map(|l| l["number"].clone())
.unwrap();
let e = s.execute("document.exportForWeb.saveColorTable", &merge(&p, json!({"slices": "selected", "slice": number}))).unwrap_err().to_string();
assert!(e.contains("no selected slice"), "{e}");
}
/// The preview refuses a `slice` that is not a slice number instead of previewing the whole image.
#[test]
fn preview_refuses_a_slice_that_is_not_a_number() {
let mut s = two_colours();
for slice in [json!("1"), json!(0), json!(-1), json!(1.5)] {
let e = s.execute("document.exportForWeb.preview", &json!({"slice": slice})).unwrap_err().to_string();
assert!(e.contains("`slice` is a slice number"), "{slice}: {e}");
}
assert!(s.execute("document.exportForWeb.preview", &json!({"slice": null})).is_ok());
}
/// Color table files are read as the published layout gives them: 768 bytes are 256 colors without
/// a transparent entry; 772 bytes add the count and the transparent index.
#[test]
fn color_table_files_are_read_by_the_published_layout() {
use cmd::webexport::read_act;
let long: Vec<u8> = (0..768).map(|i| (i % 251) as u8).collect();
let t = read_act(&long).unwrap();
assert_eq!((t.colors.len(), t.colors[0], t.colors[255], t.transparent), (256, [0, 1, 2], [12, 13, 14], None));
let t = read_act(&act_layout(&["#ff0000", "#00ff00", "#0000ff"], Some(1))).unwrap();
assert_eq!((t.colors, t.transparent), (vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], Some(1)));
assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], None)).unwrap().transparent, None);
// An index past the colors used names no entry.
assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], Some(2))).unwrap().transparent, None);
let mut zero = act_layout(&["#ff0000"], None);
zero[768..770].copy_from_slice(&0u16.to_be_bytes());
let mut over = act_layout(&["#ff0000"], None);
over[768..770].copy_from_slice(&257u16.to_be_bytes());
for bad in [vec![], vec![0; 767], vec![0; 769], vec![0; 771], vec![0; 773], zero, over] {
assert!(read_act(&bad).unwrap_err().contains("not a color table"), "{} bytes", bad.len());
}
}
/// Load Color Table makes the file's colors the fixed palette, other than its transparent entry,
/// with the file's color count; the preview of the loaded settings writes those colors.
#[test]
fn load_color_table_makes_the_file_the_fixed_palette() {
let mut s = two_colours();
let file = act_layout(&["#00ff00", "#ffffff", "#ff0000"], Some(1));
let table = json!({
"deleted": ["#0000ff"], "shifted": {"#ff0000": "#111111"}, "webShift": ["#ff0000"], "locked": ["#ff0000"],
"transparent": ["#00ff00"], "sort": "hue",
});
let p = json!({"format": "gif", "dither": "none", "transparency": false, "webSnap": 100, "colorTable": table});
let v = run(&mut s, "webExport.loadColorTable", merge(&p, json!({"dataBase64": vectorcraft_format::base64_encode(&file)})));
assert_eq!((&v["colors"], &v["transparentIndex"]), (&json!(["#00ff00", "#ffffff", "#ff0000"]), &json!(1)));
let settings = &v["settings"];
assert_eq!((&settings["colors"], &settings["webSnap"]), (&json!(3), &json!(0)));
let table = &settings["colorTable"];
assert_eq!(
(&table["customPalette"], &table["deleted"], &table["shifted"], &table["webShift"]),
(&json!(["#00ff00", "#ff0000"]), &json!([]), &json!({}), &json!([]))
);
assert_eq!((&table["locked"], &table["transparent"], &table["sort"]), (&json!([]), &json!([]), &json!("none")));
// The loaded palette is what the image is written with: blue takes the nearest loaded color.
let pv = run(&mut s, "document.exportForWeb.preview", settings.clone());
let written: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect();
assert!(!written.is_empty() && written.iter().all(|c| ["#00ff00", "#ff0000"].contains(c)), "{pv}");
// A table saved and loaded again keeps its colors.
let opaque = json!({"format": "png8", "dither": "none", "transparency": false});
let saved = color_table_file(&mut s, opaque.clone()).1;
let again = run(&mut s, "webExport.loadColorTable", json!({"format": "png8", "dataBase64": vectorcraft_format::base64_encode(&saved)}));
let shown = run(&mut s, "document.exportForWeb.preview", opaque);
let before: Vec<&Value> = shown["colors"].as_array().unwrap().iter().map(|c| &c["color"]).collect();
assert_eq!(again["colors"].as_array().unwrap().iter().collect::<Vec<_>>(), before);
// A table whose only color is its transparent entry loads that color.
let only = act_layout(&["#336699"], Some(0));
let v = run(&mut s, "webExport.loadColorTable", json!({"dataBase64": vectorcraft_format::base64_encode(&only)}));
assert_eq!((&v["settings"]["colorTable"]["customPalette"], &v["settings"]["colors"]), (&json!(["#336699"]), &json!(2)));
}
/// Load Color Table reads a path, reads no more of a file than a color table takes, and refuses
/// bad params without changing the remembered settings.
#[test]
fn load_color_table_reads_a_path_and_refuses_bad_params() {
let dir = std::env::temp_dir().join(format!("vc-color-table-load-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = two_colours();
let path = dir.join("t.act").to_string_lossy().into_owned();
std::fs::write(&path, act_layout(&["#010203", "#040506"], None)).unwrap();
let v = run(&mut s, "webExport.loadColorTable", json!({"path": path}));
assert_eq!(v["settings"]["colorTable"]["customPalette"], json!(["#010203", "#040506"]));
let large = dir.join("large.act").to_string_lossy().into_owned();
std::fs::write(&large, vec![0u8; 1 << 20]).unwrap();
let b64 = vectorcraft_format::base64_encode(&act_layout(&["#010203"], None));
for (bad, says) in [
(json!({"path": large}), "not a color table"),
(json!({"dataBase64": vectorcraft_format::base64_encode(&[0u8; 100])}), "not a color table"),
// A whole table with more data after it is too long.
(json!({"dataBase64": format!("{b64}AAAA")}), "not a color table"),
(json!({}), "give exactly one of `path` and `dataBase64`"),
(json!({"path": path, "dataBase64": b64}), "give exactly one of `path` and `dataBase64`"),
(json!({"dataBase64": "%%%"}), "bad dataBase64"),
(json!({"dataBase64": b64, "format": "jpg"}), "`jpg` has no color table"),
] {
let e = s.execute("webExport.loadColorTable", &bad).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
assert!(s.last_web_settings().color_table.custom_palette.is_empty(), "nothing is remembered");
let _ = std::fs::remove_dir_all(dir);
}
+31
View File
@@ -1793,6 +1793,37 @@ fn paste_on_all_artboards_leaves_artboard_backgrounds_out() {
assert!(r.get("profileMismatch").is_none(), "{r}");
}
/// The swatch conflicts Paste on All Artboards raises leave copied artboard backgrounds out, as the
/// paste does: pasting back into the document the objects came from, where only the RGB background
/// of the copied artboard now has another profile, converts nothing for it, so its edited CMYK
/// swatch raises no conflict. A plain paste, which brings the background and converts it, compares
/// the swatches and lists the edited one.
#[test]
fn swatch_conflicts_on_all_artboards_leave_artboard_backgrounds_out() {
let _g = settings();
let _reset = ColorSettingsReset { profile: None, paths: vec![] };
let mut s = session();
exec(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true}));
let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "swatch": "Brand"}));
exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true}));
exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"}));
exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB}));
exec(&mut s, "artboard.copy", json!({"index": 0}));
exec(&mut s, "edit.assignProfile", json!({"rgb": null}));
exec(&mut s, "swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}}));
let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len();
assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "a plain paste converts the RGB background");
assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": true})), 0);
assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": false})), 1);
assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": null})), 1, "null is the default");
for bad in [json!("yes"), json!(1)] {
assert!(s.execute("clipboard.conflicts", &json!({ "allArtboards": bad })).is_err(), "{bad}");
}
let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"}));
assert!(r.get("profileMismatch").is_none(), "{r}");
}
/// A converting paste back into the document the objects came from (its profile changed since the
/// copy) still takes its image blobs as the document's own: an image whose blob under its key
/// changed since keeps that key, and so shows the document's blob.
@@ -80,7 +80,7 @@ const INSIDE: &[(&str, &str)] = &[
"",
"activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod",
Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= Tag Tags ZOrderMethod",
),
("Application.", "prototype"),
(
@@ -103,7 +103,7 @@ const INSIDE: &[(&str, &str)] = &[
"Document.prototype.",
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= toString \
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \
typename views views= width",
),
("Layer.", "prototype"),
@@ -116,10 +116,14 @@ const INSIDE: &[(&str, &str)] = &[
"artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \
left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \
position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
),
("Tags.", "prototype"),
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
("Tag.", "prototype"),
("Tag.prototype.", "constructor name name= parent remove typename value value="),
("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"),
("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"),
("DocumentColorSpace.", "CMYK RGB"),
+127
View File
@@ -0,0 +1,127 @@
//! JavaScript filter plug-ins through the engine: a `.vcplugin` manifest and the `.js` file it
//! names install with `plugin.install {path}`, run with `plugin.run` as one undo step, and a run
//! that fails or exhausts its budget leaves the document as it was.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_engine::Session;
use vectorcraft_testkit::fixtures::{exec, rect, select, session};
/// Paints every input object's first fill blue.
const BLUE: &str = "function run(input, params) {\n\
return {objects: input.objects.map(function (o) {\n\
return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: 1}}]};\n\
})};\n\
}\n";
/// An empty folder for one test, with anything an earlier run left there removed.
fn folder(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("vc-plugin-js-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// Writes the manifest of filter `id`, whose code is `tint.js`, with `extra` keys, and `script` as
/// that file → the manifest's path.
fn package(dir: &Path, id: &str, extra: Value, script: Option<&str>) -> String {
let mut m = json!({"id": id, "name": "Tint", "kind": "filter", "runtime": "js", "script": "tint.js"});
if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) {
m.extend(extra);
}
let path = dir.join(format!("{id}.vcplugin"));
std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap();
if let Some(script) = script {
std::fs::write(dir.join("tint.js"), script).unwrap();
}
path.display().to_string()
}
/// The active document's layers and its undo steps.
fn state(s: &mut Session) -> (Value, usize) {
let layers = exec(s, "document.inspect", json!({}))["layers"].take();
(layers, s.doc().unwrap().history.undo.len())
}
fn fill(s: &Session, id: vectorcraft_doc::NodeId) -> Option<Color> {
s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color()
}
#[test]
fn a_javascript_filter_changes_a_fill_as_one_undo_step() {
let dir = folder("blue");
let mut s = session();
let path = package(&dir, "test.js.engine.blue", json!({}), Some(BLUE));
let info = exec(&mut s, "plugin.install", json!({"path": path, "replace": true}));
assert_eq!((info["runtime"].as_str(), info["script"].as_str(), info["kind"].as_str()), (Some("js"), Some("tint.js"), Some("filter")));
let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
exec(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"}));
select(&mut s, &[id]);
let before = state(&mut s);
let r = exec(&mut s, "plugin.run", json!({"id": "test.js.engine.blue"}));
assert_eq!(r["ids"], json!([id.0]));
assert_eq!(fill(&s, id).map(|c| c.to_rgb_uncalibrated()), Some([0.0, 0.0, 1.0]));
assert_eq!(state(&mut s).1, before.1 + 1, "one undo step");
exec(&mut s, "edit.undo", json!({}));
assert_eq!(state(&mut s), before);
exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.blue"}));
std::fs::remove_dir_all(&dir).unwrap();
}
/// An endless loop ends with the plug-in's instruction budget, the error names the plug-in, and the
/// document and its history stay as they were.
#[test]
fn an_endless_loop_stops_on_its_budget_and_changes_nothing() {
let dir = folder("loop");
let mut s = session();
let path = package(&dir, "test.js.engine.loop", json!({}), Some("function run(input) {\n while (true) {}\n}\n"));
exec(&mut s, "plugin.install", json!({"path": path, "replace": true}));
let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
select(&mut s, &[id]);
let before = state(&mut s);
let e = s.execute("plugin.run", &json!({"id": "test.js.engine.loop"})).unwrap_err().to_string();
assert!(e.contains("instruction budget") && e.contains("test.js.engine.loop, tint.js line 2"), "{e}");
assert_eq!(state(&mut s), before);
exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.loop"}));
std::fs::remove_dir_all(&dir).unwrap();
}
/// A filter that reads `File` throws a `ReferenceError`: the realm has none of the script runner's
/// file access. Nothing changes.
#[test]
fn a_javascript_filter_has_no_file_access() {
let dir = folder("file");
let mut s = session();
let path = package(&dir, "test.js.engine.file", json!({}), Some("function run(input) {\n return new File('/etc/passwd').read();\n}\n"));
exec(&mut s, "plugin.install", json!({"path": path, "replace": true}));
let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
select(&mut s, &[id]);
let before = state(&mut s);
let e = s.execute("plugin.run", &json!({"id": "test.js.engine.file"})).unwrap_err().to_string();
assert!(e.contains("ReferenceError") && e.contains("File") && e.contains("test.js.engine.file"), "{e}");
assert_eq!(state(&mut s), before);
exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.file"}));
std::fs::remove_dir_all(&dir).unwrap();
}
/// A manifest with `"runtime": "js"` and no `script` is refused at install, the error names the
/// key, and nothing is installed.
#[test]
fn a_manifest_without_its_script_is_refused_at_install() {
let dir = folder("noscript");
let mut s = session();
let path = package(&dir, "test.js.engine.noscript", json!({"script": null}), None);
let mut m: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
m.as_object_mut().unwrap().remove("script");
std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap();
for cmd in ["plugin.inspect", "plugin.install"] {
let e = s.execute(cmd, &json!({"path": path})).unwrap_err().to_string();
assert!(e.contains("`runtime` \"js\" needs `script`"), "{cmd}: {e}");
}
assert!(vectorcraft_plugins::registry::get("test.js.engine.noscript").is_none());
std::fs::remove_dir_all(&dir).unwrap();
}
+568
View File
@@ -0,0 +1,568 @@
//! Startup scripts (`script.startup.run`): off by default, the folder's `.jsx` files in order at
//! launch and before a chosen script, Safe Mode and disabled scripts, failures and limits, and the
//! launch marker naming the startup script that runs.
//!
//! A test binary of its own: Safe Mode, the disabled list and the launch marker are process-wide,
//! so these tests run one at a time and no other test sees them.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_plugins::safe_mode;
use vectorcraft_testkit::TempDir;
static LOCK: Mutex<()> = Mutex::new(());
/// Safe Mode off, nothing disabled, no launch marker.
fn reset() {
safe_mode::end_launch();
safe_mode::set_active(None);
safe_mode::forget_previous();
safe_mode::set_disabled(vec![]);
}
/// Holds the lock for one test and resets the process-wide state when the test starts and when it
/// ends, so a test that fails leaves the next one as it would find a new process.
struct Fresh {
_guard: std::sync::MutexGuard<'static, ()>,
}
fn fresh() -> Fresh {
let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
reset();
Fresh { _guard: guard }
}
impl Drop for Fresh {
fn drop(&mut self) {
reset();
}
}
/// A new, empty folder for test `tag`, removed with everything in it when the test ends.
fn tmp_dir(tag: &str) -> TempDir {
TempDir::new(&format!("script-startup-{tag}"))
}
/// Writes `text` to `name` under `dir`, folders included.
fn write(dir: &Path, name: &str, text: &str) -> PathBuf {
let path = dir.join(name);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, text).unwrap();
path
}
/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on.
fn session(dir: &Path) -> Session {
let mut s = Session::new();
s.attach_startup_scripts_dir(dir.to_path_buf());
s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap();
s
}
/// The names of the runs the Script Console started, in order.
fn started(s: &Session) -> Vec<String> {
let lines = s.script_console().to_json();
lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").map(|l| l["name"].as_str().unwrap().to_string()).collect()
}
/// The texts of the Script Console's lines of `kind`.
fn console(s: &Session, kind: &str) -> Vec<String> {
let lines = s.script_console().to_json();
lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == kind).map(|l| l["text"].as_str().unwrap().to_string()).collect()
}
fn names(v: &Value) -> Vec<&str> {
v.as_array().unwrap().iter().map(|n| n.as_str().unwrap()).collect()
}
#[test]
fn startup_scripts_are_off_by_default_and_run_nothing() {
let _f = fresh();
let dir = tmp_dir("off");
write(&dir, "a.jsx", "vc.log('ran');");
let mut s = Session::new();
assert!(!s.prefs.run_startup_scripts, "off by default");
s.attach_startup_scripts_dir(dir.to_path_buf());
assert_eq!(s.startup_skip(), Some("off"));
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!(r, json!({"reason": "launch", "skipped": true, "why": "off"}));
let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(1);", "name": "chosen"}})).unwrap();
assert_eq!(r["skipped"], true);
assert_eq!(r["then"]["ok"], true, "the chosen script still runs");
assert_eq!(started(&s), ["chosen"], "no startup script ran");
}
#[test]
fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script() {
let _f = fresh();
let dir = tmp_dir("order");
for name in ["b.jsx", "C.JSX", "a.jsx", ".hidden.jsx", "x.js", "lib.jsxinc", "sub/d.jsx", "notes.txt"] {
write(&dir, name, "vc.log(1);");
}
let mut s = session(&dir);
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!(r["skipped"], false);
assert_eq!(names(&r["ran"]), ["a.jsx", "b.jsx", "C.JSX"], "by name without regard to case");
assert!(r["failed"].as_array().unwrap().is_empty());
assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX"]);
let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap();
assert_eq!(r["then"]["ok"], true);
assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first");
}
#[test]
fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() {
let _f = fresh();
let dir = tmp_dir("missing");
let mut s = session(&dir.join("Startup Scripts"));
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!(r["skipped"], false);
assert!(r["ran"].as_array().unwrap().is_empty() && r["failed"].as_array().unwrap().is_empty());
assert_eq!(r["unreadable"], false);
let mut s = Session::new();
s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap();
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!(r["why"], "noFolder");
}
#[test]
fn safe_mode_skips_the_startup_scripts_and_still_runs_the_chosen_one() {
let _f = fresh();
let dir = tmp_dir("safe");
write(&dir, "a.jsx", "vc.log(1);");
let mut s = session(&dir);
safe_mode::set_active(Some(safe_mode::Source::Flag));
assert_eq!(s.startup_skip(), Some("safeMode"));
let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap();
assert_eq!(r["why"], "safeMode");
assert_eq!(started(&s), ["chosen"]);
}
#[test]
fn a_startup_script_the_safe_mode_choice_disabled_does_not_run() {
let _f = fresh();
let dir = tmp_dir("disabled");
let a = write(&dir, "a.jsx", "vc.log(1);");
write(&dir, "b.jsx", "vc.log(1);");
let mut s = session(&dir);
safe_mode::disable(safe_mode::Item::file(a.to_string_lossy()));
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!(names(&r["disabled"]), ["a.jsx"]);
assert_eq!(names(&r["ran"]), ["b.jsx"]);
}
#[test]
fn a_failing_or_endless_startup_script_is_reported_and_the_next_and_the_chosen_script_run() {
let _f = fresh();
let dir = tmp_dir("failing");
write(&dir, "1 throws.jsx", "throw new Error('broken');");
write(&dir, "2 endless.jsx", "for (;;) {}");
write(&dir, "3 syntax.jsx", "var = ;");
write(&dir, "4 fine.jsx", "vc.log(1);");
let mut s = session(&dir);
let then = json!({"source": "vc.log('chosen');", "name": "chosen"});
let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 100000})).unwrap();
let failed = r["failed"].as_array().unwrap();
let failed_names: Vec<&str> = failed.iter().map(|f| f["name"].as_str().unwrap()).collect();
assert_eq!(failed_names, ["1 throws.jsx", "2 endless.jsx", "3 syntax.jsx"]);
assert!(failed[0]["error"].as_str().unwrap().contains("broken"), "{failed:?}");
assert_eq!(names(&r["ran"]), ["4 fine.jsx"]);
assert_eq!(r["then"]["ok"], true, "the chosen script runs after them");
assert!(console(&s, "end").contains(&"ended: fuel".to_string()), "the endless one ran out of instructions");
}
#[test]
fn a_startup_script_larger_than_a_script_may_be_is_refused_unread() {
let _f = fresh();
let dir = tmp_dir("large");
let mut big = "//".to_string();
big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES));
write(&dir, "big.jsx", &big);
let mut s = session(&dir);
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}]));
assert!(console(&s, "error").iter().any(|l| l.contains(vectorcraft_engine::cmd::scripts::TOO_LARGE)), "the console names it");
}
#[test]
fn a_startup_script_cannot_start_another_startup_run() {
let _f = fresh();
let dir = tmp_dir("nested");
let text =
"try { vc.run('script.startup.run', {reason: 'menu', then: {source: 'vc.log(1);'}}); vc.log('nested'); } catch (e) { vc.log('refused'); }";
write(&dir, "a.jsx", text);
let mut s = session(&dir);
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!(names(&r["ran"]), ["a.jsx"]);
assert_eq!(console(&s, "log"), ["refused"]);
assert_eq!(started(&s), ["a.jsx"]);
}
#[test]
fn bad_parameters_are_refused() {
let _f = fresh();
let dir = tmp_dir("params");
let mut s = session(&dir);
for p in [
json!({}),
json!({"reason": "boot"}),
json!({"reason": "menu", "then": "x.jsx"}),
json!({"reason": "launch", "maxFuel": 0}),
json!({"reason": "launch", "maxFuel": 1.5}),
] {
assert!(s.execute("script.startup.run", &p).is_err(), "{p}");
}
// `then` is checked as `script.run` checks its parameters, before any startup script runs.
write(&dir, "a.jsx", "vc.log(1);");
let then = json!({"source": "vc.log(2);", "bogus": true});
let alone = s.execute("script.run", &then).unwrap_err().to_string();
let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err().to_string();
assert_eq!(e, alone);
assert!(started(&s).is_empty(), "no startup script ran");
}
#[test]
fn in_the_app_the_runs_are_queued_and_the_launch_marker_names_the_running_startup_script() {
let _f = fresh();
let dir = tmp_dir("app");
let launch = tmp_dir("app-launch");
write(&dir, "a.jsx", "vc.log(1);");
write(&dir, "b.jsx", "throw new Error('broken');");
let mut big = "//".to_string();
big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES));
write(&dir, "bb.jsx", &big);
write(&dir, "c.jsx", "vc.log(3);");
assert!(safe_mode::begin_launch(&launch).is_empty());
let mut s = session(&dir);
s.script_frames = true;
let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(4);", "name": "chosen"}})).unwrap();
assert_eq!((r["running"].clone(), r["queued"].clone(), r["failed"].clone()), (json!(true), json!(5), json!([])));
let marker = || {
let file = std::fs::read_dir(&launch)
.unwrap()
.filter_map(Result::ok)
.map(|e| e.path())
.find(|p| p.extension().is_some_and(|e| e == "json"))
.unwrap();
safe_mode::parse_marker(&std::fs::read(file).unwrap())
};
let names = |items: Vec<safe_mode::Item>| items.into_iter().map(|i| i.name).collect::<Vec<_>>();
assert_eq!(names(marker()), [Some("a.jsx".to_string())], "the marker names the running startup script");
let mut results = vec![];
for _ in 0..10_000 {
if !s.script_running() {
break;
}
if let Some(r) = s.script_pump() {
results.push(r.is_ok());
}
}
assert!(!s.script_running());
assert_eq!(results, [true, false, true, true], "each run reports as it ends");
assert_eq!(started(&s), ["a.jsx", "b.jsx", "bb.jsx", "c.jsx", "chosen"]);
let too_large = vectorcraft_engine::cmd::scripts::TOO_LARGE.to_string();
assert_eq!(s.take_startup_failures(), [("bb.jsx".to_string(), too_large)], "the one that could not start is kept for the app");
assert!(s.take_startup_failures().is_empty());
assert!(marker().is_empty(), "the marker names nothing once they have run");
}
#[test]
fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() {
let _f = fresh();
let dir = tmp_dir("app-then");
write(&dir, "a.jsx", "vc.log(1);");
let missing = dir.join("gone").join("missing.jsx");
let then = json!({"path": missing.to_string_lossy()});
for frames in [false, true] {
let mut s = session(&dir);
s.script_frames = frames;
let alone = s.execute("script.run", &then).unwrap_err().to_string();
let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err();
assert_eq!(e.to_string(), alone, "the error script.run gives, frames {frames}");
assert!(!s.script_running());
assert!(started(&s).is_empty(), "no startup script ran, frames {frames}");
assert!(s.take_startup_failures().is_empty());
let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"name": "neither"}})).unwrap_err();
assert!(e.to_string().contains("exactly one of"), "{e}");
assert!(started(&s).is_empty());
}
}
#[test]
fn a_stop_between_runs_survives_an_entry_that_cannot_start() {
let _f = fresh();
let dir = tmp_dir("stop-before-failed-entry");
write(&dir, "a.jsx", "vc.log('first');");
write(&dir, "b.jsx", "var = ;");
write(&dir, "c.jsx", "vc.log('must not run');");
for by_interrupt in [false, true] {
let mut s = session(&dir);
s.script_frames = true;
s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert!((0..10_000).find_map(|_| s.script_pump()).unwrap().is_ok());
if by_interrupt {
s.script_interrupt().set();
} else {
assert!(s.script_request_stop());
}
let stopped = (0..10_000).find_map(|_| s.script_pump()).unwrap();
assert!(stopped.is_err(), "by_interrupt={by_interrupt}");
assert_eq!(s.script_report().unwrap()["name"], "c.jsx");
assert_eq!(s.script_report().unwrap()["kind"], "stopped");
assert_eq!(console(&s, "log"), ["first"]);
assert_eq!(s.take_startup_failures().iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), ["b.jsx"]);
}
}
#[test]
fn the_chosen_run_reads_includes_after_the_startup_runs() {
let _f = fresh();
let dir = tmp_dir("chosen-includes");
let startup = dir.join("startup");
let chosen = dir.join("chosen");
write(&startup, "a.jsx", "vc.log('startup');");
let include = write(&chosen, "value.jsxinc", "vc.log('before');");
let main = write(&chosen, "main.jsx", "#include \"value.jsxinc\"\nvc.log('main');");
let mut s = session(&startup);
s.script_frames = true;
s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": main.to_string_lossy()}})).unwrap();
std::fs::write(&include, "vc.log('after');").unwrap();
for _ in 0..1000 {
if !s.script_running() {
break;
}
s.script_pump();
}
assert!(!s.script_running());
assert_eq!(console(&s, "log"), ["startup", "after", "main"]);
}
#[test]
fn failed_startup_entries_resume_in_fifo_order_on_later_pumps() {
let _f = fresh();
let dir = tmp_dir("failed-startup-pumps");
for name in ["a.jsx", "b.jsx", "c.jsx"] {
write(&dir, name, "var = ;");
}
let mut s = session(&dir);
s.script_frames = true;
let first = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log('chosen');", "name": "chosen"}})).unwrap();
let failures = first["failed"].as_array().unwrap();
assert!(!failures.is_empty() && failures.len() < 3, "{first}");
assert!(!started(&s).iter().any(|name| name == "chosen"), "the chosen run follows the remaining startup entries");
let mut failed: Vec<String> = failures.iter().map(|entry| entry["name"].as_str().unwrap().to_string()).collect();
for _ in 0..100 {
if !s.script_running() {
break;
}
s.script_pump();
failed.extend(s.take_startup_failures().into_iter().map(|(name, _)| name));
}
assert!(!s.script_running());
assert_eq!(failed, ["a.jsx", "b.jsx", "c.jsx"]);
assert_eq!(console(&s, "log"), ["chosen"]);
}
#[test]
fn a_failed_chosen_preflight_clears_the_previous_report() {
let _f = fresh();
let dir = tmp_dir("preflight-report");
write(&dir, "a.jsx", "vc.log('startup');");
for frames in [false, true] {
let mut s = session(&dir);
s.execute("script.run", &json!({"source": "vc.log('previous');"})).unwrap();
assert!(s.script_report().is_some());
let before = started(&s);
s.script_frames = frames;
assert!(s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})).is_err());
assert!(s.script_report().is_none(), "frames={frames}");
assert_eq!(started(&s), before);
assert!(!s.script_running());
}
}
#[test]
fn a_chosen_script_with_invalid_syntax_is_refused_before_startup_scripts_run() {
let _f = fresh();
let dir = tmp_dir("invalid-chosen-syntax");
write(&dir, "a.jsx", "vc.log('startup ran');");
for frames in [false, true] {
let mut s = session(&dir);
s.script_frames = frames;
let result = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}}));
assert!(result.is_err(), "frames={frames}: {result:?}");
assert!(!s.script_running());
assert!(started(&s).is_empty(), "no startup script ran, frames={frames}");
assert!(s.take_startup_failures().is_empty());
}
}
#[test]
fn an_installed_chosen_script_runs_the_text_read_before_startup_scripts() {
let _f = fresh();
for frames in [false, true] {
let dir = tmp_dir(if frames { "chosen-snapshot-sliced" } else { "chosen-snapshot-sync" });
let data = dir.join("data");
let startup = dir.join("startup");
let entry = write(&startup, "a.jsx", "");
let real = std::fs::canonicalize(&entry).unwrap();
let key = vectorcraft_plugins::permissions::sha256_hex(real.to_string_lossy().as_bytes());
let installed = data.join(&key[..16]);
let chosen = write(&installed, "chosen.jsx", "vc.log('chosen');");
let quoted = serde_json::to_string(&chosen.to_string_lossy()).unwrap();
write(&startup, "a.jsx", &format!("Folder.userData; if (!new File({quoted}).remove()) throw 'remove failed';"));
let mut s = session(&startup);
s.attach_script_data(data);
s.attach_scripts_dir(installed);
s.script_frames = frames;
s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": chosen, "installed": true}})).unwrap();
for _ in 0..10_000 {
if !s.script_running() {
break;
}
if let Some(result) = s.script_pump() {
result.unwrap();
}
}
assert!(!s.script_running());
assert!(s.take_startup_failures().is_empty());
assert_eq!(started(&s), ["a.jsx", "chosen.jsx"]);
assert!(!chosen.exists());
}
}
#[test]
fn in_the_app_a_stopped_startup_script_keeps_its_report_until_the_next_pump_starts_the_queued_run() {
let _f = fresh();
let dir = tmp_dir("app-stop");
write(&dir, "a.jsx", "for (;;) {}");
let mut s = session(&dir);
s.script_frames = true;
s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap();
assert!(s.script_pump().is_none(), "the endless one runs");
assert!(s.script_request_stop());
let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap();
assert!(ended.is_err());
assert_eq!(s.script_report().unwrap()["kind"], "stopped", "the ended run's report is still there");
assert!(s.script_running(), "the chosen script waits for the next pump");
// Nothing else starts ahead of the queued run.
let e = s.execute("script.run", &json!({"source": "vc.log(9);", "name": "direct"})).unwrap_err();
assert!(matches!(e, vectorcraft_engine::EngineError::Busy), "{e}");
assert_eq!(started(&s), ["a.jsx"]);
let r = (0..10_000).find_map(|_| s.script_pump()).unwrap();
assert_eq!(r.unwrap()["ok"], true);
assert_eq!(started(&s), ["a.jsx", "chosen"]);
assert!(!s.script_running());
}
#[test]
fn in_the_app_a_stop_between_two_runs_stops_the_run_that_starts_next() {
let _f = fresh();
let dir = tmp_dir("app-stop-between");
write(&dir, "a.jsx", "vc.log(1);");
write(&dir, "b.jsx", "for (;;) {}");
for by_interrupt in [false, true] {
let mut s = session(&dir);
s.script_frames = true;
let then = json!({"source": "vc.log(3);", "name": "chosen"});
s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 1_000_000})).unwrap();
assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends");
assert!(s.script_running(), "b.jsx waits for the next pump");
if by_interrupt {
// The status bar's Stop button.
s.script_interrupt().set();
} else {
assert!(s.script_request_stop(), "script.stop has a run to stop");
}
let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap();
assert!(ended.is_err());
assert_eq!(s.script_report().unwrap()["kind"], "stopped");
assert_eq!(s.script_report().unwrap()["name"], "b.jsx");
assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "the chosen script still runs");
assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]);
}
}
#[test]
fn a_startup_script_refused_before_it_begins_is_in_the_script_console() {
let _f = fresh();
let dir = tmp_dir("refused");
write(&dir, "a.jsx", "vc.log(1);");
let mut s = session(&dir);
s.execute("file.new", &json!({})).unwrap();
s.execute("edit.undoGroup.begin", &json!({})).unwrap();
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
let error = r["failed"][0]["error"].as_str().unwrap().to_string();
assert!(error.contains("undo group"), "{r}");
assert_eq!(started(&s), ["a.jsx"]);
assert_eq!(console(&s, "error"), [format!("a.jsx: {error}")]);
}
#[test]
fn in_the_app_abandoning_between_two_runs_drops_the_queued_runs() {
let _f = fresh();
let dir = tmp_dir("app-abandon-between");
write(&dir, "a.jsx", "vc.log(1);");
write(&dir, "b.jsx", "vc.log(2);");
let mut s = session(&dir);
s.script_frames = true;
let then = json!({"source": "vc.log(3);", "name": "chosen"});
s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap();
assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends");
assert!(s.script_running() && s.script_name().is_none(), "b.jsx waits for the next pump");
assert!(s.script_abandon(), "the queued runs are stopped");
assert!(!s.script_running());
assert!(s.script_pump().is_none());
assert_eq!(started(&s), ["a.jsx"]);
}
#[test]
fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() {
let _f = fresh();
let dir = tmp_dir("app-unread");
let mut big = "//".to_string();
big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES));
write(&dir, "big.jsx", &big);
let mut s = session(&dir);
s.script_frames = true;
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!(r["running"], json!(false));
assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}]));
assert!(s.take_startup_failures().is_empty(), "the reply names them, so the status bar does not again");
}
#[test]
fn in_the_app_every_queued_run_keeps_the_automation_roots_of_the_request_that_queued_it() {
let _f = fresh();
let dir = tmp_dir("app-roots");
// Writes a file in the run's temporary folder, which is outside the write roots below.
let source = "var ok; try { var t = new File(Folder.temp.fsName + '/t.txt'); ok = t.open('w'); t.close(); } catch (e) { ok = false; }\n\
vc.log(ok ? 'wrote' : 'refused');";
write(&dir, "a.jsx", source);
write(&dir, "b.jsx", source);
let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap().unwrap();
for confined in [false, true] {
let mut s = session(&dir);
s.script_frames = true;
let params = json!({"reason": "menu", "then": {"source": source, "name": "chosen"}});
let mut request = || s.execute("script.startup.run", &params).unwrap();
let r = if confined { vectorcraft_engine::file_access::confine(Some(&roots), request) } else { request() };
assert_eq!(r["queued"], json!(3));
// The frames that start the later runs are outside the request.
for _ in 0..1000 {
if !s.script_running() {
break;
}
s.script_pump();
}
assert!(!s.script_running(), "the startup queue did not finish, confined {confined}");
assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]);
let want = if confined { "refused" } else { "wrote" };
assert_eq!(console(&s, "log"), [want, want, want], "confined {confined}");
}
}
+3
View File
@@ -646,6 +646,9 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize
doc.dimensions = dimensions;
// Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too).
doc.fix_ruby();
// Untrusted: at most 64 tags an object, each name and value at most 64 KiB, with distinct ids
// (after the depth limit too).
doc.tidy_tags();
// Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite).
doc.raster_effects_ppi = Some(doc.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0);
// Untrusted: the superscript, subscript and small caps proportions of the type, the graph
+8
View File
@@ -244,6 +244,12 @@ pub enum Expr {
OptionalChain(ExprId),
/// The object or function before `?.` in an [`Expr::OptionalChain`].
Optional(ExprId),
/// `yield`, `yield expression` or (`delegate`) `yield* expression` in a generator function's
/// body (ECMA-262 2015 section 14.4).
Yield {
arg: Option<ExprId>,
delegate: bool,
},
}
/// A piece of a template literal's text between its substitutions.
@@ -440,6 +446,8 @@ pub struct Function {
/// The function's code is strict mode code: its own directive prologue holds `"use strict"`,
/// or the code around it is strict.
pub strict: bool,
/// A generator function (`function*`, or `*name() {…}` in an object literal).
pub generator: bool,
pub span: Span,
}
+27 -14
View File
@@ -3,8 +3,9 @@
//! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex
//! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and
//! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in
//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and
//! the iterators of arrays, strings and `arguments` objects (in `iterator`).
//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`),
//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator
//! objects' prototypes with `GeneratorFunction` (in `generator`).
//!
//! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object
//! or property it makes is checked against the heap limit before it is made, so no built-in can
@@ -12,6 +13,7 @@
mod array;
pub(crate) mod extensions;
mod generator;
mod global;
pub(crate) mod iterator;
mod json;
@@ -261,6 +263,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
if interp.options.es2015 {
symbol::install(interp, object)?;
iterator::install(interp)?;
generator::install(interp, function)?;
}
if interp.options.e4x {
crate::xml_builtins::install(interp)?;
@@ -471,7 +474,7 @@ pub(crate) fn arg(args: &[Value], i: usize) -> Value {
}
fn unreachable_native(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
Err(Abrupt::Internal("call or apply reached its native body".into()))
Err(Abrupt::Internal("a built-in the interpreter runs itself reached its native body".into()))
}
fn throw_type_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
@@ -610,7 +613,13 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b
/// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as
/// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function.
fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
const HEAD: &str = "(function anonymous(";
create_dynamic_function(interp, args, false)
}
/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with
/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`.
pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult<Value> {
let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" };
const MID: &str = "\n) {\n";
const TAIL: &str = "\n})";
let mut parts = Vec::with_capacity(args.len());
@@ -622,12 +631,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
let total = parts
.iter()
.map(Str::len)
.chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()])
.chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()])
.fold(0usize, usize::saturating_add);
interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?;
interp.prepare_source(total)?;
let mut units = Vec::with_capacity(total);
units.extend(HEAD.encode_utf16());
units.extend(head.encode_utf16());
for (i, p) in parts.iter().enumerate() {
if i > 0 {
units.push(u16::from(b','));
@@ -647,8 +656,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
};
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() });
let code = match compile_constructed_function(&program, &source) {
Ok(Some(code)) => code,
Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")),
Ok(Some(code)) if code.generator == generator => code,
Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")),
Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)),
Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)),
};
@@ -687,6 +696,10 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J
let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) };
let bound_this = arg(args, 0);
let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into();
// With ECMAScript 2015 the bound function inherits from the target's prototype, read before
// `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function
// inherits from %GeneratorFunction.prototype%.
let target_proto = interp.heap.object(target).and_then(|o| o.proto);
// A host function's `length` is an ordinary property a script can set, so it is converted
// to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is
// read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run.
@@ -700,7 +713,7 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J
// Adding 0 turns a negative zero into 0.
let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0;
if interp.options.es2015 {
return bind_es2015(interp, target, bound_this, bound_args, length);
return bind_es2015(interp, target, target_proto, bound_this, bound_args, length);
}
interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?;
let proto = interp.intrinsics.function_proto;
@@ -722,9 +735,10 @@ fn prop_bytes(names: &[&str]) -> usize {
/// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section
/// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the
/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps
/// the `caller` and `arguments` that throw, as without the option.
fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult<Value> {
/// target's `name` when that is a string (read after `length`, so a getter for it runs), and its
/// prototype is `proto`, the target's. It keeps the `caller` and `arguments` that throw, as
/// without the option.
fn bind_es2015(interp: &mut Interp, target: ObjId, proto: Option<ObjId>, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult<Value> {
let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? {
Value::String(s) => s,
_ => Str::from(""),
@@ -740,9 +754,8 @@ fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args
crate::string_builtins::charge_units(interp, name_len)?;
let mut units: Vec<u16> = "bound ".encode_utf16().collect();
units.extend_from_slice(&target_units);
let proto = interp.intrinsics.function_proto;
let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() });
let f = interp.heap.alloc_object(Object::new(class, Some(proto)));
let f = interp.heap.alloc_object(Object::new(class, proto));
interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len));
interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?;
interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?;
+51
View File
@@ -0,0 +1,51 @@
//! The generator built-ins (ECMA-262 11th edition, <https://262.ecma-international.org/11.0/>):
//! `%GeneratorFunction%` with its `prototype` (sections 25.2.1 and 25.2.3) and
//! `%GeneratorPrototype%` with `next`, `return` and `throw` (section 25.4.1), which inherits
//! from `%IteratorPrototype%`. Installed in a realm with [`crate::Options::es2015`] only, after the
//! iterators. `GeneratorFunction` is not a global; a script reaches it through a generator
//! function's `constructor`.
use super::{data, native, unreachable_native};
use crate::generator::ResumeMode;
use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeKind, ObjId, Object, Prop};
use crate::interp::{Interp, JsResult};
use crate::value::Value;
pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> {
let Some(to_string_tag) = interp.well_known(|w| &w.to_string_tag) else { return Ok(()) };
let Some(mut objects) = interp.symbols.objects else { return Ok(()) };
let object_proto = interp.intrinsics.object_proto;
let iterator_proto = interp.heap.object(objects.array_iterator_proto).and_then(|o| o.proto).unwrap_or(object_proto);
let generator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto)));
for (name, mode) in [("next", ResumeMode::Next), ("return", ResumeMode::Return), ("throw", ResumeMode::Throw)] {
let m = native(interp, name, unreachable_native, 1, NativeKind::Resume(mode), false)?;
data(interp, generator_proto, name, Value::Object(m), HIDDEN)?;
}
interp.define_sym(generator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Generator"), flags: CONFIGURABLE })?;
let function_proto = interp.intrinsics.function_proto;
// %GeneratorFunction.prototype% is an ordinary object, not a function, that inherits from
// Function.prototype (section 25.2.3).
let generator_function_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto)));
data(interp, generator_function_proto, "prototype", Value::Object(generator_proto), CONFIGURABLE)?;
data(interp, generator_proto, "constructor", Value::Object(generator_function_proto), CONFIGURABLE)?;
interp.define_sym(generator_function_proto, to_string_tag, Prop::Data { value: Value::str("GeneratorFunction"), flags: CONFIGURABLE })?;
let generator_function = native(interp, "GeneratorFunction", generator_function_ctor, 1, NativeKind::Plain, true)?;
if let Some(o) = interp.heap.object_mut(generator_function) {
o.proto = Some(function);
}
data(interp, generator_function, "prototype", Value::Object(generator_function_proto), 0)?;
data(interp, generator_function_proto, "constructor", Value::Object(generator_function), CONFIGURABLE)?;
objects.generator_proto = generator_proto;
objects.generator_function_proto = generator_function_proto;
interp.symbols.objects = Some(objects);
Ok(())
}
/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1).
fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
super::create_dynamic_function(interp, args, true)
}
+1 -1
View File
@@ -84,7 +84,7 @@ fn iter_result_bytes() -> usize {
}
/// CreateIterResultObject (section 7.4.7): `{ value, done }`.
fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult<Value> {
pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult<Value> {
interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?;
let proto = interp.intrinsics.object_proto;
let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)));
+9 -4
View File
@@ -30,7 +30,9 @@ use std::rc::Rc;
use super::{arg, constructor, create_at, method, native, new_array};
use crate::LimitKind;
use crate::bytecode::Code;
use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key};
use crate::heap::{
BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key,
};
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
use crate::value::Value;
@@ -261,6 +263,9 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
let object_proto = interp.intrinsics.object_proto;
let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
interp.promises.proto = Some(proto);
if let Some(tag) = interp.well_known(|w| &w.to_string_tag) {
interp.define_sym(proto, tag, Prop::Data { value: Value::str("Promise"), flags: CONFIGURABLE })?;
}
let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?;
interp.promises.ctor = Some(ctor);
constructor(interp, "Promise", ctor, proto)?;
@@ -928,8 +933,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<V
Err(Abrupt::Throw(thunk_value(interp, args)?))
}
/// `v` is a constructor: a function written in JavaScript other than an arrow function or a
/// method, a built-in constructor, or a bound function whose target is one.
/// `v` is a constructor: a function written in JavaScript other than an arrow function, generator
/// function or method, a built-in constructor, or a bound function whose target is one.
fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult<bool> {
let mut v = v.clone();
loop {
@@ -938,7 +943,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult<bool> {
_ => return Ok(false),
};
match func {
Func::Closure { code, .. } => return Ok(!code.arrow && !code.method),
Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator),
Func::Native { constructor, .. } => return Ok(constructor),
Func::Bound { target, .. } => {
interp.use_fuel()?;
+4 -1
View File
@@ -44,13 +44,16 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> {
method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?;
let function_proto = interp.intrinsics.function_proto;
let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?;
// The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed.
// The iterator and generator prototypes and `%ArrayProto_values%` are set when the iterators
// and generators are installed.
interp.symbols.objects = Some(Es2015Objects {
symbol_proto: proto,
array_iterator_proto: proto,
string_iterator_proto: proto,
array_values: has_instance,
has_instance,
generator_proto: proto,
generator_function_proto: function_proto,
});
Ok(())
}
+34
View File
@@ -246,6 +246,30 @@ pub(crate) enum Op {
InitIndex,
/// `object key function` → `object`: a getter (`true`) or a setter with a computed name.
InitAccessorIndex(bool),
/// Ends a generator function's call once its parameters are initialized: the frame becomes a
/// new generator object, which the call returns. The first `next` goes on after it.
GeneratorStart,
/// `value` → `received mode`: suspends the generator, giving its caller `{ value, done: false }`
/// (or, when true, the value itself, an iterator result from `yield*`'s delegate). It goes on
/// when the generator is resumed, with the value it was resumed with and how (0 `next`, 1
/// `throw`, 2 `return`).
Yield(bool),
/// `received mode` → `received`: goes on for `next`, throws the value for `throw`, and jumps
/// with it for `return`.
Resume(u32),
/// `value` → `iterator next`: GetIterator (ECMA-262 11th edition, section 7.4.1) for `yield*`,
/// which calls the iterator's methods itself.
DelegateIterator,
/// `iterator next received mode` → `iterator next mode method iterator received`, ready for
/// `Call(1)`: the delegate's `next`, `throw` or `return`. With `return` and no `return` method
/// it jumps with `iterator next received`; with `throw` and no `throw` method it closes the
/// iterator and throws a `TypeError` (section 14.4.14).
DelegateCall(u32),
/// `mode result` → `result` when the iterator result is not done; when it is, jumps with
/// `mode value`. A result that is not an object is a `TypeError`.
DelegateResult(u32),
/// `mode value` → `value`; for `return`, jumps with it.
DelegateDone(u32),
}
/// The names a block declares, entered with [`Op::PushBlock`].
@@ -354,6 +378,9 @@ pub(crate) struct Code {
/// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]:
/// its functions have no `prototype` and cannot be constructed (section 14.3.8).
pub(crate) method: bool,
/// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]),
/// and it is not a constructor.
pub(crate) generator: bool,
}
/// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors.
@@ -476,6 +503,12 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
Op::IterClose => e(1, 0),
Op::IterCloseThrow => end(2),
Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1),
Op::GeneratorStart => e(0, 0),
Op::Yield(_) => e(1, 2),
Op::Resume(t) | Op::DelegateDone(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 1)] },
Op::DelegateIterator => e(1, 2),
Op::DelegateCall(t) => Effect { pops: 2, next: Some(4), jumps: vec![(t, 1)] },
Op::DelegateResult(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 2)] },
})
}
@@ -511,6 +544,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> {
Op::PushBlock(i) => check(i, code.scopes.len(), "scope"),
Op::TemplateObject(i) => check(i, code.templates.len(), "template"),
Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"),
Op::GeneratorStart | Op::Yield(_) if !code.generator => Err("a generator instruction outside a generator function".into()),
_ => Ok(()),
}
}
+82 -3
View File
@@ -109,6 +109,8 @@ struct FnCompiler<'a> {
/// The optional chains being compiled, innermost last: where a step that finds `undefined`
/// or `null` jumps, and the stack depth the chain started at.
optional: Vec<(Label, u32)>,
/// The code is a generator function's.
generator: bool,
}
/// The `var` names and function declarations a body hoists.
@@ -157,6 +159,7 @@ impl<'a> FnCompiler<'a> {
block_funcs: HashSet::new(),
annex: HashSet::new(),
optional: Vec::new(),
generator: false,
}
}
@@ -281,12 +284,13 @@ impl<'a> FnCompiler<'a> {
Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))),
Stmt::Lexical(..) => {}
Stmt::FunctionDecl(fid) => {
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else {
return internal("function declaration without a name");
};
let k = key_of(&name.name);
if self.es2015 && nested {
if !self.strict {
// Annex B.3.3 gives plain function declarations only a var binding too.
if !self.strict && !generator {
annex.push((k, scope, id));
}
} else {
@@ -1351,10 +1355,73 @@ impl<'a> FnCompiler<'a> {
self.at(self.ast.expr_span(id).end);
self.nullish_check()?;
}
Expr::Yield { arg, delegate: false } => {
match arg {
Some(e) => self.expr(*e)?,
None => self.emit(Op::Undefined),
}
self.at(self.ast.expr_span(id).start);
self.emit(Op::Yield(false));
self.resume_after_yield()?;
}
Expr::Yield { arg: Some(e), delegate: true } => self.yield_delegate(id, *e)?,
Expr::Yield { arg: None, delegate: true } => return internal("yield* without an operand"),
}
Ok(())
}
/// After a `Yield` that left `received mode`: goes on with the received value for `next`,
/// throws it for `throw`, and for `return` returns it through the `finally` blocks around.
fn resume_after_yield(&mut self) -> CResult<()> {
if !self.generator {
return internal("yield outside a generator function");
}
let ret = self.new_label();
let after = self.new_label();
self.jump(Op::Resume, ret);
self.jump(Op::Jump, after);
self.bind(ret);
self.emit_exit(Exit::Return)?;
self.bind(after);
Ok(())
}
/// `yield* operand` (ECMA-262 11th edition, section 14.4.14): each `next`, `throw` and `return`
/// the generator is resumed with goes to the operand's iterator, each result it gives that is
/// not done is yielded as it is, and a done one gives the expression its value, or for a
/// `return` returns that value.
fn yield_delegate(&mut self, id: ExprId, operand: ExprId) -> CResult<()> {
if !self.generator {
return internal("yield outside a generator function");
}
let d = self.depth;
self.expr(operand)?;
self.at(self.ast.expr_span(id).start);
self.emit(Op::DelegateIterator);
// The first step calls `next` with one argument, `undefined`: the spec starts with
// `received` as NormalCompletion(undefined) and calls `next` with « received.[[Value]] ».
self.emit(Op::Undefined);
self.push_number(0.0);
let (step, ret, done, end) = (self.new_label(), self.new_label(), self.new_label(), self.new_label());
self.bind(step);
self.jump(Op::DelegateCall, ret);
self.emit(Op::Call(1));
self.jump(Op::DelegateResult, done);
self.emit(Op::Yield(true));
self.jump(Op::Jump, step);
self.bind(done);
self.depth = d + 4;
self.jump(Op::DelegateDone, ret);
self.emit(Op::PopUnder(2));
self.jump(Op::Jump, end);
self.bind(ret);
self.depth = d + 3;
self.emit_exit(Exit::Return)?;
self.bind(end);
self.depth = d + 1;
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<()> {
@@ -2075,7 +2142,11 @@ impl<'a> FnCompiler<'a> {
| Op::JumpIfNullish { target: t, .. }
| Op::ForInNext(t)
| Op::IterStep(t)
| Op::XmlFilterNext(t),
| Op::XmlFilterNext(t)
| Op::Resume(t)
| Op::DelegateCall(t)
| Op::DelegateResult(t)
| Op::DelegateDone(t),
) => *t = target,
_ => return internal("patching an instruction that is not a jump"),
}
@@ -2123,6 +2194,7 @@ impl<'a> FnCompiler<'a> {
es2015: self.es2015,
own_name: meta.own_name,
method: meta.method,
generator: self.generator,
};
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
Ok(Rc::new(code))
@@ -2156,6 +2228,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
let Some(f) = ast.function(fid) else { return internal("function out of range") };
let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion);
c.es2015 = es2015;
c.generator = f.generator;
c.at(f.span.start);
c.enter()?;
// A destructured parameter has a binding of its own under a name no script can write, which
@@ -2207,6 +2280,12 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
}
c.emit(Op::BodyEnv);
}
if f.generator {
// The call has bound the arguments and run the default values; the body waits for
// the first `next` (ECMA-262 2015 section 14.4.11).
c.at(f.span.start);
c.emit(Op::GeneratorStart);
}
c.stmts(&f.body)?;
c.at(f.span.end.saturating_sub(1));
c.emit(Op::Undefined);
+414
View File
@@ -0,0 +1,414 @@
//! Generator objects (ECMA-262 11th edition, <https://262.ecma-international.org/11.0/>,
//! sections 14.4 and 25.4), in a realm with [`crate::Options::es2015`].
//!
//! A call to a generator function runs its parameters' initialization and stops at
//! [`Op::GeneratorStart`]: its frame, with the operands above the frame's base and the `finally`
//! blocks it is inside, moves into a new generator object, which the call returns. `next`,
//! `return` and `throw` push the frame back on the interpreter's frame stack and go on in the same
//! loop, so a generator driven from JavaScript uses no Rust stack, and each resumption takes a unit
//! of fuel and counts against the frame limit. `yield` moves the frame back into the object. A
//! suspended generator's frame is reachable only through its object, so the collector keeps it
//! while the object is reachable and frees it with the object.
//!
//! [`Op::GeneratorStart`]: crate::bytecode::Op::GeneratorStart
use std::rc::Rc;
use crate::LimitKind;
use crate::builtins::iterator::iter_result;
use crate::bytecode::Code;
use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key};
use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal};
use crate::value::Value;
/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4).
/// The code after a `yield` reads it as the number [`ResumeMode::number`] gives.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ResumeMode {
Next,
Throw,
Return,
}
impl ResumeMode {
fn number(self) -> f64 {
match self {
ResumeMode::Next => 0.0,
ResumeMode::Throw => 1.0,
ResumeMode::Return => 2.0,
}
}
fn of(v: &Value) -> JsResult<Self> {
match v {
Value::Number(n) if *n == 0.0 => Ok(ResumeMode::Next),
Value::Number(n) if *n == 1.0 => Ok(ResumeMode::Throw),
Value::Number(n) if *n == 2.0 => Ok(ResumeMode::Return),
_ => internal("a resumption mode that is not one"),
}
}
}
/// The estimated bytes of a suspended generator's frame besides its operands.
const GENERATOR_BYTES: usize = 128;
/// The estimated bytes of each operand and `finally` entry a suspended frame holds.
const SLOT_BYTES: usize = 16;
/// A generator's frame while it is suspended: what [`Frame`] holds, with the operands above its
/// base and its `finally` entries, their stack slots counted from its base.
#[derive(Clone)]
pub(crate) struct SavedFrame {
pub(crate) code: Rc<Code>,
pc: usize,
pub(crate) env: EnvId,
pub(crate) var_env: EnvId,
env_depth: u32,
pub(crate) this: Value,
pub(crate) callee: Option<ObjId>,
pub(crate) completion: Value,
pub(crate) stack: Vec<Value>,
/// [`Interp::finally_sites`] entries.
pub(crate) sites: Vec<(ThrowSite, usize)>,
/// [`Interp::finally_marks`] entries.
pub(crate) marks: Vec<(ObjId, u32, usize)>,
}
/// A generator's [[GeneratorState]] (section 25.4.3), with its frame while it is suspended.
#[derive(Clone)]
pub(crate) enum GenState {
SuspendedStart(SavedFrame),
SuspendedYield(SavedFrame),
Executing,
Completed,
}
impl GenState {
/// The suspended frame, if the generator is suspended.
pub(crate) fn saved(&self) -> Option<&SavedFrame> {
match self {
GenState::SuspendedStart(s) | GenState::SuspendedYield(s) => Some(s),
GenState::Executing | GenState::Completed => None,
}
}
}
/// The bytes a suspended frame adds to its generator object, which a collection counts.
pub(crate) fn saved_bytes(s: &SavedFrame) -> usize {
GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(s.stack.len().saturating_add(s.sites.len()).saturating_add(s.marks.len())))
}
/// A generator resumed by `next`, `return` or `throw`, ready to be pushed: the value it was
/// resumed with and how, unless it had not started.
pub(crate) struct Resumed {
generator: ObjId,
saved: SavedFrame,
received: Option<(Value, ResumeMode)>,
}
impl Interp {
fn generator_state_mut(&mut self, g: ObjId) -> Option<&mut GenState> {
match self.heap.object_mut(g).map(|o| &mut o.class) {
Some(Class::Generator(s)) => Some(s),
_ => None,
}
}
/// Marks the generator `g`, whose frame was popped without being saved, completed.
pub(crate) fn end_generator(&mut self, g: Option<ObjId>) {
if let Some(state) = g.and_then(|g| self.generator_state_mut(g))
&& let GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved) = std::mem::replace(state, GenState::Completed)
{
self.release_saved(&saved);
}
}
/// Takes a saved frame that left its generator object off the heap's total.
fn release_saved(&mut self, saved: &SavedFrame) {
self.heap.bytes = self.heap.bytes.saturating_sub(saved_bytes(saved));
}
/// Gives a frame's caller `v`: the Rust call that pushed a boundary frame, or the frame below.
fn deliver(&mut self, boundary: bool, v: Value) -> JsResult<Option<Value>> {
if boundary {
return Ok(Some(v));
}
self.push(v)?;
Ok(None)
}
/// Moves `frame`, just popped, with its operands and `finally` entries, into a [`SavedFrame`].
fn save_frame(&mut self, frame: Frame) -> SavedFrame {
let base = frame.base;
let stack = self.stack.split_off(base.min(self.stack.len()));
let i = self.finally_sites.partition_point(|&(_, slot)| slot < base);
let sites = self.finally_sites.split_off(i).into_iter().map(|(site, slot)| (site, slot - base)).collect();
let mut marks = Vec::new();
self.finally_marks.retain(|&(id, mark, slot)| {
let below = slot < base;
if !below {
marks.push((id, mark, slot - base));
}
below
});
SavedFrame {
code: frame.code,
pc: frame.pc,
env: frame.env,
var_env: frame.var_env,
env_depth: frame.env_depth,
this: frame.this,
callee: frame.callee,
completion: frame.completion,
stack,
sites,
marks,
}
}
/// [`Op::GeneratorStart`](crate::bytecode::Op::GeneratorStart): OrdinaryCreateFromConstructor
/// of the function's `prototype` (section 14.4.11), or %GeneratorPrototype% when that is not an
/// object, holding the frame, which the call returns.
pub(crate) fn op_generator_start(&mut self) -> JsResult<Option<Value>> {
let Some(callee) = self.frame()?.callee else { return internal("a generator's body without its function") };
// A realm made without `Options::es2015` that reads the syntax later has no generator
// built-ins.
let Some(fallback) = self.symbols.objects.map(|o| o.generator_proto) else {
return Err(self.type_error("generators need the ECMAScript 2015 built-ins, and this realm was made without them"));
};
let proto = match self.get_from(callee, &key("prototype"), &Value::Object(callee))? {
Value::Object(p) => p,
_ => fallback,
};
self.rooted(&[Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + GENERATOR_BYTES))?;
let Some(frame) = self.frames.pop() else { return internal("no frame") };
let boundary = frame.boundary;
let saved = self.save_frame(frame);
let bytes = saved_bytes(&saved);
let g = self.heap.alloc_object(Object::new(Class::Generator(Box::new(GenState::SuspendedStart(saved))), Some(proto)));
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
self.deliver(boundary, Value::Object(g))
}
/// [`Op::Yield`](crate::bytecode::Op::Yield): GeneratorYield (section 25.4.3.7). The frame,
/// already past the instruction, goes into the generator object, and its caller gets the
/// iterator result.
pub(crate) fn op_yield(&mut self, raw: bool) -> JsResult<Option<Value>> {
let Some(g) = self.frame()?.generator else { return internal("yield outside a generator's body") };
if !raw {
let v = self.peek(0)?;
let result = iter_result(self, v, false)?;
self.replace(1, result)?;
}
// What `save_frame` keeps: the frame's operands without the result, popped below, and its
// own `finally` entries, not those of the frames under it.
let base = self.frame()?.base;
let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base));
let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count();
let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks);
let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held));
self.reserve_heap(bytes)?;
let result = self.pop()?;
let Some(frame) = self.frames.pop() else { return internal("no frame") };
let boundary = frame.boundary;
let saved = self.save_frame(frame);
self.heap.bytes = self.heap.bytes.saturating_add(saved_bytes(&saved));
let Some(state) = self.generator_state_mut(g) else { return internal("a generator's frame without its object") };
*state = GenState::SuspendedYield(saved);
self.deliver(boundary, result)
}
/// GeneratorResume and GeneratorResumeAbrupt (sections 25.4.3.3 and 25.4.3.4) for `next`,
/// `return` and `throw` called on `this` with `sent`: the result when the generator does not
/// run, or its frame to push.
pub(crate) fn prepare_resume(&mut self, this: Value, mode: ResumeMode, sent: Value) -> JsResult<Prepared> {
// Whether it has started, or `None` when it is running or completed.
let (g, started) = match this {
Value::Object(g) => match self.heap.object(g).map(|o| &o.class) {
Some(Class::Generator(s)) => match **s {
GenState::SuspendedStart(_) => (g, Some(false)),
GenState::SuspendedYield(_) => (g, Some(true)),
GenState::Executing => return Err(self.type_error("the generator is already running")),
GenState::Completed => (g, None),
},
_ => return Err(self.type_error("the value is not a generator object")),
},
_ => return Err(self.type_error("the value is not a generator object")),
};
let Some(started) = started else {
return match mode {
ResumeMode::Next => Ok(Prepared::Done(iter_result(self, Value::Undefined, true)?)),
ResumeMode::Return => Ok(Prepared::Done(iter_result(self, sent, true)?)),
ResumeMode::Throw => Err(Abrupt::Throw(sent)),
};
};
if !started && mode != ResumeMode::Next {
self.end_generator(Some(g));
return match mode {
ResumeMode::Throw => Err(Abrupt::Throw(sent)),
_ => Ok(Prepared::Done(iter_result(self, sent, true)?)),
};
}
if self.frames.len() >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
}
let Some(state) = self.generator_state_mut(g) else { return internal("a generator object without its state") };
let (GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved)) = std::mem::replace(state, GenState::Executing) else {
return internal("a suspended generator without its frame");
};
self.release_saved(&saved);
let received = started.then_some((sent, mode));
Ok(Prepared::Resume(Box::new(Resumed { generator: g, saved, received })))
}
/// Pushes a resumed generator's frame, with the value it was resumed with and how on top of
/// its operands when it had yielded.
pub(crate) fn enter_resumed(&mut self, r: Resumed, boundary: bool) -> JsResult<()> {
let Resumed { generator, saved, received } = r;
if self.frames.len() >= self.limits.frames {
let bytes = saved_bytes(&saved);
if let Some(state) = self.generator_state_mut(generator) {
*state = if received.is_some() { GenState::SuspendedYield(saved) } else { GenState::SuspendedStart(saved) };
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
}
return Err(Abrupt::Limit(LimitKind::Frames));
}
let base = self.stack.len();
self.drop_left_finally_sites(base);
let SavedFrame { code, pc, env, var_env, env_depth, this, callee, completion, stack, sites, marks } = saved;
self.stack.extend(stack);
if let Some((value, mode)) = received {
self.stack.push(value);
self.stack.push(Value::Number(mode.number()));
}
self.finally_sites.extend(sites.into_iter().map(|(site, slot)| (site, slot + base)));
self.finally_marks.extend(marks.into_iter().map(|(id, mark, slot)| (id, mark, slot + base)));
self.frames.push(Frame {
code,
pc,
base,
env,
var_env,
env_depth,
this,
callee,
construct: None,
completion,
boundary,
generator: Some(generator),
});
Ok(())
}
/// [`Op::Resume`](crate::bytecode::Op::Resume): `received mode` → `received`.
pub(crate) fn op_resume(&mut self, target: u32) -> JsResult<()> {
let mode = ResumeMode::of(&self.peek(0)?)?;
let received = self.peek(1)?;
self.pop()?;
self.pop()?;
match mode {
ResumeMode::Next => self.push(received),
ResumeMode::Throw => {
self.thrown_mark = None;
Err(Abrupt::Throw(received))
}
ResumeMode::Return => {
self.push(received)?;
self.jump_to(target)
}
}
}
/// GetMethod (section 7.3.10): the property `name` of `v`, `None` when it is `undefined` or
/// `null`.
fn get_method(&mut self, v: &Value, name: &str) -> JsResult<Option<Value>> {
let f = self.get_value(v, &key(name))?;
if f.is_nullish() {
return Ok(None);
}
if !self.is_callable(&f) {
return Err(self.type_error(&format!("the iterator's {name} is not a function")));
}
Ok(Some(f))
}
/// [`Op::DelegateIterator`](crate::bytecode::Op::DelegateIterator): `value` → `iterator next`.
pub(crate) fn op_delegate_iterator(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let Some(sym) = self.well_known(|w| &w.iterator) else { return internal("no Symbol.iterator in this realm") };
let method = self.get_value_sym(&v, &sym)?;
if !self.is_callable(&method) {
return Err(self.type_error("the value is not iterable"));
}
let iterator = self.call(&method, &v, &[])?;
if !matches!(iterator, Value::Object(_)) {
return Err(self.type_error("the iterator is not an object"));
}
self.replace(1, iterator.clone())?;
let next = self.get_value(&iterator, &key("next"))?;
self.push(next)
}
/// [`Op::DelegateCall`](crate::bytecode::Op::DelegateCall): the method of `yield*`'s iterator
/// that the generator's resumption calls (section 14.4.14, step 7).
pub(crate) fn op_delegate_call(&mut self, target: u32) -> JsResult<()> {
let mode = ResumeMode::of(&self.peek(0)?)?;
let iterator = self.peek(3)?;
let method = match mode {
ResumeMode::Next => Some(self.peek(2)?),
ResumeMode::Throw => self.get_method(&iterator, "throw")?,
ResumeMode::Return => self.get_method(&iterator, "return")?,
};
let received = self.peek(1)?;
match (method, mode) {
(Some(m), _) => {
self.replace(2, Value::Number(mode.number()))?;
self.push(m)?;
self.push(iterator)?;
self.push(received)
}
(None, ResumeMode::Return) => {
self.replace(2, received)?;
self.jump_to(target)
}
(None, _) => {
// The iterator has no `throw`: it is closed, and the protocol violation is a
// `TypeError` (step 7.b.iii).
if let Some(close) = self.get_method(&iterator, "return")? {
let result = self.call(&close, &iterator, &[])?;
if !matches!(result, Value::Object(_)) {
return Err(self.type_error("the iterator result is not an object"));
}
}
Err(self.type_error("the iterator has no throw method"))
}
}
}
/// [`Op::DelegateResult`](crate::bytecode::Op::DelegateResult): `mode result` → `result`, or
/// when it is done, a jump with `mode value`.
pub(crate) fn op_delegate_result(&mut self, target: u32) -> JsResult<()> {
let result = self.peek(0)?;
if !matches!(result, Value::Object(_)) {
return Err(self.type_error("the iterator result is not an object"));
}
if self.get_value(&result, &key("done"))?.truthy() {
let value = self.get_value(&result, &key("value"))?;
self.replace(1, value)?;
return self.jump_to(target);
}
self.replace(2, result)
}
/// [`Op::DelegateDone`](crate::bytecode::Op::DelegateDone): `mode value` → `value`, a jump for
/// `return`.
pub(crate) fn op_delegate_done(&mut self, target: u32) -> JsResult<()> {
let mode = ResumeMode::of(&self.peek(1)?)?;
let value = self.peek(0)?;
self.replace(2, value)?;
if mode == ResumeMode::Return {
return self.jump_to(target);
}
Ok(())
}
}
+382
View File
@@ -0,0 +1,382 @@
//! Generator functions, `yield`, `yield*` and the generator objects, in a realm with
//! [`Options::es2015`].
use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind};
fn es2015(limits: Limits) -> Realm {
Realm::with_options(Options { es2015: true, ..Options::default() }, limits)
}
fn run(src: &str) -> JsValue {
match es2015(Limits::default()).run(src) {
Ok(v) => v,
Err(e) => panic!("{src}\n{e:?}"),
}
}
fn truth(src: &str) {
assert_eq!(run(src), JsValue::Bool(true), "{src}");
}
fn string(src: &str) -> String {
match run(src) {
JsValue::String(s) => s,
other => panic!("{src}: {other:?}"),
}
}
/// The run throws an error whose message starts with `name`.
fn throws(src: &str, name: &str) {
match es2015(Limits::default()).run(src) {
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"),
other => panic!("{src}: {other:?}"),
}
}
/// The script does not parse in a realm with `options`.
fn syntax_with(src: &str, options: Options) {
match Realm::with_options(options, Limits::default()).run(src) {
Err(RunError { kind: RunErrorKind::Syntax, .. }) => {}
other => panic!("{src}: {other:?}"),
}
}
fn syntax(src: &str) {
syntax_with(src, Options { es2015: true, ..Options::default() });
}
#[test]
fn promise_jobs_resume_generator_callbacks() {
let mut realm = es2015(Limits::default());
realm
.run(
"var log = []; var it = (function* () { log.push('start'); var value = yield 7; \
log.push('resume:' + value); return 9; })(); \
Promise.resolve().then(it.next.bind(it)).then(function (result) { \
log.push(result.value + ':' + result.done); return it.next(5); \
}).then(function (result) { log.push(result.value + ':' + result.done); });",
)
.unwrap();
assert_eq!(realm.run("log.join(',')").unwrap(), JsValue::String("start,7:false,resume:5,9:true".into()));
}
#[test]
fn promise_static_methods_reject_generator_constructors() {
truth(
"var g = function* () {}, count = 0; [g, g.bind(null)].forEach(function (C) { \
try { Promise.resolve.call(C, 1); } catch (error) { if (error instanceof TypeError) count++; } \
try { Promise.reject.call(C, 1).catch(function () {}); } \
catch (error) { if (error instanceof TypeError) count++; } }); count === 4",
);
}
#[test]
fn a_generator_runs_its_body_one_yield_at_a_time() {
assert_eq!(
string(
"var log = []; function* g(a, b) { log.push('start'); var x = yield a; log.push(x); yield b + x; return 'end'; } \
var it = g(1, 2); log.push('made'); var r = [it.next('ignored'), it.next(10), it.next(20), it.next()]; \
log.join() + ' ' + r.map(function (o) { return o.value + ':' + o.done; }).join()"
),
"made,start,10 1:false,12:false,end:true,undefined:true"
);
// The parameters' default values run at the call, the body at the first `next`.
assert_eq!(string("var log = []; function* g(a = log.push('d')) { log.push('b'); } var it = g(); log.push('c'); it.next(); log.join()"), "d,c,b");
truth("function* g() { yield this; } var o = { g: g }; o.g().next().value === o");
truth("function* g() { return arguments.length; } g(1, 2, 3).next().value === 3");
truth("var it = (function* () {})(); var r = it.next(); r.value === undefined && r.done === true");
truth("function* g() { yield 1; } var a = g(), b = g(); a.next(); a.next().done && !b.next().done");
}
#[test]
fn yield_takes_an_operand_only_on_the_same_line() {
assert_eq!(string("function* g() { yield\n1; } var it = g(); String(it.next().value) + ',' + it.next().done"), "undefined,true");
truth("function* g() { var x = yield; return x; } var it = g(); it.next(); it.next(7).value === 7");
truth("function* g() { yield /a/g; } g().next().value instanceof RegExp");
truth("function* g() { yield yield 1; } var it = g(); it.next().value === 1 && it.next(2).value === 2");
truth("function* g() { var a = [yield 1, yield 2]; return a.join(); } var it = g(); it.next(); it.next('x'); it.next('y').value === 'x,y'");
}
#[test]
fn return_runs_the_finally_blocks_around_the_yield() {
truth(
"var log = []; function* g() { try { yield 1; yield 2; } finally { log.push('f'); } } \
var it = g(); it.next(); var r = it.return(9); r.value === 9 && r.done === true && log.join() === 'f' && it.next().done",
);
// A `finally` block that yields suspends the return, which ends at the next resumption.
assert_eq!(
string(
"function* g() { try { yield 1; } finally { yield 'cleanup'; } } var it = g(); it.next(); \
var a = it.return(5), b = it.next(), c = it.next(); [a.value, a.done, b.value, b.done, c.done].join()"
),
"cleanup,false,5,true,true"
);
truth("function* g() { try { yield 1; } finally { return 'override'; } } var it = g(); it.next(); it.return(5).value === 'override'");
// Before the body starts, and after it ends, `return` only completes the generator.
truth("var ran = false; function* g() { ran = true; } var it = g(); var r = it.return(3); r.value === 3 && r.done && !ran && it.next().done");
truth("function* g() {} var it = g(); it.next(); var r = it.return(4); r.value === 4 && r.done");
}
#[test]
fn throw_goes_into_a_suspended_generator() {
truth("function* g() { try { yield 1; } catch (e) { yield 'caught ' + e; } } var it = g(); it.next(); it.throw('x').value === 'caught x'");
truth(
"function* g() { yield 1; yield 2; } var it = g(); it.next(); var e; try { it.throw(new RangeError('r')); } catch (x) { e = x; } \
e instanceof RangeError && it.next().done",
);
// A generator that has not started is completed by `throw`, which its body never sees.
truth(
"var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done",
);
throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end");
}
#[test]
fn resuming_a_running_generator_is_a_type_error() {
truth(
"var it; function* g() { try { it.next(); } catch (e) { yield e instanceof TypeError; } } it = g(); \
it.next().value === true",
);
truth("var it; function* g() { it.next(); } it = g(); var e; try { it.next(); } catch (x) { e = x; } e instanceof TypeError && it.next().done");
throws("var g = function* () {}; g.prototype.next.call({});", "TypeError");
throws("(function* () {}).prototype.next.call(1);", "TypeError");
}
#[test]
fn yield_star_delegates_next_throw_and_return() {
truth(
"function* g() { yield* [1, 2]; yield* 'ab'; } var r = []; var it = g(), s; while (!(s = it.next()).done) r.push(s.value); r.join() === '1,2,a,b'",
);
truth(
"function* inner() { yield 1; return 'r'; } function* outer() { var v = yield* inner(); yield v; } var it = outer(); it.next().value === 1 && it.next().value === 'r'",
);
// The values `next` sends go to the delegate.
truth(
"function* inner() { var x = yield 1; yield x * 2; } function* outer() { yield* inner(); } var it = outer(); it.next(); it.next(21).value === 42",
);
truth(
"var log = []; function* inner() { try { yield 1; } finally { log.push('inner'); } } function* outer() { try { yield* inner(); } finally { log.push('outer'); } } \
var it = outer(); it.next(); var r = it.return(7); r.value === 7 && r.done && log.join() === 'inner,outer'",
);
truth(
"function* inner() { try { yield 1; } catch (e) { yield 'in ' + e; } } function* outer() { yield* inner(); } var it = outer(); it.next(); it.throw('t').value === 'in t'",
);
// The delegate's own results are passed on as they are.
truth(
"var r = { done: false, value: 1, extra: 2 }; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return r; } }; }; function* g() { yield* o; } g().next() === r",
);
// A delegate without `throw` is closed, and the generator gets a TypeError.
truth(
"var closed = false; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return { done: false }; }, return: function () { closed = true; return {}; } }; }; \
function* g() { yield* o; } var it = g(); it.next(); var e; try { it.throw(1); } catch (x) { e = x; } e instanceof TypeError && closed",
);
throws("function* g() { yield* 5; } g().next();", "TypeError");
throws(
"var o = {}; o[Symbol.iterator] = function () { return { next: function () { return 1; } }; }; function* g() { yield* o; } g().next();",
"TypeError",
);
}
#[test]
fn generator_methods_and_the_generator_objects() {
truth("var o = { *g(a) { yield this === o && a; } }; o.g(5).next().value === 5");
truth("var o = { *'s'() { yield 1; }, *2() { yield 2; } }; o.s().next().value + o[2]().next().value === 3");
throws("function* g() {} new g();", "TypeError");
throws("var o = { *m() {} }; new o.m();", "TypeError");
// A generator method has a `prototype` that its generator objects inherit from, unlike other
// methods, and takes a computed name and the method's `name`.
truth("var o = { *m() {} }; var it = o.m(); Object.getPrototypeOf(it) === o.m.prototype && !o.m.prototype.hasOwnProperty('constructor')");
truth("var k = 'c'; var o = { *[k + 'd']() { yield 4; } }; o.cd().next().value === 4 && o.cd.name === 'cd'");
truth("function* g() {} var GP = Object.getPrototypeOf(g); GP === Object.getPrototypeOf(function* () {}) && GP !== Function.prototype");
truth("function* g() {} Object.getPrototypeOf(g.prototype) === Object.getPrototypeOf(g).prototype && !g.prototype.hasOwnProperty('constructor')");
truth("function* g() {} var it = g(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Generator]'");
truth("function* g() {} Object.prototype.toString.call(g) === '[object GeneratorFunction]' && g instanceof Function && typeof g === 'function'");
// %GeneratorFunction.prototype% is an ordinary object, not a function (section 25.2.3).
truth("var GP = Object.getPrototypeOf(function* () {}); typeof GP === 'object' && Object.getPrototypeOf(GP) === Function.prototype");
throws("Object.getPrototypeOf(function* () {})();", "TypeError");
truth(
"var GF = Object.getPrototypeOf(function* () {}).constructor; var f = GF('a', 'yield a; yield a * 2;'); var it = f(3); it.next().value + it.next().value === 9",
);
truth(
"var GF = Object.getPrototypeOf(function* () {}).constructor; Object.getPrototypeOf(GF) === Function && GF.prototype === Object.getPrototypeOf(function* () {})",
);
truth(
"var GF = Object.getPrototypeOf(function* () {}).constructor; typeof this.GeneratorFunction === 'undefined' && new GF('yield 1')().next().value === 1",
);
truth("function* g() { yield 1 } String(g) === 'function* g() { yield 1 }'");
// A generator function's own `prototype` is used when it is an object.
truth("function* g() {} var p = { mark: 1 }; g.prototype = p; Object.getPrototypeOf(g()) === p");
truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype");
}
#[test]
fn a_bound_generator_function_inherits_from_the_targets_prototype() {
truth("function* g() {} var b = g.bind(null); Object.getPrototypeOf(b) === Object.getPrototypeOf(g) && b.constructor !== Function");
truth("function* g(a) { yield a; } g.bind(null, 3)().next().value === 3");
truth("function f() {} Object.getPrototypeOf(f.bind(null)) === Function.prototype");
}
#[test]
fn yield_is_an_identifier_outside_generators_in_sloppy_code() {
truth("var yield = 1; yield + 1 === 2");
truth("function f(yield) { return yield; } f(3) === 3");
truth("function* g() { function f() { var yield = 4; return yield; } yield f(); } g().next().value === 4");
truth("function* g() { var o = { yield: 5 }; yield o.yield; } g().next().value === 5");
truth("function* yield() { yield 6; } yield().next().value === 6");
syntax("'use strict'; var yield = 1;");
}
#[test]
fn bad_generators_are_syntax_errors() {
for src in [
"function* g() { var yield; }",
"function* g(yield) {}",
"function* g(a = yield) {}",
"function* g() { function* h(a = yield 1) {} }",
"var f = function* yield() {};",
"function* g() { (yield) => 1; }",
"function* g() { yield = 1; }",
"function* g() { yi\\u0065ld 1; }",
"function* g() { yield\n* 1; }",
"function* g() { yield: 1; }",
"if (true) function* g() {}",
"L: function* g() {}",
"{ function* g() {} function* g() {} }",
"function* g() { yield* ; }",
"var o = { *m(a, a) {} };",
"function* g() { (a = yield) => 1; }",
] {
syntax(src);
}
// A `yield` in the body of a function in a generator's parameters belongs to that function.
truth("function* g(a = function* () { yield 1; }) { yield* a(); } g().next().value === 1");
truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3");
}
#[test]
fn realms_without_es2015_have_no_generators() {
let es5 = Options::default();
let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() };
for options in [es5, extendscript] {
for src in ["function* g() {}", "var g = function* () {};", "var o = { *m() {} };"] {
syntax_with(src, options.clone());
}
let mut realm = Realm::with_options(options, Limits::default());
assert_eq!(realm.run("function f() { var yield = 2; return yield; } f()"), Ok(JsValue::Number(2.0)));
// Reading the syntax later does not add the built-ins, so a call is a TypeError.
realm.set_es2015(true);
match realm.run("function* g() { yield 1; } g();") {
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{message}"),
other => panic!("{other:?}"),
}
}
}
#[test]
fn a_suspended_generator_keeps_its_frame_across_a_collection() {
let mut realm = es2015(Limits::default());
let setup = "function* g() { var local = { v: 'left' }; var r = [{ w: 'held' }, yield 1]; yield local.v + r[0].w + r[1]; } \
var it = g(); it.next(); it.next('!').value";
assert_eq!(realm.run(setup), Ok(JsValue::String("leftheld!".into())));
// The operands on the stack at the `yield` (the array being built) survive a collection.
assert_eq!(realm.run("var it3 = g(); it3.next(); 'ok'"), Ok(JsValue::String("ok".into())));
realm.collect_garbage();
assert_eq!(realm.run("it3.next('#').value"), Ok(JsValue::String("leftheld#".into())));
}
#[test]
fn a_frame_taken_out_of_its_generator_leaves_the_heap_total() {
let mut realm = es2015(Limits::default());
// At the `yield`, the 500 arguments before it are operands in the saved frame.
let args = vec!["0"; 500].join(", ");
let setup = format!("function f() {{}} function* g() {{ while (true) f({args}, yield 1); }} var it = g(); it.next(); 0");
assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0)));
let mut gaps = Vec::new();
for resumes in [10, 210] {
realm.collect_garbage();
assert_eq!(realm.run(&format!("for (var i = 0; i < {resumes}; i++) it.next(); 0")), Ok(JsValue::Number(0.0)));
let counted = realm.interp().heap.bytes;
gaps.push(counted.saturating_sub(realm.collect_garbage()));
}
// 200 more resumptions leave far less than one saved frame's worth each.
assert!(gaps[1] < gaps[0] + 200 * 1024, "{gaps:?}");
}
#[test]
fn an_unreachable_suspended_generator_is_freed() {
let mut realm = es2015(Limits::default());
let setup = "function* g() { var big = []; for (var i = 0; i < 20000; i++) big.push({ i: i }); yield big.length; } var it = g(); it.next().value";
assert_eq!(realm.run(setup), Ok(JsValue::Number(20000.0)));
let held = realm.collect_garbage();
assert_eq!(realm.run("it = null; 0"), Ok(JsValue::Number(0.0)));
let freed = realm.collect_garbage();
assert!(freed + 1_000_000 < held, "held {held}, after {freed}");
}
/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`.
fn smallest_heap_limit(setup: &str, script: &str) -> usize {
let fits = |limit: usize| {
let mut realm = es2015(Limits::default());
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
realm.collect_garbage();
realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() });
realm.run(script).is_ok()
};
let (mut low, mut high) = (0, 64 << 20);
assert!(fits(high), "{script}");
while high - low > 256 {
let mid = low + (high - low) / 2;
if fits(mid) {
high = mid;
} else {
low = mid;
}
}
high
}
#[test]
fn a_yield_reserves_only_what_its_frame_keeps() {
// At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks
// that a throw entered. Their entries stay with those frames, so the yield needs no more room
// than the one in `before`, which comes before those frames are pushed.
let setup = "function* g() { yield 1; } var it = g(); 0";
let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0";
let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0";
let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before));
assert!(inside < before + 4096, "inside {inside}, before {before}");
}
#[test]
fn generators_stay_within_the_limits() {
let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() });
match realm.run("function* g() { while (true) yield 1; } var it = g(); while (true) it.next();") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
}
// Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next`
// take at least 1,000 more than the same calls of a native method that takes none.
let mut realm = es2015(Limits::default());
let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0";
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
let mut used = Vec::new();
for callee in ["control", "it"] {
assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0)));
used.push(Limits::default().fuel - realm.fuel_left());
}
assert!(used[1] >= used[0] + 1000, "{used:?}");
// A deep `yield*` chain stops at the frame limit, and the realm can run again.
let mut realm = es2015(Limits { frames: 200, ..Limits::default() });
match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Frames), .. }) => {}
other => panic!("{other:?}"),
}
assert_eq!(realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(20).next().value"), Ok(JsValue::Number(1.0)));
// A generator whose body was running when a limit ended the run cannot be resumed.
let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() });
match realm.run("var it = (function* () { while (true) {} })(); it.next();") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
}
assert_eq!(realm.run("var r = it.next(); r.done && r.value === undefined"), Ok(JsValue::Bool(true)));
}
+29 -1
View File
@@ -181,6 +181,8 @@ pub(crate) enum NativeKind {
Apply,
/// The global `eval`: a call to it by that name is a direct eval.
Eval,
/// `%GeneratorPrototype%`'s `next`, `return` or `throw`.
Resume(crate::generator::ResumeMode),
}
/// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section
@@ -245,6 +247,8 @@ pub(crate) enum Class {
/// The Iterator Record of a `for-of` loop, an array pattern or a spread in progress, on the
/// operand stack only.
IterRecord(Box<crate::iteration::IterRecord>),
/// A generator object and its state (ECMA-262 11th edition, section 25.4).
Generator(Box<crate::generator::GenState>),
ForIn(Box<ForIn>),
/// The `Math` object (section 15.8).
Math,
@@ -343,7 +347,13 @@ impl Class {
Class::Promise(_) => "Promise",
Class::Math => "Math",
Class::Json => "JSON",
Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object",
Class::Ordinary
| Class::ForIn(_)
| Class::Host(_)
| Class::Symbol(_)
| Class::Iterator(_)
| Class::IterRecord(_)
| Class::Generator(_) => "Object",
Class::Array { .. } => "Array",
Class::Function(_) => "Function",
Class::Error(_) => "Error",
@@ -773,6 +783,24 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)),
crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)),
},
Class::Generator(state) => {
if let Some(saved) = state.saved() {
work.push(saved.env.0);
work.push(saved.var_env.0);
work.extend(saved.callee.iter().map(|o| o.0));
work.extend(saved.marks.iter().map(|&(id, _, _)| id.0));
mark_value(&saved.this, work, strings);
mark_value(&saved.completion, work, strings);
for v in &saved.stack {
mark_value(v, work, strings);
}
mark_code(&saved.code, strings);
for ((code, _), _) in &saved.sites {
mark_code(code, strings);
}
extra = crate::generator::saved_bytes(saved);
}
}
Class::Xml(node) => {
work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0));
strings.add(&node.value);
+46 -17
View File
@@ -30,6 +30,7 @@ pub enum Data {
}
/// How much one crossing may carry.
/// Host receivers, their handles and explicit arguments share these limits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DataLimits {
/// How deeply arrays and objects may nest.
@@ -265,9 +266,7 @@ impl Interp {
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
}
let shape = match &self.object(id)?.class {
Class::Host(_) if r.hosted => {
return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into()));
}
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")),
Class::Array { length, .. } => Shape::Array(*length),
Class::Ordinary => {
@@ -299,6 +298,14 @@ impl Interp {
out
}
fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult<Data> {
let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) };
self.charge_entries(r, len.saturating_add(2))?;
let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8);
self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?;
self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into()))
}
fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult<Data> {
self.charge_entries(r, length as usize)?;
let mut items = Vec::with_capacity(length as usize);
@@ -407,16 +414,8 @@ impl Interp {
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, this: &Value, args: &[Value], how: &ArgRead) -> JsResult<Value> {
let data = match how {
ArgRead::Site => site_data(self.call_site()),
ArgRead::Hosted => {
let this = match this {
Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined),
_ => Data::Undefined,
};
let mut data = vec![this];
data.extend(self.read_args(name, args, how)?);
data
}
_ => self.read_args(name, args, how)?,
ArgRead::Hosted => self.read_args(name, Some(this), args, how)?,
_ => self.read_args(name, None, args, how)?,
};
// Only the script's own code, in a run that can pause, can wait for a result, and a host
// class's constructor called with `new` cannot.
@@ -463,7 +462,7 @@ impl Interp {
name: &Rc<str>,
args: &[Value],
) -> JsResult<Value> {
let data = self.read_args(name, args, &ArgRead::Data)?;
let data = self.read_args(name, None, args, &ArgRead::Data)?;
let source = match f(data) {
Ok(Data::String(source)) => source,
Ok(d) => return self.write_data(d, 0, false),
@@ -505,8 +504,8 @@ impl Interp {
r
}
/// The arguments of host function `name` as [`Data`], read as `how` says.
fn read_args(&mut self, name: &Rc<str>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
let mut reading = Reading {
limits: self.data_limits,
bytes: 0,
@@ -520,7 +519,14 @@ impl Interp {
ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args),
_ => args,
};
let mut data = Vec::with_capacity(args.len());
let mut data = Vec::with_capacity(args.len() + 1);
if let Some(this) = this {
let this = match this {
Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?,
_ => Data::Undefined,
};
data.push(this);
}
// A conversion can run the script's own `toString`, which may collect garbage.
let mark = self.temp_roots.len();
if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) {
@@ -552,6 +558,29 @@ impl Interp {
Ok(data)
}
pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult<Vec<Data>> {
let mut reading = Reading {
limits: self.data_limits,
bytes: 0,
entries: 0,
ancestors: Vec::new(),
path: Vec::new(),
function: Rc::from("host indexer"),
hosted: true,
};
let receiver = self.read_host_ref(id, &mut reading)?;
match &key {
Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?,
Data::Number(_) => {}
_ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())),
}
let mut args = vec![receiver, key];
if probe {
args.push(Data::Bool(true));
}
Ok(args)
}
/// What host error `e` throws, or the limit it ends the run with. A function that waits
/// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal
/// error.
+9 -4
View File
@@ -172,6 +172,12 @@ impl Interp {
Ok(Some(host_ref(&name, &h.handle)))
}
pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult<Option<(usize, usize)>> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?;
Ok(Some((name, h.handle.len())))
}
/// The object of a host class that `d`, which a host function gave, stands for.
pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult<Value> {
let Some((name, handle)) = host_ref_parts(d) else {
@@ -220,11 +226,10 @@ impl Interp {
/// gets `true` as a third argument.
pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult<Value> {
self.use_fuel()?;
let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) };
let mut args = vec![this, k];
if probe {
args.push(Data::Bool(true));
if self.host_ref_size(id)?.is_none() {
return Ok(Value::Undefined);
}
let args = self.read_index_args(id, k, probe)?;
match f(args) {
Ok(d) => self.write_hosted(d),
Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())),
+51
View File
@@ -11,6 +11,57 @@ fn realm(fuel: u64) -> Realm {
r
}
#[test]
fn non_finite_indexer_keys_reach_the_host_unchanged() {
let mut r = realm(1_000_000);
let index: HostFunction = Rc::new(|args| {
assert!(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()), "{args:?}");
Ok(Data::Bool(true))
});
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None };
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap();
let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')";
assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into()));
}
#[test]
fn host_receivers_obey_limits_lowered_after_the_object_was_created() {
for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] {
for expression in ["it[0]", "0 in it", "it.method()", "it.take(it)"] {
let mut r = realm(1_000_000);
let calls = Rc::new(Cell::new(0));
let called = calls.clone();
let function: HostFunction = Rc::new(move |_| {
called.set(called.get() + 1);
Ok(Data::Undefined)
});
let class = HostClass {
name: "Indexed".into(),
parent: None,
members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))],
index: Some(function),
construct: None,
};
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0, 2.0, 3.0]))]).unwrap();
r.set_data_limits(limits);
let source = format!("var result = 'called'; try {{ {expression}; }} catch (e) {{ result = e.name; }} result");
assert_eq!(r.run(&source).unwrap(), JsValue::String("RangeError".into()), "{expression}: {limits:?}");
assert_eq!(calls.get(), 0, "{expression}");
}
}
}
#[test]
fn index_keys_share_the_receivers_data_budget() {
let mut r = realm(1_000_000);
let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None };
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap();
r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 });
assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true));
let source = "var result = 'called'; try { it[new Array(71).join('x')]; } catch (e) { result = e.name; } result";
assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into()));
}
/// A realm with `host.take(value)`, which records what it was given and returns it.
fn with_take(r: &mut Realm) -> Rc<RefCell<Vec<Data>>> {
let seen: Rc<RefCell<Vec<Data>>> = Rc::default();
+68 -15
View File
@@ -4,7 +4,9 @@
//! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call
//! only where the language needs a function's result in the middle of an operation (a getter or
//! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are
//! counted against [`crate::Limits::reentry`].
//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own,
//! which `yield` moves into the generator object, operands included, and a call to its `next`,
//! `return` or `throw` pushes again ([`crate::generator`]).
//!
//! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and,
//! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap
@@ -198,22 +200,24 @@ pub(crate) struct Frame {
pub(crate) code: Rc<Code>,
pub(crate) pc: usize,
/// Where this frame's operands start on the operand stack.
base: usize,
pub(crate) base: usize,
pub(crate) env: EnvId,
pub(crate) var_env: EnvId,
/// `with` and catch environments entered and not yet left.
env_depth: u32,
this: Value,
callee: Option<ObjId>,
pub(crate) env_depth: u32,
pub(crate) this: Value,
pub(crate) callee: Option<ObjId>,
/// The object `new` made, returned unless the function returns an object.
construct: Option<ObjId>,
completion: Value,
pub(crate) construct: Option<ObjId>,
pub(crate) completion: Value,
/// Returning from this frame returns from the Rust call that pushed it.
boundary: bool,
pub(crate) boundary: bool,
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
pub(crate) generator: Option<ObjId>,
}
/// Where the exception being thrown was raised: the code and the instruction.
type ThrowSite = (Rc<Code>, usize);
pub(crate) type ThrowSite = (Rc<Code>, usize);
/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time.
pub(crate) type CodeObserver = Rc<dyn Fn(&[u16])>;
@@ -533,7 +537,7 @@ fn arguments_bytes(args: usize) -> usize {
}
/// A call to a function written in JavaScript, ready to enter.
struct Entry {
pub(crate) struct Entry {
callee: ObjId,
code: Rc<Code>,
env: EnvId,
@@ -542,9 +546,11 @@ struct Entry {
}
/// What a call resolved to.
enum Prepared {
pub(crate) enum Prepared {
Closure(Entry),
Done(Value),
/// A generator's `next`, `return` or `throw` that goes on with its body.
Resume(Box<crate::generator::Resumed>),
}
/// A variable found in the environment chain.
@@ -872,7 +878,7 @@ impl Interp {
/// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of
/// `finally` blocks that were left. The slots rise along the list, so only its end is looked at.
fn drop_left_finally_sites(&mut self, len: usize) {
pub(crate) fn drop_left_finally_sites(&mut self, len: usize) {
while let Some(&(_, slot)) = self.finally_sites.last() {
#[cfg(test)]
SITE_CHECKS.with(|c| c.set(c.get() + 1));
@@ -900,7 +906,7 @@ impl Interp {
for f in &self.frames {
roots.values.push(&f.this);
roots.values.push(&f.completion);
roots.objects.extend(f.callee.iter().chain(f.construct.iter()));
roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.generator.iter()));
roots.envs.push(f.env);
roots.envs.push(f.var_env);
roots.codes.push(&f.code);
@@ -1001,6 +1007,8 @@ impl Interp {
let v = self.frame()?.completion.clone();
self.return_value(v)
}
Op::GeneratorStart => self.op_generator_start(),
Op::Yield(raw) => self.op_yield(raw),
_ => self.exec(op).map(|()| None),
}
}
@@ -1055,6 +1063,7 @@ impl Interp {
}
let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if frame.boundary {
self.passing = v.clone();
return Err(Abrupt::Throw(v));
@@ -1071,6 +1080,7 @@ impl Interp {
fn abort_to_boundary(&mut self) {
while let Some(frame) = self.frames.pop() {
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if frame.boundary {
break;
}
@@ -1078,8 +1088,15 @@ impl Interp {
}
fn return_value(&mut self, v: Value) -> JsResult<Option<Value>> {
// A generator's body that returns ends it, and its caller gets `{ value, done: true }`,
// made while the frame is still there to fail in.
let v = match self.frames.last().and_then(|f| f.generator) {
Some(_) => crate::builtins::iterator::iter_result(self, v, true)?,
None => v,
};
let Some(frame) = self.frames.pop() else { return internal("return without a frame") };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
self.drop_left_finally_sites(frame.base);
let v = match frame.construct {
@@ -1260,7 +1277,12 @@ impl Interp {
Op::PatternGet(n) => self.op_pattern_get(n),
Op::InitIndex => self.op_init_index(),
Op::InitAccessorIndex(getter) => self.op_init_accessor_index(getter),
Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"),
Op::Resume(t) => self.op_resume(t),
Op::DelegateIterator => self.op_delegate_iterator(),
Op::DelegateCall(t) => self.op_delegate_call(t),
Op::DelegateResult(t) => self.op_delegate_result(t),
Op::DelegateDone(t) => self.op_delegate_done(t),
Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"),
}
}
@@ -2413,7 +2435,8 @@ impl Interp {
Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }),
None => env,
};
let proto = self.intrinsics.function_proto;
let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten();
let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto);
let length = code.length;
let strict = code.strict;
let arrow = code.arrow;
@@ -2427,6 +2450,18 @@ impl Interp {
if let Some(name) = own_name {
self.define(f, key("name"), Prop::Data { value: Value::String(Str::from_rc(name)), flags: CONFIGURABLE })?;
}
// A generator function's `prototype`, a generator method's included, inherits from
// %GeneratorPrototype% and has no `constructor` (ECMA-262 11th edition, section 14.4.13).
// A generator function has no own `caller` or `arguments`, strict or not
// (section 16.2).
if let (false, Some((_, generator_proto))) = (arrow, generator) {
let p = self.heap.alloc_object(Object::new(Class::Ordinary, Some(generator_proto)));
self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?;
if let Some(name) = self_name {
self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?;
}
return Ok(f);
}
// An arrow function, a method and an accessor of ECMAScript 2015 code have no
// `prototype` and cannot be constructed (sections 14.2.16 and 14.3.8).
if arrow || method {
@@ -2825,6 +2860,11 @@ impl Interp {
let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?;
return Ok(Prepared::Closure(Entry { callee, code, env, this, args }));
}
Func::Native { kind: NativeKind::Resume(mode), .. } => {
self.use_fuel()?;
let sent = args.into_iter().next().unwrap_or(Value::Undefined);
return self.prepare_resume(this, mode, sent);
}
Func::Native { kind: NativeKind::Call, .. } => {
self.use_fuel()?;
f = this;
@@ -2950,6 +2990,10 @@ impl Interp {
self.stack.truncate(start);
self.enter_function(entry, None, false)
}
Prepared::Resume(r) => {
self.stack.truncate(start);
self.enter_resumed(*r, false)
}
}
}
@@ -2970,6 +3014,7 @@ impl Interp {
}
match self.func_of(&f) {
Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")),
Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")),
Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")),
Some(Func::Closure { code, env }) => {
let Some(callee) = f.as_object() else { return internal("callee is not an object") };
@@ -3072,6 +3117,7 @@ impl Interp {
construct,
completion: Value::Undefined,
boundary,
generator: None,
});
Ok(())
}
@@ -3306,6 +3352,7 @@ impl Interp {
match prepared? {
Prepared::Done(v) => Ok(Some(v)),
Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None),
Prepared::Resume(resumed) => self.enter_resumed(*resumed, true).map(|()| None),
}
}
@@ -3317,6 +3364,11 @@ impl Interp {
self.enter_function(entry, None, true)?;
self.execute()
}
Prepared::Resume(r) => {
self.stack.truncate(saved);
self.enter_resumed(*r, true)?;
self.execute()
}
}
}
@@ -3566,6 +3618,7 @@ impl Interp {
construct: None,
completion: Value::Undefined,
boundary,
generator: None,
});
Ok(())
}
+1
View File
@@ -1015,6 +1015,7 @@ fn code(ops: Vec<Op>) -> Code {
es2015: false,
own_name: None,
method: false,
generator: false,
}
}
+13 -1
View File
@@ -63,7 +63,16 @@
//! closes its iterator. In a realm made without the option and later given it with
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects
//! by index and strings by code point, and throw a `TypeError` for other values.
//! Object rest properties (`{ a, ...rest }`), classes, generators and modules stay syntax errors.
//! Object rest properties (`{ a, ...rest }`), classes and modules stay syntax errors.
//!
//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition,
//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in
//! object literals, `yield` and `yield*`, which passes `next`, `throw` and `return` on to the
//! iterator it delegates to, and generator objects with `next`, `return` and `throw` from
//! `%GeneratorPrototype%`, reached through `%GeneratorFunction%`. Outside a generator function's
//! body and parameters, `yield` stays an identifier in sloppy code. A generator's suspended frame
//! lives in the heap, each resumption takes fuel and counts against the frame limit, and resuming a
//! generator while its body runs is a `TypeError`.
//!
//! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4,
//! <https://262.ecma-international.org/11.0/>): `Symbol.for` and `Symbol.keyFor` over a registry
@@ -96,6 +105,7 @@ mod compiler;
mod date_builtins;
mod error;
mod file_classes;
mod generator;
mod heap;
mod host;
mod host_classes;
@@ -276,6 +286,8 @@ mod es2020_tests;
#[cfg(test)]
mod extension_tests;
#[cfg(test)]
mod generator_tests;
#[cfg(test)]
mod host_tests;
#[cfg(test)]
mod interp_tests;
+120 -17
View File
@@ -37,6 +37,9 @@ struct Context {
breakables: u32,
/// The current function body's directive prologue has a `"use strict"` directive.
use_strict: bool,
/// The code is a generator function's body or parameters: `yield` starts a yield expression
/// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4).
generator: bool,
}
/// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations
@@ -115,6 +118,9 @@ pub(crate) struct Parser<'s> {
/// section B.3.1). Each is also in `cover_inits`, so it is a `SyntaxError` unless the literal
/// is read as a destructuring pattern.
proto_twice: HashSet<u32>,
/// Where each yield expression read so far starts, in the order read, so the parameters of a
/// generator function and an arrow function's head can be checked for one.
yields: Vec<u32>,
}
impl<'s> Parser<'s> {
@@ -143,6 +149,7 @@ impl<'s> Parser<'s> {
cover_ok: false,
rest_commas: HashSet::new(),
proto_twice: HashSet::new(),
yields: Vec::new(),
};
parser.tok = parser.next_significant()?;
Ok(parser)
@@ -284,9 +291,18 @@ impl<'s> Parser<'s> {
if self.ctx.strict && strict_reserved(name) {
return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode")));
}
if self.ctx.generator && name == "yield" {
return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function"));
}
Ok(())
}
/// A yield expression starts at `offset` or later, before `end`.
fn yield_between(&self, offset: u32, end: u32) -> bool {
let i = self.yields.partition_point(|&y| y < offset);
self.yields.get(i).is_some_and(|&y| y < end)
}
/// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does,
/// and in strict code neither `eval` nor `arguments`.
fn binding_identifier(&mut self) -> Result<Name> {
@@ -359,7 +375,7 @@ impl<'s> Parser<'s> {
/// Declares a function declaration that stands in a statement list: var-scoped in a function
/// body or the script, lexical in a block.
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) };
let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) };
match self.scopes.last_mut() {
Some(scope) if scope.function => {
if scope.lexical.contains_key(&name.name) {
@@ -368,7 +384,8 @@ impl<'s> Parser<'s> {
scope.vars.insert(name.name);
Ok(())
}
Some(_) => self.declare_lexical(&name, true),
// Only plain function declarations may repeat in a block (Annex B.3.3.4).
Some(_) => self.declare_lexical(&name, !generator),
None => Ok(()),
}
}
@@ -532,6 +549,9 @@ impl<'s> Parser<'s> {
};
return Err(self.error_at_token(&self.tok, message));
}
if self.es2015 && self.peek().is_some_and(|t| t.is_punct(Punct::Star)) {
return Err(self.error_at_token(&self.tok, "a generator declaration cannot stand here; put it in a block"));
}
self.parse_function_declaration()
}
TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list),
@@ -1039,8 +1059,9 @@ impl<'s> Parser<'s> {
fn parse_function_declaration(&mut self) -> Result<StmtId> {
let start = self.expect_keyword(Keyword::Function)?.span;
let generator = self.es2015 && self.eat(Punct::Star)?;
let name = self.function_name()?;
let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?;
let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start)))
}
@@ -1056,15 +1077,28 @@ impl<'s> Parser<'s> {
Ok((Name { name, span: token.span }, token))
}
/// The parameters and body of a function, from `(`.
fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result<crate::ast::FunctionId> {
/// The parameters and body of a function, from `(`; with `generator`, a generator function's.
fn parse_function_rest(
&mut self,
kind: FunctionKind,
name: Option<(Name, Token)>,
start: Span,
generator: bool,
) -> Result<crate::ast::FunctionId> {
self.enter()?;
let result = self.function_rest(kind, name, start);
// The parameters are read with the function's own `yield` rule, not the enclosing code's.
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
let yields = self.yields.len();
let result = self.function_rest(kind, name, start, generator);
// The `yield` expressions of this function are not in the code around it.
self.yields.truncate(yields);
self.ctx.generator = outer_generator;
self.leave();
result
}
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result<crate::ast::FunctionId> {
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result<crate::ast::FunctionId> {
let params_start = self.tok.span.start;
self.expect(Punct::LParen)?;
let mut params: Vec<Binding> = Vec::new();
let mut defaults: Vec<Option<ExprId>> = Vec::new();
@@ -1097,6 +1131,10 @@ impl<'s> Parser<'s> {
}
}
let close = self.expect(Punct::RParen)?;
if generator && self.yield_between(params_start, close.span.start) {
let at = self.yields.get(self.yields.partition_point(|&y| y < params_start)).copied().unwrap_or(params_start);
return Err(self.error_at_offset(at, "a yield expression cannot stand in a generator function's parameters"));
}
match kind {
FunctionKind::Getter if !params.is_empty() || rest.is_some() => {
return Err(self.error_at_token(&close, "a getter must not have parameters"));
@@ -1112,7 +1150,7 @@ impl<'s> Parser<'s> {
self.expect(Punct::LBrace)?;
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
let outer_strict = self.ctx.strict;
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() };
let outer = std::mem::replace(&mut self.ctx, inner);
self.push_scope(true, names);
let body = self.parse_body(true);
@@ -1121,7 +1159,7 @@ impl<'s> Parser<'s> {
self.ctx = outer;
let body = body?;
self.expect(Punct::RBrace)?;
let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) };
let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start) };
self.check_params(&function, use_strict)?;
Ok(self.ast.push_function(function))
}
@@ -1153,7 +1191,8 @@ impl<'s> Parser<'s> {
self.expect(Punct::RBrace)?;
}
let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults };
let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) };
let function =
Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, generator: false, span: self.span_from(start) };
self.check_params(&function, use_strict)?;
let id = self.ast.push_function(function);
Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start)))
@@ -1271,10 +1310,15 @@ impl<'s> Parser<'s> {
fn assignment(&mut self, no_in: bool) -> Result<ExprId> {
let mut targets: Vec<(ExprId, AssignOp)> = Vec::new();
loop {
let mut expr = self.parse_conditional(no_in)?;
if self.es2015 && self.at(Punct::Arrow) {
expr = self.arrow_from(expr, no_in)?;
}
let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped {
self.parse_yield(no_in)?
} else {
let mut expr = self.parse_conditional(no_in)?;
if self.es2015 && self.at(Punct::Arrow) {
expr = self.arrow_from(expr, no_in)?;
}
expr
};
let Some(op) = assign_op(&self.tok) else {
let mut value = expr;
while let Some((target, op)) = targets.pop() {
@@ -1293,10 +1337,28 @@ impl<'s> Parser<'s> {
}
}
/// A yield expression, from `yield` (ECMA-262 2015 section 14.4): its operand is left out when
/// a line break follows `yield` or the next token cannot start an expression, and `yield*`
/// must have one.
fn parse_yield(&mut self, no_in: bool) -> Result<ExprId> {
let start = self.bump()?.span;
self.yields.push(start.start);
let delegate = !self.tok.newline_before && self.at(Punct::Star);
if delegate {
self.bump()?;
}
let arg =
if delegate || (!self.tok.newline_before && starts_expression(&self.tok, self.e4x)) { Some(self.parse_assignment(no_in)?) } else { None };
Ok(self.ast.push_expr(Expr::Yield { arg, delegate }, self.span_from(start)))
}
/// The arrow function whose head is `expr`, read before the current `=>`: a name standing
/// alone, or parameters in parentheses.
fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result<ExprId> {
let start = self.ast.expr_span(expr);
if self.yield_between(start.start, start.end) {
return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters"));
}
let params = match self.ast.expr(expr) {
Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None),
Some(Expr::Paren(_)) => self.arrow_params(expr)?,
@@ -1706,8 +1768,13 @@ impl<'s> Parser<'s> {
fn parse_function_expression(&mut self) -> Result<ExprId> {
let start = self.expect_keyword(Keyword::Function)?.span;
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None };
let id = self.parse_function_rest(FunctionKind::Expression, name, start)?;
let generator = self.es2015 && self.eat(Punct::Star)?;
// A generator expression's name is read with its own `yield` rule.
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) };
self.ctx.generator = outer_generator;
let name = name?;
let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?;
Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start)))
}
@@ -1790,7 +1857,7 @@ impl<'s> Parser<'s> {
let word = self.bump()?;
if property_key(&self.tok).is_some() {
let (key, _) = self.parse_property_key()?;
let function = self.parse_function_rest(kind, None, start)?;
let function = self.parse_function_rest(kind, None, start, false)?;
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
return Ok(Property { key, value, span: self.span_from(start) });
}
@@ -1829,6 +1896,42 @@ fn property_key(token: &Token) -> Option<PropertyKey> {
}
}
/// The token can start an expression, so a `yield` before it on the same line takes an operand.
fn starts_expression(token: &Token, e4x: bool) -> bool {
match &token.kind {
TokenKind::Ident(_) | TokenKind::Number(_) | TokenKind::String(_) | TokenKind::Template { .. } | TokenKind::RegExp { .. } => true,
TokenKind::Keyword(k) => matches!(
k,
Keyword::This
| Keyword::Null
| Keyword::True
| Keyword::False
| Keyword::Function
| Keyword::New
| Keyword::Delete
| Keyword::Void
| Keyword::Typeof
),
TokenKind::Punct(p) => {
matches!(
p,
Punct::LParen
| Punct::LBracket
| Punct::LBrace
| Punct::Plus
| Punct::Minus
| Punct::Bang
| Punct::Tilde
| Punct::PlusPlus
| Punct::MinusMinus
| Punct::Slash
| Punct::SlashEq
) || (e4x && matches!(p, Punct::Lt | Punct::At))
}
_ => false,
}
}
fn is_eval_or_arguments(name: &str) -> bool {
name == "eval" || name == "arguments"
}
+8 -2
View File
@@ -146,6 +146,12 @@ impl Parser<'_> {
/// initializer (`a = 1`), which only a pattern may hold.
pub(super) fn parse_property_es2015(&mut self) -> Result<Property> {
let start = self.tok.span;
// `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4).
if self.eat(Punct::Star)? {
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
let function = self.parse_function_rest(FunctionKind::Method, None, start, true)?;
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
}
// `get` and `set` start an accessor only when written without escapes and followed by a
// property name.
let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) {
@@ -158,7 +164,7 @@ impl Parser<'_> {
{
self.bump()?;
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
let function = self.parse_function_rest(kind, None, start)?;
let function = self.parse_function_rest(kind, None, start, false)?;
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
return Ok(Property { key, value, span: self.span_from(start) });
}
@@ -192,7 +198,7 @@ impl Parser<'_> {
/// the value may still turn out to be a pattern.
fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result<Property> {
if self.at(Punct::LParen) {
let function = self.parse_function_rest(FunctionKind::Method, None, start)?;
let function = self.parse_function_rest(FunctionKind::Method, None, start, false)?;
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
}
self.expect(Punct::Colon)?;
+16
View File
@@ -57,6 +57,22 @@ fn promise_prototype_cannot_be_replaced() {
assert_eq!(string(src), "true,true,true");
}
#[test]
fn promise_prototype_has_a_configurable_string_tag() {
assert_eq!(
string(
"var d = Object.getOwnPropertyDescriptor(Promise.prototype, Symbol.toStringTag); \
[Object.prototype.toString.call(Promise.prototype), \
Object.prototype.toString.call(Promise.resolve()), \
d.value, d.writable, d.enumerable, d.configurable].join()"
),
"[object Promise],[object Promise],Promise,false,false,true"
);
let mut r = Realm::new();
r.add_es2015();
assert_eq!(r.run("Object.prototype.toString.call(Promise.resolve())").unwrap(), JsValue::String("[object Promise]".into()));
}
#[test]
fn then_callbacks_run_after_the_scripts_code_in_order() {
let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\
+3
View File
@@ -353,6 +353,9 @@ impl Realm {
interp.finally_marks.clear();
interp.finally_sites.clear();
interp.stack.clear();
// A generator whose body was running when the run ended cannot go on.
let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect();
running.into_iter().for_each(|g| interp.end_generator(Some(g)));
interp.frames.clear();
interp.temp_roots.clear();
interp.join_stack.clear();
+15 -1
View File
@@ -185,6 +185,10 @@ pub(crate) struct Es2015Objects {
pub(crate) array_values: ObjId,
/// `Function.prototype[@@hasInstance]`.
pub(crate) has_instance: ObjId,
/// `%GeneratorPrototype%`, which each generator function's `prototype` inherits from.
pub(crate) generator_proto: ObjId,
/// `%GeneratorFunction.prototype%`, the `[[Prototype]]` of every generator function.
pub(crate) generator_function_proto: ObjId,
}
/// The estimated bytes of a registry entry without its Symbol.
@@ -208,7 +212,17 @@ impl Symbols {
/// The objects the collector starts from.
pub(crate) fn root_objects(&self) -> Vec<ObjId> {
self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance])
self.objects.map_or_else(Vec::new, |o| {
vec![
o.symbol_proto,
o.array_iterator_proto,
o.string_iterator_proto,
o.array_values,
o.has_instance,
o.generator_proto,
o.generator_function_proto,
]
})
}
/// The bytes the registry's entries hold besides their Symbols, which a collection adds.
+57 -1
View File
@@ -51,11 +51,15 @@
//! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and
//! that parse with that option. Its failures go to `symbol-failures.txt`.
//!
//! The last test reads the tests of `for-of` and destructuring (the folders
//! Another test reads the tests of `for-of` and destructuring (the folders
//! [`FOR_OF_AND_PATTERN_FOLDERS`] names) with [`Options::es2015`]: tests of any edition whose
//! feature tags are all in [`FOR_OF_AND_PATTERN_FEATURES`]. Negative parse tests must give a
//! `SyntaxError`; the others run as the Symbol tests run. Its failures go to `for-of-failures.txt`.
//!
//! The last test reads and runs the tests of generator functions, `yield` and the generator objects
//! (the folders [`GENERATOR_FOLDERS`] names) the same way, with the `generators` tag and the tags of
//! the two tests before it. Its failures go to `generators-failures.txt`.
//!
//! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses
//! an `includes:` name that leaves the `harness/` folder, and refuses a file over
//! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test.
@@ -1176,6 +1180,58 @@ fn run_for_of_and_patterns(dir: &Path) {
assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display());
}
/// The folders of the tests of generator functions, `yield` and the generator objects, which run
/// in a realm with [`Options::es2015`].
const GENERATOR_FOLDERS: &[&str] = &[
"language/statements/generators",
"language/expressions/generators",
"language/expressions/yield",
"built-ins/GeneratorPrototype",
"built-ins/GeneratorFunction",
];
#[test]
fn es2015_generators_run() {
let Some(dir) = suite_dir() else {
println!("test262 generators: SKIPPED (no suite; run cargo xtask test262)");
return;
};
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_generators(&dir)).unwrap();
handle.join().unwrap();
}
/// Reads the tests under each folder [`GENERATOR_FOLDERS`] names whose feature tags are all
/// `generators` or in [`FOR_OF_AND_PATTERN_FEATURES`] or [`SYMBOL_FEATURES`] with
/// [`Options::es2015`], as [`run_for_of_and_patterns`] reads its tests. Prints the counts of each
/// folder and writes the failures to `generators-failures.txt` beside the suite.
fn run_generators(dir: &Path) {
let options = Options { es2015: true, ..Options::default() };
let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]);
let mut features: Vec<&str> = vec!["generators"];
features.extend(FOR_OF_AND_PATTERN_FEATURES);
features.extend(SYMBOL_FEATURES);
let mut all = RunCounts::default();
let mut report = String::new();
for folder in GENERATOR_FOLDERS {
let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else {
println!("test262 {folder}: SKIPPED (not in this suite)");
continue;
};
let mut counts = run_parse_negatives(dir, &root, &options, &features);
counts.add(run_tagged_tests(dir, &root, &missing, &options, &features));
println!("test262 {folder} with Options::es2015: {}.", counts.summary());
report.push_str(&format!("# {folder}\n{}\n", counts.failures));
all.add(counts);
}
assert!(all.tests > 0, "no generator tests ran under {}", dir.display());
let path = dir.join("generators-failures.txt");
if let Err(e) = std::fs::write(&path, &report) {
println!("could not write {}: {e}", path.display());
}
println!("test262 generators with Options::es2015: {}. Failures: {}", all.summary(), path.display());
assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display());
}
/// Parses the negative parse tests under `root` whose feature tags are all in `features`, in
/// each mode the test names, with `options`; each must give a `SyntaxError`.
fn run_parse_negatives(dir: &Path, root: &Path, options: &Options, features: &[&str]) -> RunCounts {
+11 -5
View File
@@ -771,7 +771,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.panel.float",
"Float Panel",
"",
"{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}",
"{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window when the float takes the whole window (a panel alone in it, `column`, or `group` on a tab group that fills it); omitted components keep their current values. A panel that shares its native window floats into a new window instead, and the shared window keeps its other panels. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}",
),
(
"window.panel.dock",
@@ -867,7 +867,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"retype.find",
"Find Matching Fonts",
"",
"{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns",
"{more?: bool, installed?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first, then, unless installed is false, the installed fonts not loaded yet, which the app reads in the background, with retype.cancelSearch to stop it, when the panel's button, a menu or the command palette runs it): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more or installed other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns",
),
(
"retype.list",
@@ -1597,7 +1597,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors Line truncated
),
(
"ui.savePdfDialog",
@@ -2030,17 +2030,23 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}",
),
(
"retype.cancelSearch",
"Cancel Font Search",
"",
"{} stop the search of the installed fonts that Type › Retype or the Retype panel's Find Matching Fonts runs in the background (its progress window's Cancel): it stops before its next file, and Retype changes nothing and the list stays as it was → {cancelled: n}",
),
(
"ui.runScript",
"Other Script…",
"Cmd+F12",
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)",
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
),
(
"ui.runInstalledScript",
"Run Script",
"",
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again",
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
),
(
"ui.checkScript",
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "vectorcraft-plugins"
description = "Sandboxed WebAssembly plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects"
description = "Sandboxed plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects, and JavaScript object filters"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -21,6 +21,8 @@ craft-vectorcraft-format = { workspace = true }
# The SHA-256 of a module, which the install prompt shows and a grant records.
sha2 = { version = "0.10", default-features = false }
thiserror = { workspace = true }
# The interpreter of JavaScript plug-ins (`js.rs`).
vectorcraft-js = { workspace = true }
wasmi = { workspace = true }
wasmparser = { workspace = true }
# The monotonic clock of run deadlines and the first-view budget: `std::time::Instant` on the
+3 -3
View File
@@ -688,7 +688,7 @@ impl Run {
}
}
fn progress(&mut self, done: i64, total: i64) {
pub(crate) fn progress(&mut self, done: i64, total: i64) {
let total = u64::try_from(total).unwrap_or(0);
let done = u64::try_from(done).unwrap_or(0);
let done = if total > 0 { done.min(total) } else { done };
@@ -710,12 +710,12 @@ impl Run {
vectorcraft_doc::cancel::progress(done, total, PROGRESS_STEP);
}
fn cancelled(&self) -> i32 {
pub(crate) fn cancelled(&self) -> i32 {
i32::from(vectorcraft_doc::cancel::is_cancelled() || self.deadline.passed())
}
/// Writes the `len` bytes at `ptr` in `memory` as a line of `level` → what `vc_log` returns.
fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 {
pub(crate) fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 {
let Some(level) = LogLevel::from_code(level) else { return LOG_BAD_LEVEL };
let Some(bytes) = ptr.checked_add(len).and_then(|end| memory.get(ptr..end)) else { return LOG_OUTSIDE_MEMORY };
if self.report.truncated {
+517
View File
@@ -0,0 +1,517 @@
//! JavaScript plug-ins: an object filter whose manifest gives `"runtime": "js"`, with its code in a
//! JavaScript file instead of a WebAssembly module, run on `vectorcraft-js`.
//!
//! On disk the plug-in is a manifest file (`.vcplugin`, JSON) with `"runtime": "js"` and `script`,
//! the name of its `.js` file in the same folder ([`crate::registry::read_js_package`]). The host
//! loads it as one JSON object, the manifest with the script's text in `source`
//! ([`read_bundle`]): that object is what `plugin.install {dataBase64}` takes, what the plug-in
//! store keeps, and what the SHA-256 a grant records covers, so a change to the manifest or to the
//! script needs a new approval. Loading parses the script and runs none of it.
//!
//! Each run gets a fresh realm with the language's built-ins and a `vc` object: `vc.input`
//! and `vc.params` hold the input and parameter JSON a WebAssembly filter's `vc_run` is given, and
//! with the `progress` permission `vc.progress(done, total)`, `vc.cancelled()` and
//! `vc.log(level, text)` do what `vc_progress`, `vc_cancelled` and `vc_log` do ([`crate::host`]).
//! The realm has no `$`, `File`, `Folder`, `app` or other global of the script runner, no clock
//! (`Date.now()` is `NaN`) and no host function besides these. The script's top level runs, then
//! `run(input, params)` is called with the parsed JSON, and the value it returns, written as JSON,
//! is the run's output, which the host checks as it checks a WebAssembly filter's.
//!
//! A run is held to the filter's instruction budget (one budget for the top level and the call,
//! checked in slices between which the deadline and Cancel are checked), a heap of at most the
//! plug-in's memory cap, and the interpreter's frame and re-entry limits. A thrown error, a limit
//! or a malformed result fails the run with an [`Error`] that names the plug-in, its script and,
//! when known, the line and column.
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::{Map, Value};
use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind};
use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run};
use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime};
use crate::permissions::{self, Permission};
use crate::runtime::SELECTION_TOO_LARGE;
use crate::{Error, Limits, Result};
/// The extension of a JavaScript plug-in's manifest file.
pub const PACKAGE_EXT: &str = "vcplugin";
/// Largest script, in bytes.
pub const MAX_SCRIPT_BYTES: usize = 8 << 20;
/// Longest script file name, in bytes.
pub const MAX_SCRIPT_NAME: usize = 128;
/// The script's name when the plug-in's JSON gives none.
pub const DEFAULT_SCRIPT: &str = "plugin.js";
/// Instructions a run executes between two checks of its deadline and Cancel.
pub const FUEL_SLICE: u64 = 1_000_000;
/// Longest error message a run reports, in characters.
const MAX_ERROR_TEXT: usize = 512;
/// What `script` may hold.
const SCRIPT_NAME_RULE: &str =
"`script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.`";
/// Where the script's text may be given.
pub const SOURCE_RULE: &str =
"`source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script`";
/// The error of a plug-in's JSON without `"runtime": "js"`.
pub(crate) const NOT_JS: &str = "a JavaScript plug-in's manifest gives `runtime` \"js\"";
/// What the arguments of `vc.progress` and `vc.log` may be.
const PROGRESS_ARGS: &str = "vc.progress(done, total) takes two numbers";
const LOG_ARGS: &str = "vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string";
/// What runs the plug-in: its script's top level is done, `run` is called with the input and the
/// parameters, and what it returns is written as JSON.
const ENTRY: &str = "(function () {\n\
if (typeof run !== 'function') throw new TypeError('the script defines no function run(input, params)');\n\
return JSON.stringify(run(JSON.parse(vc.input), JSON.parse(vc.params)));\n\
})()";
/// A JavaScript plug-in's code.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Script {
/// Its file name, which errors give.
pub(crate) name: String,
pub(crate) source: String,
}
/// Is `name` a script file name `script` may give: a `.js` file directly in the manifest's folder?
pub fn valid_script_name(name: &str) -> bool {
(1..=MAX_SCRIPT_NAME).contains(&name.len())
&& !name.starts_with('.')
&& !name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control())
&& name.len() > 3
&& name.get(name.len() - 3..).is_some_and(|ext| ext.eq_ignore_ascii_case(".js"))
}
/// The `script` a manifest's JSON gives, checked.
pub(crate) fn script_name(v: &Value) -> Result<String> {
match v.as_str() {
Some(name) if valid_script_name(name) => Ok(name.to_string()),
_ => Err(Error::Manifest(SCRIPT_NAME_RULE.into())),
}
}
/// The error of a manifest with `"runtime": "js"` and no `script`.
pub(crate) fn no_script() -> Error {
Error::Manifest("`runtime` \"js\" needs `script`: the name of the plug-in's .js file, next to the manifest".into())
}
/// Does `map`, a plug-in's JSON, give `"runtime": "js"`?
pub(crate) fn is_js(map: &Map<String, Value>) -> bool {
map.get("runtime").and_then(Value::as_str) == Some(Runtime::Js.name())
}
/// How the script is read.
fn options() -> vectorcraft_js::Options {
vectorcraft_js::Options { max_source_units: MAX_SCRIPT_BYTES, ..vectorcraft_js::Options::default() }
}
/// Reads a JavaScript plug-in given as one JSON object: its manifest, with the script's text in
/// `source` and its file name in `script` (left out: [`DEFAULT_SCRIPT`]). The manifest is checked as
/// a module's is, and the script is parsed, not run.
pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> {
let mut map: Map<String, Value> = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?;
if !is_js(&map) {
return Err(Error::Manifest(NOT_JS.into()));
}
let named = map.remove("script");
let source = match map.remove("source") {
Some(Value::String(s)) => s,
Some(_) => return Err(Error::Manifest(SOURCE_RULE.into())),
None if named.is_some() => return Err(Error::Manifest(SOURCE_RULE.into())),
None => return Err(no_script()),
};
let name = named.as_ref().map_or_else(|| Ok(DEFAULT_SCRIPT.to_string()), script_name)?;
if source.len() > MAX_SCRIPT_BYTES {
return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES)));
}
// The manifest is read from `bytes`, so `params` keep their order; its size is counted
// without `script` and `source`.
let size = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?.len();
if size > MAX_MANIFEST_BYTES {
return Err(Error::Manifest(format!("manifest is {size} bytes (limit {MAX_MANIFEST_BYTES})")));
}
let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?;
let manifest = Manifest::parse_text(text)?;
if let Err(e) = vectorcraft_js::parse(&source, &options()) {
let named = Named { id: &manifest.id, script: &name };
return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column)))));
}
Ok((manifest, Script { name, source }))
}
/// `reason` followed by where it happened: the plug-in's id, its script's name and, when `at` gives
/// them, the line and column.
fn located(reason: &str, named: &Named<'_>, at: Option<(u32, u32)>) -> String {
let (id, script) = (named.id, named.script);
match at {
Some((line, column)) if line > 0 => format!("{reason} ({id}, {script} line {line}, column {column})"),
_ => format!("{reason} ({id}, {script})"),
}
}
/// One run's input and budgets.
pub(crate) struct Call<'a> {
pub(crate) input: &'a [u8],
pub(crate) params: &'a [u8],
pub(crate) limits: &'a Limits,
/// The plug-in's memory cap, which the run's heap stays within.
pub(crate) max_memory: usize,
pub(crate) deadline: Deadline,
}
/// The heap a run may use with memory cap `max_memory`.
fn heap_bytes(max_memory: usize) -> usize {
vectorcraft_js::Limits::default().heap_bytes.min(max_memory)
}
/// Runs `script`, the code of the plug-in `m` describes, on `call`'s input in a fresh realm → the
/// output JSON. What it reported with `vc.progress` and `vc.log` goes to `report`.
pub(crate) fn run(script: &Script, m: &Manifest, call: &Call<'_>, state: Run, report: &mut Report) -> Result<Vec<u8>> {
let heap = heap_bytes(call.max_memory);
// Each UTF-8 byte may become a UTF-16 code unit of two bytes, and the parsed JSON takes more.
if call.input.len().saturating_add(call.params.len()) > heap / 8 {
return Err(Error::Limit(SELECTION_TOO_LARGE.into()));
}
// The host writes the input and the parameters with serde_json, so they are UTF-8.
let (input, params) = (String::from_utf8_lossy(call.input), String::from_utf8_lossy(call.params));
let state = Rc::new(RefCell::new(state));
let out = run_realm(script, m, (&*input, &*params), call, heap, &state);
*report = std::mem::take(&mut state.borrow_mut().report);
out
}
/// What errors name: the plug-in's id and its script's file name.
struct Named<'a> {
id: &'a str,
script: &'a str,
}
fn run_realm(
script: &Script,
m: &Manifest,
(input, params): (&str, &str),
call: &Call<'_>,
heap: usize,
state: &Rc<RefCell<Run>>,
) -> Result<Vec<u8>> {
let defaults = vectorcraft_js::Limits::default();
let fuel = call.limits.fuel_base.saturating_add((call.input.len() as u64).saturating_mul(call.limits.fuel_per_byte));
let limits = vectorcraft_js::Limits { fuel, heap_bytes: heap, ..defaults };
let mut realm = Realm::with_options(options(), limits);
realm.set_clock(|| f64::NAN);
let named = Named { id: &m.id, script: &script.name };
realm.define_host_object("vc", vc_items(input, params, m, state)).map_err(|e| match e.kind {
RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(SELECTION_TOO_LARGE.into()),
_ => js_error(&realm, e, vectorcraft_js::UNKNOWN_SOURCE, &named),
})?;
let (_, tag) = drive(&mut realm, &script.source, &call.deadline, &named, None)?;
// The call takes what the top level left of the budget.
let left = realm.fuel_left();
realm.set_limits(vectorcraft_js::Limits { fuel: left, ..realm.limits().clone() });
let (value, _) = drive(&mut realm, ENTRY, &call.deadline, &named, Some(tag))?;
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
call.deadline.check()?;
match value {
JsValue::String(s) if s.len() > call.limits.max_output_bytes => {
let (what, len, max) = ("the output", s.len(), call.limits.max_output_bytes);
Err(Error::Limit(format!("output size ({what} is {len} bytes, limit {max})")))
}
JsValue::String(s) => Ok(s.into_bytes()),
_ => Err(Error::Output(located(NO_OUTPUT, &named, None))),
}
}
/// The error of a `run` that returned nothing JSON can write.
const NO_OUTPUT: &str = "run(input, params) returned no output object";
/// The limit a run that nested its calls too deeply exceeded.
const CALL_DEPTH: &str = "call depth";
/// Runs `source` in `realm` to its end, in slices of [`FUEL_SLICE`] with the deadline and Cancel
/// checked between them → its completion value, and the source tag of the plug-in's script:
/// `script_tag`, or with `None` the tag of `source`, which is then the script.
fn drive(realm: &mut Realm, source: &str, deadline: &Deadline, named: &Named<'_>, script_tag: Option<u32>) -> Result<(JsValue, u32)> {
let started = realm.start(source);
let tag = script_tag.unwrap_or_else(|| realm.script_tag());
started.map_err(|e| js_error(realm, e, tag, named))?;
loop {
match realm.advance(FUEL_SLICE) {
Ok(Progress::Done(v)) => return Ok((v, tag)),
Ok(Progress::Paused) => {}
Err(e) => return Err(js_error(realm, e, tag, named)),
}
if vectorcraft_doc::cancel::check().is_err() {
realm.end();
return Err(Error::Cancelled);
}
if let Err(e) = deadline.check() {
realm.end();
return Err(e);
}
}
}
/// The plug-in error for `e`, which a run of `realm` ended with: it names the plug-in and the script,
/// and the line and column when the error is in the script (source tag `tag`).
fn js_error(realm: &Realm, e: RunError, tag: u32, named: &Named<'_>) -> Error {
let at = (realm.error_tag() == tag).then_some((e.line, e.column));
let message = permissions::display_text(&e.message, MAX_ERROR_TEXT);
match e.kind {
RunErrorKind::Syntax => Error::Module(located(&message, named, at)),
RunErrorKind::Thrown | RunErrorKind::Limit(LimitKind::Host) => Error::Failed(located(&message, named, at)),
RunErrorKind::Limit(LimitKind::Jobs) => Error::Limit(located(&message, named, at)),
RunErrorKind::Limit(LimitKind::Fuel | LimitKind::Unbroken) => Error::Limit(located("instruction budget", named, at)),
RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(located("memory budget", named, at)),
RunErrorKind::Limit(LimitKind::Frames | LimitKind::Reentry) => Error::Limit(located(CALL_DEPTH, named, at)),
RunErrorKind::Limit(LimitKind::Interrupted) => Error::Cancelled,
RunErrorKind::Internal => Error::Trap(located(&message, named, at)),
}
}
/// The members of the realm's `vc` object.
fn vc_items(input: &str, params: &str, m: &Manifest, state: &Rc<RefCell<Run>>) -> Vec<(String, HostItem)> {
let mut items = vec![
("input".to_string(), HostItem::Value(Data::String(input.into()))),
("params".to_string(), HostItem::Value(Data::String(params.into()))),
];
if !m.permissions().contains(&Permission::Progress) {
return items;
}
let number = |args: &[Data], i: usize, rule: &str| match args.get(i) {
Some(Data::Number(n)) => Ok(*n),
_ => Err(HostError::Type(rule.into())),
};
let run = state.clone();
items.push((
"progress".into(),
HostItem::Function(Rc::new(move |args| {
let (done, total) = (number(&args, 0, PROGRESS_ARGS)?, number(&args, 1, PROGRESS_ARGS)?);
// `as` turns NaN into 0 and clamps the rest, as `vc_progress` clamps negative values.
run.borrow_mut().progress(done as i64, total as i64);
Ok(Data::Undefined)
})),
));
let run = state.clone();
items.push(("cancelled".into(), HostItem::Function(Rc::new(move |_| Ok(Data::Bool(run.borrow().cancelled() == 1))))));
let run = state.clone();
items.push((
"log".into(),
HostItem::Function(Rc::new(move |args| {
let level = number(&args, 0, LOG_ARGS)?;
let Some(Data::String(text)) = args.get(1) else { return Err(HostError::Type(LOG_ARGS.into())) };
let level = if level.fract() == 0.0 && (0.0..=3.0).contains(&level) { level as i32 } else { LOG_BAD_LEVEL };
match run.borrow_mut().log(level, text.as_bytes(), 0, text.len()) {
LOG_WRITTEN => Ok(Data::Bool(true)),
LOG_DROPPED => Ok(Data::Bool(false)),
_ => Err(HostError::Range(LOG_ARGS.into())),
}
})),
));
items
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use crate::{Error, Limits, Plugin};
/// A JavaScript filter `id` with `source` as its code, and `extra` manifest keys.
fn bundle(id: &str, source: &str, extra: Value) -> Vec<u8> {
let mut m = json!({"id": id, "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", "source": source});
if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) {
m.extend(extra);
}
serde_json::to_vec(&m).unwrap()
}
fn load(bytes: &[u8]) -> crate::Result<Plugin> {
load_with(bytes, Limits::default())
}
fn load_with(bytes: &[u8], limits: Limits) -> crate::Result<Plugin> {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
Plugin::load(bytes, limits)
}
const PATH: &str = r#"{"objects":[{"id":7,"type":"path","fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]}]}"#;
/// The output of `run(input, params)` is the run's output JSON.
#[test]
fn a_filter_returns_its_objects_as_json() {
let src = "function run(input, params) { return {objects: input.objects.map(function (o) { \
return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: params.blue}}]}; })}; }";
let p = load(&bundle("test.js.blue", src, json!({}))).unwrap();
assert_eq!((p.runtime(), p.script()), (crate::Runtime::Js, Some("test.js")));
let out: Value = serde_json::from_slice(&p.run(PATH.as_bytes(), br#"{"blue":1}"#).unwrap()).unwrap();
assert_eq!(out, json!({"objects": [{"id": 7, "fills": [{"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}]}]}));
}
/// The realm has none of the script runner's globals, so code that reads them throws a
/// `ReferenceError` naming the global, the plug-in and where in its script.
#[test]
fn file_folder_and_app_are_not_defined() {
for name in ["File", "Folder", "$", "app", "BridgeTalk"] {
let src = format!("function run(input) {{\n return {name}.x;\n}}");
let e = load(&bundle("test.js.globals", &src, json!({}))).unwrap().run(PATH.as_bytes(), b"{}").unwrap_err();
let Error::Failed(why) = &e else { panic!("{name}: {e:?}") };
assert!(why.starts_with("ReferenceError") && why.contains(name), "{name}: {why}");
assert!(why.ends_with("(test.js.globals, test.js line 2, column 10)"), "{name}: {why}");
}
let p = load(&bundle("test.js.clock", "function run() { return {objects: [], n: String(Date.now())}; }", json!({}))).unwrap();
let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap();
assert_eq!(out["n"], "NaN", "no clock");
}
/// Each run has a realm of its own: what one run changes in the built-ins, the next run doesn't
/// see.
#[test]
fn a_polluted_prototype_does_not_reach_the_next_run() {
let src = "function run() { var seen = Object.prototype.polluted; Object.prototype.polluted = 1; \
Array.prototype.map = null; return {objects: [], seen: String(seen)}; }";
let p = load(&bundle("test.js.pollute", src, json!({}))).unwrap();
for _ in 0..2 {
let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap();
assert_eq!(out["seen"], "undefined");
}
}
/// An endless loop ends with the instruction budget, naming the plug-in and the line.
#[test]
fn an_endless_loop_ends_with_the_instruction_budget() {
let p = load(&bundle("test.js.loop", "function run() {\n for (;;) {}\n}", json!({}))).unwrap();
let limits = Limits { fuel_base: 3 * super::FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() };
let e = p.run_limited(b"{\"objects\":[]}", b"{}", &limits).unwrap_err();
assert!(matches!(&e, Error::Limit(why) if why.starts_with("instruction budget (test.js.loop, test.js line 2")), "{e:?}");
}
/// A plug-in that fills its heap ends with its memory budget, and a realm another caller holds
/// meanwhile, such as a script's, runs on as before.
#[test]
fn heap_exhaustion_leaves_a_held_realm_usable() {
let mut held = vectorcraft_js::Realm::new();
held.run("var kept = 41;").unwrap();
let src = "function run() { var a = []; for (;;) { a.push(new Array(1000).join('x') + a.length); } }";
let small = load_with(&bundle("test.js.heap", src, json!({})), Limits { max_memory_bytes: 8 << 20, ..Limits::default() }).unwrap();
let e = small.run(b"{\"objects\":[]}", b"{}").unwrap_err();
assert!(matches!(&e, Error::Limit(why) if why.starts_with("memory budget (test.js.heap")), "{e:?}");
assert_eq!(held.run("kept + 1").unwrap(), vectorcraft_js::JsValue::Number(42.0));
}
/// An input too large for the heap is refused before it is copied in.
#[test]
fn a_selection_too_large_for_the_heap_is_refused() {
let small =
load_with(&bundle("test.js.big", "function run(i) { return i; }", json!({})), Limits { max_memory_bytes: 1 << 20, ..Limits::default() })
.unwrap();
let input = format!(r#"{{"objects":[],"pad":"{}"}}"#, "x".repeat(200_000));
assert_eq!(small.run(input.as_bytes(), b"{}"), Err(Error::Limit(crate::runtime::SELECTION_TOO_LARGE.into())));
}
/// A result that isn't an output object, and a script without `run`, fail the run.
#[test]
fn a_missing_entry_or_result_fails_the_run() {
let e = load(&bundle("test.js.none", "var x = 1;", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err();
assert!(matches!(&e, Error::Failed(why) if why.contains("defines no function run")), "{e:?}");
let e = load(&bundle("test.js.undef", "function run() {}", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err();
assert!(matches!(&e, Error::Output(why) if why.contains("test.js.undef")), "{e:?}");
let e = load(&bundle("test.js.cycle", "function run() { var o = {}; o.o = o; return o; }", json!({})))
.unwrap()
.run(b"{\"objects\":[]}", b"{}")
.unwrap_err();
assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}");
}
/// With `progress`, `vc.progress` and `vc.log` report as their imports do; without it, `vc`
/// has neither.
#[test]
fn progress_and_log_need_the_progress_permission() {
let src = "function run() { vc.progress(3, 4); vc.log(2, 'half'); return {objects: [], cancelled: vc.cancelled()}; }";
let p = load(&bundle("test.js.progress", src, json!({"api": 2, "permissions": ["progress"]}))).unwrap();
let (out, report) = p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits());
let out: Value = serde_json::from_slice(&out.unwrap()).unwrap();
assert_eq!(out["cancelled"], false);
assert_eq!(report.progress, Some((3, 4)));
assert_eq!(report.lines, vec![crate::LogLine { level: crate::LogLevel::Info, text: "half".into() }]);
let e = load(&bundle("test.js.quiet", src, json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err();
assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}");
}
/// Loading checks the manifest and the script, and runs none of it.
#[test]
fn loading_refuses_a_bad_manifest_or_script() {
let ok = "function run() { return {objects: []}; }";
let refused = |bytes: Vec<u8>| load(&bytes).unwrap_err();
let e = refused(bundle("test.js.syntax", "function run( {", json!({})));
assert!(matches!(&e, Error::Module(why) if why.contains("(test.js.syntax, test.js line 1, column")), "{e:?}");
let big = "x".repeat(super::MAX_SCRIPT_BYTES + 1);
assert!(matches!(refused(bundle("test.js.big", &big, json!({}))), Error::Module(why) if why.starts_with("test.js is")));
let e = refused(bundle("test.js.effect", ok, json!({"kind": "effect"})));
assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}");
let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]})));
assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}");
let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"})));
assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}");
let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"})));
assert!(matches!(&e, Error::Manifest(why) if why == super::NOT_JS), "{e:?}");
let mut no_source: Value = serde_json::from_slice(&bundle("test.js.nosource", ok, json!({}))).unwrap();
no_source.as_object_mut().unwrap().remove("source");
let e = refused(serde_json::to_vec(&no_source).unwrap());
assert!(matches!(&e, Error::Manifest(why) if why.contains("`source`")), "{e:?}");
// Top-level code that would throw does not run at load.
assert!(load(&bundle("test.js.lazy", "throw new Error('ran');", json!({}))).is_ok());
}
/// A WebAssembly module's manifest can't give `"runtime": "js"`.
#[test]
fn a_module_manifest_cannot_be_javascript() {
let manifest = r#"{"id":"test.js.wasm","name":"T","kind":"filter","runtime":"js"}"#;
let bytes = wat::parse_str(crate::wat::returning(manifest, r#"{"objects":[]}"#)).unwrap();
assert!(matches!(load(&bytes), Err(Error::Manifest(why)) if why.contains("`runtime`")));
}
/// The SHA-256 a grant records is the bundle's, so another script is another module.
#[test]
fn the_hash_covers_the_script() {
let a = load(&bundle("test.js.hash", "function run() { return {objects: []}; }", json!({}))).unwrap();
let b = load(&bundle("test.js.hash", "function run() { return {objects: [] }; }", json!({}))).unwrap();
assert_ne!(a.hash(), b.hash());
}
/// The parameters, and a command's, keep the order the plug-in's JSON declares them in.
#[test]
fn params_keep_their_declaration_order() {
let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#;
let text = format!(
r#"{{"id": "test.js.order", "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js",
"params": {{"z": {num}, "a": {num}, "m": {num}}},
"commands": [{{"id": "go", "label": "Go", "params": {{"y": {num}, "b": {num}}}}}],
"source": "function run(i) {{ return i; }}"}}"#
);
let (manifest, _) = super::read_bundle(text.as_bytes()).unwrap();
let names = |p: &[(String, crate::manifest::Param)]| p.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>();
assert_eq!(names(&manifest.params), ["z", "a", "m"]);
assert_eq!(names(&manifest.commands[0].params), ["y", "b"]);
}
#[test]
fn script_names_stay_in_the_manifest_s_folder() {
for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] {
assert!(super::valid_script_name(ok), "{ok}");
}
for bad in ["", ".js", ".hidden.js", "../x.js", "sub/x.js", "sub\\x.js", "c:x.js", "x.jsx", "x.js\n", "x.wasm"] {
assert!(!super::valid_script_name(bad), "{bad:?}");
}
assert!(!super::valid_script_name(&format!("{}.js", "a".repeat(126))));
}
}
+6 -1
View File
@@ -32,6 +32,10 @@
//! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A
//! filter or a live effect may also add menu commands of its own ([`Command`]), which the host
//! runs through `vc_run` with the command's id in `_context`.
//!
//! An object filter may also be written in JavaScript ([`js`]): its manifest gives
//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each
//! run, with the same input, output, permissions and budgets.
#![forbid(unsafe_code)]
pub mod deferred;
@@ -40,6 +44,7 @@ pub mod effect;
pub mod export;
pub mod host;
pub mod import;
pub mod js;
pub mod loader;
pub mod manifest;
pub mod objects;
@@ -53,7 +58,7 @@ pub mod wat;
pub use dialog::ParamUi;
pub use host::{LogLevel, LogLine, Report};
pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec};
pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime};
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms};
#[doc(hidden)]
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
+61 -1
View File
@@ -224,6 +224,32 @@ impl Budget {
}
}
/// What runs a plug-in's code.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Runtime {
/// A WebAssembly module ([`crate::Plugin::load`]); the manifest is the module's `vc_manifest`.
#[default]
Wasm,
/// A JavaScript file run on `vectorcraft-js` ([`crate::js`]): an object filter whose manifest
/// gives `"runtime": "js"`.
Js,
}
impl Runtime {
pub fn name(self) -> &'static str {
match self {
Runtime::Wasm => "wasm",
Runtime::Js => "js",
}
}
/// WebAssembly, which a manifest written back leaves out (`skip_serializing_if`).
fn is_wasm(&self) -> bool {
*self == Runtime::Wasm
}
}
/// One declared parameter.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
@@ -494,6 +520,9 @@ pub struct Manifest {
/// lists any ([`Manifest::validate`]).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub command_allowlist: Vec<String>,
/// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter.
#[serde(default, skip_serializing_if = "Runtime::is_wasm")]
pub runtime: Runtime,
}
impl Manifest {
@@ -503,6 +532,13 @@ impl Manifest {
return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len())));
}
let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?;
Manifest::parse_text(text)
}
/// [`Manifest::parse`] without its size limit, for JSON that holds other keys besides the
/// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys
/// the manifest doesn't declare are ignored, and `params` keep the order the text gives them.
pub(crate) fn parse_text(text: &str) -> Result<Manifest> {
if serde_json::from_str::<Value>(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) {
return Err(Error::Manifest("`paintOutput` may only be true".into()));
}
@@ -533,6 +569,7 @@ impl Manifest {
paint_output: false,
commands: Vec::new(),
command_allowlist: Vec::new(),
runtime: Runtime::Wasm,
}
}
@@ -620,7 +657,30 @@ impl Manifest {
}
self.validate_params()?;
self.validate_commands()?;
self.validate_allowlist()
self.validate_allowlist()?;
self.validate_runtime()
}
/// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions
/// it lists only `progress`: its realm has no settings, cache or command calls.
fn validate_runtime(&self) -> Result<()> {
if self.runtime == Runtime::Wasm {
return Ok(());
}
if self.kind != Kind::Filter {
let kind = self.kind.name();
return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\"")));
}
let listed = self.permissions.as_deref().unwrap_or_default();
for p in [Permission::Settings, Permission::Cache, Permission::Commands] {
if listed.iter().any(|n| n == p.name()) {
let name = p.name();
return Err(Error::Manifest(format!(
"a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress`"
)));
}
}
Ok(())
}
/// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids
+164 -7
View File
@@ -279,14 +279,73 @@ pub fn intern(s: &str) -> &'static str {
v
}
/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit)
/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit),
/// or a JavaScript plug-in's `.vcplugin` manifest and the script it names ([`read_js_package`]),
/// and loads it.
#[cfg(not(target_arch = "wasm32"))]
pub fn load_file(path: &std::path::Path, limits: Limits) -> Result<Plugin> {
let bytes = read_module(path, &limits, || {})?;
load_file_where(path, limits, &|_| Ok(()))
}
/// [`load_file`], reading a JavaScript plug-in's script only when `allow` accepts its path.
#[cfg(not(target_arch = "wasm32"))]
fn load_file_where(path: &std::path::Path, limits: Limits, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result<Plugin> {
let bytes = if is_js_package(path) { read_js_package(path, allow)? } else { read_module(path, &limits, || {})? };
Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string()))
}
/// Does `path` name a JavaScript plug-in's manifest file: is its extension `.vcplugin`?
pub fn is_js_package(path: &std::path::Path) -> bool {
path.extension().is_some_and(|x| x.eq_ignore_ascii_case(crate::js::PACKAGE_EXT))
}
/// The JavaScript plug-in whose manifest file is `path`, as the one JSON object [`Plugin::load`]
/// reads: the manifest, with the text of the script its `script` names in `source`. The manifest
/// file must give `"runtime": "js"` and `script`, a `.js` file in the same folder, and no `source`.
/// Each file is refused before it is read when it isn't a regular file or is larger than its limit
/// ([`crate::manifest::MAX_MANIFEST_BYTES`], [`crate::js::MAX_SCRIPT_BYTES`]); the script is read
/// only when `allow` accepts its path, and must be UTF-8.
#[cfg(not(target_arch = "wasm32"))]
pub fn read_js_package(path: &std::path::Path, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result<Vec<u8>> {
read_js_package_with(path, allow, || {})
}
/// [`read_js_package`], with `opening` run between the script's size check and its open.
#[cfg(not(target_arch = "wasm32"))]
fn read_js_package_with(
path: &std::path::Path,
allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>,
opening: impl FnOnce(),
) -> Result<Vec<u8>> {
use serde_json::Value;
let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() };
let bytes = read_module(path, &manifest_limits, || {})?;
let map: serde_json::Map<String, Value> = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?;
if !crate::js::is_js(&map) {
return Err(Error::Manifest(crate::js::NOT_JS.into()));
}
if map.contains_key("source") {
return Err(Error::Manifest(crate::js::SOURCE_RULE.into()));
}
let name = crate::js::script_name(map.get("script").ok_or_else(crate::js::no_script)?)?;
let file = path.parent().unwrap_or(std::path::Path::new("")).join(&name);
allow(&file).map_err(Error::Io)?;
let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() };
let source = read_module(&file, &script_limits, opening)?;
let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?;
// `source` is added to the manifest's own text, so its keys keep their order. The text parsed as
// an object that has `runtime`, so its last character other than white space is its closing `}`.
let end = bytes.iter().rposition(|b| !b.is_ascii_whitespace()).filter(|&i| bytes[i] == b'}');
let end = end.ok_or_else(|| Error::Manifest(format!("{}: not a JSON object", path.display())))?;
let source = serde_json::to_vec(&Value::String(source)).map_err(|e| Error::Manifest(e.to_string()))?;
let mut out = Vec::with_capacity(bytes.len() + source.len() + 12);
out.extend_from_slice(&bytes[..end]);
out.extend_from_slice(b",\"source\":");
out.extend_from_slice(&source);
out.push(b'}');
Ok(out)
}
/// The bytes of the module file at `path`. A path that doesn't name a regular file is refused
/// before it is opened, and so is one over the module limit. On Unix the file is opened without
/// waiting, so a named pipe put in its place after that check doesn't hold the load until something
@@ -329,7 +388,7 @@ fn open_module(path: &std::path::Path) -> std::io::Result<std::fs::File> {
#[cfg(not(target_arch = "wasm32"))]
const MAX_FOLDER_FILES: usize = 1000;
/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how
/// The first [`MAX_FOLDER_FILES`] `*.wasm` and `*.vcplugin` paths directly in `dir` by file name, sorted, and how
/// many more there are. Only that many paths are held while the folder is listed. An error while
/// the folder is listed is returned, as one opening it is.
#[cfg(not(target_arch = "wasm32"))]
@@ -340,7 +399,7 @@ fn folder_files(dir: &std::path::Path) -> Result<(Vec<std::path::PathBuf>, usize
let mut more = 0;
for entry in rd {
let p = entry.map_err(io)?.path();
if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) {
if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) && !is_js_package(&p) {
continue;
}
kept.push(p);
@@ -373,7 +432,7 @@ pub struct FolderReport {
pub no_thread: bool,
}
/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first
/// Installs every `*.wasm` and `*.vcplugin` ([`read_js_package`]) directly in `dir` (not recursive), in file-name order, up to the first
/// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything
/// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it
/// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name
@@ -386,7 +445,7 @@ pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
load_folder_where(dir, |_| Ok(()), approved)
}
/// [`load_folder`], loading only the files `allow` accepts, and of the plug-ins that list
/// [`load_folder`], loading only the files `allow` accepts (a JavaScript plug-in's script too), and of the plug-ins that list
/// permissions only those `approve` accepts and a recorded grant covers ([`install`]); the others
/// are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and
/// skipped, by its file before it loads or by its id after (its file is then disabled too, so the
@@ -500,7 +559,7 @@ impl FolderLoad {
hook(&path);
}
}
load_file(&path, Limits::default())
load_file_where(&path, Limits::default(), &*allow)
}));
}
files.push((f, refused));
@@ -885,6 +944,104 @@ mod tests {
assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}");
}
/// A JavaScript plug-in's manifest file and its script, in `dir`.
#[cfg(not(target_arch = "wasm32"))]
fn write_js(dir: &std::path::Path, id: &str, manifest: serde_json::Value, script: Option<&str>) -> std::path::PathBuf {
let mut m = serde_json::json!({"id": id, "name": "JS", "kind": "filter", "runtime": "js", "script": "f.js"});
if let (Some(m), serde_json::Value::Object(extra)) = (m.as_object_mut(), manifest) {
m.extend(extra);
}
let path = dir.join(format!("{id}.vcplugin"));
std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap();
if let Some(script) = script {
std::fs::write(dir.join("f.js"), script).unwrap();
}
path
}
/// A `.vcplugin` in a folder installs with its script, and its SHA-256 is the one an install of
/// the same package by bytes gets.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_installs_a_javascript_plugin() {
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
crate::safe_mode::set_active(None);
let dir = test_dir("js");
let id = "test.registry.js";
write_js(&dir, id, serde_json::json!({}), Some("function run(i) { return i; }"));
let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap();
let bytes = read_js_package(&dir.join(format!("{id}.vcplugin")), &|_| Ok(())).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(r.loaded, vec![id.to_string()], "{r:?}");
let p = get(id).unwrap();
assert_eq!((p.script(), p.hash()), (Some("f.js"), crate::permissions::sha256_hex(&bytes).as_str()));
assert!(remove(id));
}
/// A manifest with `"runtime": "js"` and no `script` is refused, and the error names the key;
/// so is one that names a script `allow` refuses or that isn't there.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_javascript_manifest_needs_its_script() {
let dir = test_dir("js-script");
let no_key = write_js(&dir, "a", serde_json::json!({"script": null}), None);
let mut m: serde_json::Value = serde_json::from_slice(&std::fs::read(&no_key).unwrap()).unwrap();
m.as_object_mut().unwrap().remove("script");
std::fs::write(&no_key, serde_json::to_vec(&m).unwrap()).unwrap();
let missing = write_js(&dir, "b", serde_json::json!({}), None);
let inline = write_js(&dir, "c", serde_json::json!({"source": "function run(i) { return i; }"}), None);
let not_js = write_js(&dir, "d", serde_json::json!({"runtime": "wasm"}), None);
let refused = read_js_package(&missing, &|p| Err(format!("{} is outside", p.display())));
let results = [
read_js_package(&no_key, &|_| Ok(())),
read_js_package(&missing, &|_| Ok(())),
read_js_package(&inline, &|_| Ok(())),
read_js_package(&not_js, &|_| Ok(())),
];
std::fs::remove_dir_all(&dir).unwrap();
assert!(matches!(&results[0], Err(Error::Manifest(e)) if e.starts_with("`runtime` \"js\" needs `script`")), "{:?}", results[0]);
assert!(matches!(&results[1], Err(Error::Io(e)) if e.contains("f.js")), "{:?}", results[1]);
assert!(matches!(&results[2], Err(Error::Manifest(e)) if e.contains("`source`")), "{:?}", results[2]);
assert!(matches!(&results[3], Err(Error::Manifest(e)) if e == crate::js::NOT_JS), "{:?}", results[3]);
assert!(matches!(&refused, Err(Error::Io(e)) if e.ends_with("is outside")), "{refused:?}");
}
/// A script larger than the limit is refused by its size before it is opened.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_oversized_script_is_refused_before_it_is_read() {
let dir = test_dir("js-big");
let path = write_js(&dir, "big", serde_json::json!({}), Some(""));
std::fs::File::options().write(true).open(dir.join("f.js")).unwrap().set_len(crate::js::MAX_SCRIPT_BYTES as u64 + 1).unwrap();
let opened = std::cell::Cell::new(false);
let read = read_js_package_with(&path, &|_| Ok(()), || opened.set(true));
std::fs::remove_dir_all(&dir).unwrap();
assert!(matches!(&read, Err(Error::Module(e)) if e.contains(&format!("limit {}", crate::js::MAX_SCRIPT_BYTES))), "{read:?}");
assert!(!opened.get(), "the script was opened");
}
/// A manifest file's parameters keep their declaration order through the package it is read
/// into, which is its own text with `source` added.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_javascript_package_keeps_the_manifest_s_order() {
let dir = test_dir("js-order");
let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#;
let text = format!(
"{{\"id\": \"order\", \"name\": \"JS\", \"kind\": \"filter\", \"runtime\": \"js\", \"script\": \"f.js\", \"params\": {{\"z\": {num}, \"a\": {num}}}}}\n"
);
let path = dir.join("order.vcplugin");
std::fs::write(&path, &text).unwrap();
std::fs::write(dir.join("f.js"), "function run(i) { return i; }").unwrap();
let bytes = read_js_package(&path, &|_| Ok(()));
std::fs::remove_dir_all(&dir).unwrap();
let bytes = bytes.unwrap();
let expected = format!("{},\"source\":\"function run(i) {{ return i; }}\"}}", text.trim_end().strip_suffix('}').unwrap());
assert_eq!(String::from_utf8_lossy(&bytes), expected);
let (manifest, _) = crate::js::read_bundle(&bytes).unwrap();
assert_eq!(manifest.params.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(), ["z", "a"]);
}
/// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm`
/// names as not files, and goes on.
#[cfg(unix)]
+69 -18
View File
@@ -7,7 +7,7 @@ use wasmi::{
use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures};
use crate::host::{self, Bridge, Deadline, Host, Report, Run};
use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest};
use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest, Runtime};
use crate::permissions::Permission;
use crate::{Error, Kind, Result};
@@ -169,12 +169,17 @@ impl Default for Limits {
}
}
/// A plug-in's code: a WebAssembly module, or a JavaScript file ([`crate::js`]).
enum Code {
Wasm { engine: Engine, module: Module },
Js(crate::js::Script),
}
/// A loaded, validated plug-in. Cheap to share (`Arc`) and safe to run from several threads:
/// every run gets its own store and instance.
/// every run gets its own store and instance, or for a JavaScript plug-in its own realm.
pub struct Plugin {
manifest: Manifest,
engine: Engine,
module: Module,
code: Code,
limits: Limits,
size: usize,
hash: String,
@@ -341,13 +346,21 @@ impl Plugin {
/// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the
/// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is
/// checked without being instantiated, so none of its code runs; one without that section is
/// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded
/// ([`Error::SafeMode`]).
/// instantiated to call `vc_abi_version` and `vc_manifest`. Bytes that hold a JSON object with
/// `"runtime": "js"` are a JavaScript plug-in ([`crate::js`]): its manifest is checked and its
/// script parsed, and none of it runs. In Safe Mode nothing is loaded ([`Error::SafeMode`]).
pub fn load(bytes: &[u8], limits: Limits) -> Result<Plugin> {
crate::safe_mode::check()?;
if bytes.len() > limits.max_module_bytes {
return Err(Error::Module(format!("module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes)));
}
if bytes.trim_ascii_start().starts_with(b"{") {
let (manifest, script) = crate::js::read_bundle(bytes)?;
let hash = crate::permissions::sha256_hex(bytes);
let mut p = Plugin { manifest, code: Code::Js(script), limits, size: bytes.len(), hash, source: None, serial: 0 };
p.heavy_limits();
return Ok(p);
}
if !bytes.starts_with(b"\0asm") {
return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into()));
}
@@ -362,8 +375,17 @@ impl Plugin {
let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?;
let imports = host::check_imports(&module)?;
let hash = crate::permissions::sha256_hex(bytes);
let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 };
let live = match section_manifest(&p.module)? {
let section = section_manifest(&module)?;
let mut p = Plugin {
manifest: Manifest::placeholder(),
code: Code::Wasm { engine, module: module.clone() },
limits,
size: bytes.len(),
hash,
source: None,
serial: 0,
};
let live = match section {
Some(manifest) => {
p.manifest = manifest;
None
@@ -388,13 +410,11 @@ impl Plugin {
Some(live)
}
};
host::check_granted(&p.manifest, &imports)?;
// A heavy filter's runs get the larger budget the host allows for one, which the host
// lets the user allow or refuse before installing it.
if p.manifest.budget == crate::Budget::Heavy {
p.limits.fuel_base = p.limits.fuel_base.max(p.limits.heavy_fuel);
p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms);
if p.manifest.runtime != Runtime::Wasm {
return Err(Error::Manifest("a WebAssembly module's manifest leaves `runtime` out: \"js\" is for a JavaScript plug-in".into()));
}
host::check_granted(&p.manifest, &imports)?;
p.heavy_limits();
// The other exports must exist with the right types.
match live {
Some(live) => {
@@ -402,13 +422,35 @@ impl Plugin {
live.func::<RunArgs, i64>("vc_run")?;
}
None => {
check_exports(&p.module, p.limits.max_memory_bytes)?;
check_exports(&module, p.limits.max_memory_bytes)?;
check_tables(bytes)?;
}
}
Ok(p)
}
/// A heavy filter's runs get the larger budget the host allows for one, which the host lets the
/// user allow or refuse before installing it.
fn heavy_limits(&mut self) {
if self.manifest.budget == crate::Budget::Heavy {
self.limits.fuel_base = self.limits.fuel_base.max(self.limits.heavy_fuel);
self.limits.wall_time_ms = self.limits.wall_time_ms.max(self.limits.heavy_wall_time_ms);
}
}
/// What runs its code ([`Manifest::runtime`]).
pub fn runtime(&self) -> Runtime {
self.manifest.runtime
}
/// A JavaScript plug-in's script file name; `None` for a WebAssembly module.
pub fn script(&self) -> Option<&str> {
match &self.code {
Code::Js(script) => Some(&script.name),
Code::Wasm { .. } => None,
}
}
pub fn manifest(&self) -> &Manifest {
&self.manifest
}
@@ -452,6 +494,7 @@ impl Plugin {
/// A new instance for `run`, with the host imports of the permissions `granted` linked. When the
/// module's start function fails, what it reported through the host imports goes to `report`.
fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result<Live> {
let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) };
let limits = StoreLimitsBuilder::new()
.memory_size(self.limits.max_memory_bytes)
.memories(1)
@@ -459,13 +502,13 @@ impl Plugin {
.table_elements(MAX_TABLE_ELEMENTS as usize)
.instances(1)
.build();
let mut store = Store::new(&self.engine, Host { limits, run });
let mut store = Store::new(engine, Host { limits, run });
store.limiter(|h| &mut h.limits);
// The start function (if any) runs on one slice of fuel: it runs before `call` can check
// the deadline or a cancel between slices, so a heavy budget would let it run for minutes.
store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?;
let linker = host::linker(&self.engine, granted);
let instance = match linker.instantiate_and_start(&mut store, &self.module) {
let linker = host::linker(engine, granted);
let instance = match linker.instantiate_and_start(&mut store, module) {
Ok(instance) => instance,
Err(e) => {
*report = std::mem::take(&mut store.data_mut().run.report);
@@ -595,6 +638,14 @@ impl Plugin {
let deadline = Deadline::new(limits.wall_time_ms);
let m = &self.manifest;
let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id));
if let Code::Js(script) = &self.code {
// Its manifest lists no `commands`, so nothing calls it with a bridge.
if bridge.is_some() {
return Err(Error::Abi("a JavaScript plug-in makes no command calls".into()));
}
let call = crate::js::Call { input, params, limits, max_memory: self.limits.max_memory_bytes, deadline };
return crate::js::run(script, m, &call, run, report);
}
let mut live = self.instantiate(run, &m.permissions(), report)?;
// Calls can be made from `vc_run` on, not from the start function.
if bridge.is_some() {
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff. Show more