mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:42:44 +00:00
Merge remote-tracking branch 'origin/main' into fix/import-document-title
# Conflicts: # docs/file-format-parity.md # docs/gaps.md # docs/target-app-parity.md
This commit is contained in:
@@ -774,8 +774,9 @@ fn divide_dashes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
let only = (segs.len() < sp.segment_count()).then_some(&segs);
|
||||
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made))
|
||||
.ok_or_else(|| bad(C, "that makes too many pieces (at most 100000): make the dashes longer"))?;
|
||||
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made)).ok_or_else(|| {
|
||||
bad(C, "that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer")
|
||||
})?;
|
||||
made += out.len();
|
||||
for (piece, kind) in out.into_iter().filter(|(_, k)| !(remove_gaps && *k == pt::Piece::Gap)) {
|
||||
dashes += usize::from(kind == pt::Piece::Dash);
|
||||
@@ -825,7 +826,7 @@ fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
|
||||
fn expand_dashes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.pathtools.expandDashes";
|
||||
let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer");
|
||||
let too_many = || bad(C, "that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer");
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Each dashed path and its dashes, as the canvas draws them.
|
||||
|
||||
@@ -21,8 +21,8 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration,
|
||||
TextStyleDef,
|
||||
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice,
|
||||
SymbolRegistration, TextStyleDef,
|
||||
};
|
||||
|
||||
use super::super::brushsym::{set_natural_size, stored_natural_size};
|
||||
@@ -140,6 +140,48 @@ fn node_refs(n: &Node, f: Visit) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The `(name, xml)` of `e` when it is an SVG filter effect.
|
||||
fn filter_of(e: &Effect) -> Option<(String, String)> {
|
||||
let text = |k: &str| e.params.get(k).and_then(Value::as_str).map(str::to_string);
|
||||
if e.id != Appearance::SVG_FILTER {
|
||||
return None;
|
||||
}
|
||||
Some((text("name")?, text("xml")?))
|
||||
}
|
||||
|
||||
/// The SVG filter effects of appearance `a` (its own and its fills' and strokes').
|
||||
fn appearance_filters(a: &Appearance, out: &mut BTreeSet<(String, String)>) {
|
||||
let items = a.items.iter().flat_map(|i| i.effects().iter());
|
||||
out.extend(a.effects.iter().chain(items).filter_map(filter_of));
|
||||
}
|
||||
|
||||
/// The SVG filter effects in the subtree of `n` (opacity-mask art included).
|
||||
fn node_filters(n: &Node, out: &mut BTreeSet<(String, String)>) {
|
||||
n.walk(&mut |m| {
|
||||
appearance_filters(&m.appearance, out);
|
||||
if let Some(mask) = &m.extras().mask {
|
||||
node_filters(&mask.art, out);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The names the SVG filter effects of appearance `a` give (its own and its fills' and strokes').
|
||||
fn appearance_filter_names(a: &Appearance, out: &mut BTreeSet<String>) {
|
||||
let items = a.items.iter().flat_map(|i| i.effects().iter());
|
||||
let named = a.effects.iter().chain(items).filter(|e| e.id == Appearance::SVG_FILTER);
|
||||
out.extend(named.filter_map(|e| e.params.get("name").and_then(Value::as_str)).map(str::to_string));
|
||||
}
|
||||
|
||||
/// The names the SVG filter effects in the subtree of `n` give (opacity-mask art included).
|
||||
fn node_filter_names(n: &Node, out: &mut BTreeSet<String>) {
|
||||
n.walk(&mut |m| {
|
||||
appearance_filter_names(&m.appearance, out);
|
||||
if let Some(mask) = &m.extras().mask {
|
||||
node_filter_names(&mask.art, out);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A global or spot colour of its own (not a tint of another swatch): what colours link to.
|
||||
fn is_base(w: &Swatch) -> bool {
|
||||
(w.global || w.spot) && matches!(w.paint, Paint::Solid { swatch: None, .. })
|
||||
@@ -527,6 +569,9 @@ impl SwatchChoices {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Relink {
|
||||
renames: BTreeMap<Res, BTreeMap<String, String>>,
|
||||
/// An SVG filter effect's `(name, xml)` on the clipboard → its `(name, xml)` in the document
|
||||
/// ([`Clipboard::filter_links`]).
|
||||
filters: BTreeMap<(String, String), (String, String)>,
|
||||
/// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped.
|
||||
styles: BTreeMap<u32, u32>,
|
||||
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
|
||||
@@ -566,6 +611,15 @@ impl Relink {
|
||||
});
|
||||
}
|
||||
fn appearance(&self, a: &mut Appearance) {
|
||||
if !self.filters.is_empty() {
|
||||
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
|
||||
for e in a.effects.iter_mut().chain(items) {
|
||||
if let Some((name, xml)) = filter_of(e).and_then(|k| self.filters.get(&k)) {
|
||||
e.params["name"] = json!(name);
|
||||
e.params["xml"] = json!(xml);
|
||||
}
|
||||
}
|
||||
}
|
||||
for it in &mut a.items {
|
||||
self.paint(it.paint_mut());
|
||||
if let AppearanceItem::Stroke(l) = it
|
||||
@@ -1013,6 +1067,7 @@ impl Clipboard {
|
||||
/// of definitions that use each other is matched on its own ([`loop_groups`]).
|
||||
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported {
|
||||
let mut out = Imported::default();
|
||||
out.relink.filters = self.filter_links(d, same_doc);
|
||||
self.import_images(d, used, same_doc, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
|
||||
@@ -1170,10 +1225,78 @@ impl Clipboard {
|
||||
}
|
||||
vectorcraft_brush::store(d, &lib);
|
||||
}
|
||||
out.relinks = !(out.relink.renames.is_empty() && out.relink.styles.is_empty() && out.relink.colors.is_empty() && used.styles.is_empty());
|
||||
out.relinks = !(out.relink.renames.is_empty()
|
||||
&& out.relink.filters.is_empty()
|
||||
&& out.relink.styles.is_empty()
|
||||
&& out.relink.colors.is_empty()
|
||||
&& used.styles.is_empty());
|
||||
out
|
||||
}
|
||||
|
||||
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
|
||||
/// filter of its name; one that draws another definition than that filter takes the document's
|
||||
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
|
||||
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would
|
||||
/// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else
|
||||
/// a free letter or digit; the filter's id is always its name.
|
||||
fn filter_links(&self, d: &Document, same_doc: bool) -> BTreeMap<(String, String), (String, String)> {
|
||||
let mut found = BTreeSet::new();
|
||||
for n in &self.nodes {
|
||||
node_filters(n, &mut found);
|
||||
}
|
||||
for s in &self.symbols {
|
||||
node_filters(&s.art, &mut found);
|
||||
}
|
||||
for a in self.patterns.iter().flat_map(|p| p.art.iter()) {
|
||||
node_filters(a, &mut found);
|
||||
}
|
||||
for a in self.brushes.iter().flat_map(Brush::art) {
|
||||
node_filters(a, &mut found);
|
||||
}
|
||||
for g in &self.graphic_styles {
|
||||
appearance_filters(&g.appearance, &mut found);
|
||||
}
|
||||
let mut taken: BTreeSet<String> = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect();
|
||||
let mut effects_read = false;
|
||||
let mut links = BTreeMap::new();
|
||||
for (name, xml) in found {
|
||||
let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue };
|
||||
let to = if same_doc {
|
||||
(name.clone(), held.xml.clone())
|
||||
} else {
|
||||
// The names the document's effects give are taken too, those whose filter was
|
||||
// deleted included: defining a filter of that name later changes every effect that
|
||||
// names it. They are read at the first rename only.
|
||||
if !effects_read {
|
||||
effects_read = true;
|
||||
for root in d.art_roots() {
|
||||
node_filter_names(root, &mut taken);
|
||||
}
|
||||
for g in &d.graphic_styles {
|
||||
appearance_filter_names(&g.appearance, &mut taken);
|
||||
}
|
||||
}
|
||||
// Free names made from the starts of the name, longest first, then free letters and
|
||||
// digits: the first under which the filter still draws.
|
||||
let mut ends: Vec<usize> = name.char_indices().map(|(i, _)| i).skip(1).collect();
|
||||
ends.push(name.len());
|
||||
let starts = ends.iter().rev().filter_map(|&end| name.get(..end).map(str::trim_end)).filter(|b| !b.is_empty());
|
||||
let shorter = starts.map(|b| unique_name(b, |n| taken.contains(n)));
|
||||
let single = ('a'..='z').chain('0'..='9').map(String::from).filter(|n| !taken.contains(n));
|
||||
let renamed = shorter.chain(single).find_map(|new| {
|
||||
let drawn = vectorcraft_render::effects::svg_filter::with_id(&xml, &new)
|
||||
.filter(|x| vectorcraft_render::effects::svg_filter::check(x).is_ok_and(|id| id == new))?;
|
||||
Some((new, drawn))
|
||||
});
|
||||
let Some((new, drawn)) = renamed else { continue };
|
||||
taken.insert(new.clone());
|
||||
(new, drawn)
|
||||
};
|
||||
links.insert((name, xml), to);
|
||||
}
|
||||
links
|
||||
}
|
||||
|
||||
/// Image blobs: a different blob under a key the document uses gets a new key.
|
||||
fn import_images(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
|
||||
for (key, blob) in self.images.iter().filter(|(k, _)| used.has(Res::Image, k)) {
|
||||
|
||||
@@ -478,6 +478,32 @@ fn an_opened_file_measures_its_type_in_its_own_composite_fonts() {
|
||||
assert_eq!(actual.cached_bounds, Some(expected));
|
||||
}
|
||||
|
||||
/// Threaded type read from a file flows through its frames in the file's own composite fonts, when
|
||||
/// no open document defines them.
|
||||
#[test]
|
||||
fn an_opened_file_flows_its_threads_in_its_own_composite_fonts() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Threaded")]})).unwrap();
|
||||
let story = "The quick brown fox jumps over the lazy dog and keeps running. ".repeat(4);
|
||||
let a = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 20, "font": "CF Threaded", "area": {"width": 150, "height": 60}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 300})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
let first = text(&s, a).plain_text();
|
||||
assert!(!first.is_empty() && first.len() < story.len());
|
||||
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
|
||||
// A new front document without the font: the font database no longer holds it.
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
assert!(vectorcraft_text::FontDb::global().composite_font("CF Threaded").is_none());
|
||||
let file = crate::cmd::fileio::read_for_open("threaded.vectorcraft", &bytes, None, &json!({}), false, false).unwrap();
|
||||
crate::cmd::fileio::open_read(&mut s, file).unwrap();
|
||||
assert_eq!(text(&s, a).plain_text(), first);
|
||||
}
|
||||
|
||||
/// A document replaced while in the back (File › Revert) is measured in its own composite fonts
|
||||
/// when it comes to the front, not in the front document's.
|
||||
#[test]
|
||||
|
||||
@@ -272,9 +272,9 @@ impl EndedLink {
|
||||
}
|
||||
|
||||
/// The [`reached`] dimensions become plain groups, whose art does not redraw or follow what it
|
||||
/// measured. A command that replaces art calls this before it changes anything, since replacing
|
||||
/// the art a dimension measures would otherwise leave the dimension unlinked, and then
|
||||
/// [`restore_unchanged`].
|
||||
/// measured. A command that replaces art calls this before it changes anything and
|
||||
/// [`restore_unchanged`] after, so that a dimension whose own art the command changed stays a
|
||||
/// plain group.
|
||||
pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec<EndedLink> {
|
||||
let mut ended = Vec::new();
|
||||
for id in reached(doc, roots) {
|
||||
@@ -287,18 +287,156 @@ pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec<EndedLink>
|
||||
ended
|
||||
}
|
||||
|
||||
/// The dimensions in `ended` whose art is as it was are live again.
|
||||
pub(crate) fn restore_unchanged(doc: &mut Document, ended: Vec<EndedLink>) {
|
||||
/// The dimensions in `ended` whose own art is as it was are live again. One whose measured art the
|
||||
/// command changed from `before` so that the art no longer fits its link stays where it was, no
|
||||
/// longer linked, as [`refresh`] leaves a dimension whose art was deleted.
|
||||
pub(crate) fn restore_unchanged(before: &Document, doc: &mut Document, ended: Vec<EndedLink>) {
|
||||
for e in ended {
|
||||
if doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art)
|
||||
&& let Some(n) = doc.node_mut(e.id)
|
||||
{
|
||||
n.extras_mut().dimension = Some(Box::new(e.recipe));
|
||||
if !doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art) {
|
||||
continue;
|
||||
}
|
||||
let recipe = if e.source_kept(before, doc) { e.recipe } else { unlinked(&e.recipe) };
|
||||
if let Some(n) = doc.node_mut(e.id) {
|
||||
n.extras_mut().dimension = Some(Box::new(recipe));
|
||||
doc.dimensions = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `old` where it was, no longer linked. A move it had on its own and not yet drawn is kept when
|
||||
/// the moved dimension is valid.
|
||||
fn unlinked(old: &Dimension) -> Dimension {
|
||||
let mut unlinked = old.clone();
|
||||
unlinked.source = None;
|
||||
unlinked.moved = None;
|
||||
if let Some(v) = old.moved {
|
||||
let mut shifted = unlinked.clone();
|
||||
(shifted.a, shifted.b, shifted.vertex) = (shifted.a + v, shifted.b + v, shifted.vertex + v);
|
||||
if shifted.validate().is_ok() {
|
||||
unlinked = shifted;
|
||||
}
|
||||
}
|
||||
unlinked
|
||||
}
|
||||
|
||||
/// The whole dimensions under `roots` that are selected together with art they measure (art under
|
||||
/// `roots`), each one a root or held by groups without fills, strokes or effects of their own.
|
||||
/// Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave their
|
||||
/// lines and label as they are. A group with an appearance of its own changes everything it holds
|
||||
/// when it expands, its dimensions included.
|
||||
pub(crate) fn with_their_art(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
if !doc.dimensions {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
for root in roots {
|
||||
let Some(n) = doc.node(*root) else { continue };
|
||||
n.walk(&mut |c| {
|
||||
if let Some(source) = c.extras().dimension.as_ref().and_then(|d| d.source.as_ref()) {
|
||||
found.push((*root, c.id, source.nodes()));
|
||||
}
|
||||
});
|
||||
}
|
||||
let under_roots = |id: NodeId| doc.ancestry(id).is_some_and(|a| a.iter().any(|a| roots.contains(a)));
|
||||
found
|
||||
.into_iter()
|
||||
.filter(|(root, id, _)| {
|
||||
let Some(ancestry) = doc.ancestry(*id) else { return false };
|
||||
let from = ancestry.iter().position(|a| a == root).unwrap_or(ancestry.len());
|
||||
ancestry.get(from..ancestry.len().saturating_sub(1)).unwrap_or_default().iter().all(|a| doc.node(*a).is_some_and(plain_group))
|
||||
})
|
||||
.filter(|(_, _, measured)| measured.iter().any(|m| under_roots(*m)))
|
||||
.map(|(_, id, _)| id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A group or layer without fills, strokes or effects of its own.
|
||||
fn plain_group(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && n.appearance.items.is_empty() && n.appearance.effects.is_empty()
|
||||
}
|
||||
|
||||
/// A dimension [`lift`] took out of the document, with its place, the export assets that list it or
|
||||
/// its parts (with their places in the asset list) and its parts' variable bindings.
|
||||
pub(crate) struct Lifted {
|
||||
parent: Option<NodeId>,
|
||||
index: usize,
|
||||
node: Arc<Node>,
|
||||
assets: Vec<(usize, vectorcraft_doc::assets::ExportAsset)>,
|
||||
bindings: Vec<(NodeId, std::collections::BTreeSet<String>)>,
|
||||
}
|
||||
|
||||
impl Lifted {
|
||||
pub(crate) fn id(&self) -> NodeId {
|
||||
self.node.id
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the [`with_their_art`] dimensions under `roots` out of `doc`, so a command that replaces
|
||||
/// art does not reach them; [`put_back`] puts them back.
|
||||
pub(crate) fn lift(doc: &mut Document, roots: &[NodeId]) -> Vec<Lifted> {
|
||||
let mut lifted = Vec::new();
|
||||
for id in with_their_art(doc, roots) {
|
||||
let Some((parent, index, _)) = doc.position(id) else { continue };
|
||||
let mut parts = std::collections::BTreeSet::new();
|
||||
if let Some(n) = doc.node(id) {
|
||||
n.walk(&mut |c| {
|
||||
parts.insert(c.id);
|
||||
});
|
||||
}
|
||||
let assets = doc.assets.iter().enumerate().filter(|(_, a)| a.nodes.iter().any(|n| parts.contains(n))).map(|(i, a)| (i, a.clone())).collect();
|
||||
let bindings = doc.variables.bindings.iter().filter(|(n, _)| parts.contains(n)).map(|(n, b)| (*n, b.clone())).collect();
|
||||
if let Ok(node) = doc.remove(id) {
|
||||
lifted.push(Lifted { parent, index, node, assets, bindings });
|
||||
}
|
||||
}
|
||||
lifted
|
||||
}
|
||||
|
||||
/// Each dimension [`lift`] took out, as it was, back in its place in `doc`, with its parts back in
|
||||
/// the export assets that listed them and their variable bindings back: edits made while it was out
|
||||
/// let go of them. A dimension whose group is gone goes on top of the first layer.
|
||||
pub(crate) fn put_back(doc: &mut Document, lifted: Vec<Lifted>) {
|
||||
for l in lifted.into_iter().rev() {
|
||||
let parent = if doc.children(l.parent).is_some() { l.parent } else { doc.layers.first().map(|layer| layer.id) };
|
||||
let Ok(ch) = doc.children_mut(parent) else { continue };
|
||||
let i = if parent == l.parent { l.index.min(ch.len()) } else { ch.len() };
|
||||
ch.insert(i, l.node);
|
||||
doc.dimensions = true;
|
||||
for (at, saved) in l.assets {
|
||||
let there: Vec<NodeId> = saved.nodes.iter().copied().filter(|n| doc.node(*n).is_some()).collect();
|
||||
if let Some(a) = doc.assets.iter_mut().find(|a| a.id == saved.id) {
|
||||
for (k, n) in there.iter().enumerate() {
|
||||
if !a.nodes.contains(n) {
|
||||
let k = k.min(a.nodes.len());
|
||||
a.nodes.insert(k, *n);
|
||||
}
|
||||
}
|
||||
} else if !there.is_empty() {
|
||||
let at = at.min(doc.assets.len());
|
||||
doc.assets.insert(at, vectorcraft_doc::assets::ExportAsset { nodes: there, ..saved });
|
||||
}
|
||||
}
|
||||
for (n, b) in l.bindings {
|
||||
doc.variables.bindings.entry(n).or_insert(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `doc` without the [`with_their_art`] dimensions under `roots`, to see what a command that leaves
|
||||
/// them alone would change: `doc` itself when there are none.
|
||||
pub(crate) fn without_kept<'a>(doc: &'a Document, roots: &[NodeId]) -> std::borrow::Cow<'a, Document> {
|
||||
let ids = with_their_art(doc, roots);
|
||||
if ids.is_empty() {
|
||||
return std::borrow::Cow::Borrowed(doc);
|
||||
}
|
||||
let mut view = doc.clone();
|
||||
for id in ids {
|
||||
// A dimension already gone (inside another one removed) needs nothing more.
|
||||
let _ = view.remove(id);
|
||||
}
|
||||
std::borrow::Cow::Owned(view)
|
||||
}
|
||||
|
||||
/// Called inside every edit, so dimensions and their undo history stay in step with the art they
|
||||
/// measure. Returns at once in documents without dimensions.
|
||||
pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
|
||||
@@ -320,17 +458,7 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
|
||||
// The art it measured was deleted, or rebuilt with other anchors, or no longer fits
|
||||
// (an ellipse that was a circle): it stays where it was, no longer linked, in this
|
||||
// same undo step, rather than attaching to a different edge.
|
||||
let mut unlinked = old.clone();
|
||||
unlinked.source = None;
|
||||
unlinked.moved = None;
|
||||
if let Some(v) = moved {
|
||||
let mut shifted = unlinked.clone();
|
||||
(shifted.a, shifted.b, shifted.vertex) = (shifted.a + v, shifted.b + v, shifted.vertex + v);
|
||||
if shifted.validate().is_ok() {
|
||||
unlinked = shifted;
|
||||
}
|
||||
}
|
||||
if replace(doc, id, unlinked).is_err()
|
||||
if replace(doc, id, unlinked(&old)).is_err()
|
||||
&& let Some(n) = doc.node_mut(id)
|
||||
{
|
||||
// Its recipe cannot be drawn again: its art stays as it is, as a plain group.
|
||||
|
||||
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand Appearance",
|
||||
["Object"],
|
||||
None,
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
can_expand,
|
||||
expand_appearance
|
||||
),
|
||||
@@ -109,9 +109,155 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
move_effect
|
||||
),
|
||||
cmd!(
|
||||
query "effect.deferredStatus",
|
||||
"Deferred Effects",
|
||||
[],
|
||||
None,
|
||||
"{} the live-effect plug-in stages the active document left undrawn: while a document is drawn on screen, the plug-in effects of its first view share a 2,000 ms budget (each run also keeps to its own 5,000 ms limit); a stage left out for want of time, or one that times out, fails or has no plug-in, draws its input art unchanged and stays listed until it gives a result (Effect › Refresh Deferred Effects, an edit to its input or parameters, or an export, which runs every stage under the per-call limit), or until its object is deleted or its effect is removed, moved or hidden (or its fill or stroke is hidden) → {budgetMs: 2000, effects: [{objectId (also an object in the art of a symbol, pattern, brush or opacity mask), effectIndex (in the object's effects, or in the fill's or stroke's), item? (the fill or stroke whose effect it is), pluginId, reason: budget|timeout|missing|failed|safeMode}]} (empty: none)",
|
||||
has_doc,
|
||||
deferred_status
|
||||
),
|
||||
cmd!(
|
||||
"effect.refreshDeferred",
|
||||
"Refresh Deferred Effects",
|
||||
["Effect"],
|
||||
None,
|
||||
"{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
|
||||
has_deferred,
|
||||
refresh_deferred
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The active document has deferred live-effect plug-in stages ([`deferred_status`]).
|
||||
fn has_deferred(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if deferred_effects(&st.doc, &st.plugin_effects).is_empty() { Err("no plug-in effect is deferred".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The objects the deferred stages of `fx` name, by id, each with whether it is in `d`'s layers.
|
||||
/// An object that is not is looked for in the art `d` draws from elsewhere, where live-effect
|
||||
/// plug-ins run too: the art of its symbols, patterns and brushes, and opacity masks.
|
||||
fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> std::collections::HashMap<u64, (Arc<Node>, bool)> {
|
||||
let mut out = std::collections::HashMap::new();
|
||||
let mut rest = Vec::new();
|
||||
for object in fx.list().into_iter().map(|x| x.stage.object) {
|
||||
match d.node_arc(NodeId(object)) {
|
||||
Some(n) => {
|
||||
out.insert(object, (n.clone(), true));
|
||||
}
|
||||
None => rest.push(object),
|
||||
}
|
||||
}
|
||||
if rest.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let symbols = d.symbols.iter().map(|s| &*s.art);
|
||||
let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a));
|
||||
let layers = d.layers.iter().map(|a| &**a);
|
||||
let mut look = |n: &Node| {
|
||||
if rest.contains(&n.id.0) {
|
||||
out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false));
|
||||
}
|
||||
};
|
||||
for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(a, &mut look);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Is plug-in `plugin`'s effect at `stage`'s place in `n` (`None`: no such object), and visible,
|
||||
/// on a visible fill or stroke when it is one's?
|
||||
fn stage_holds(n: Option<&Node>, stage: vectorcraft_plugins::deferred::Stage, plugin: &str) -> bool {
|
||||
let Some(n) = n else { return false };
|
||||
let list = match stage.item {
|
||||
None => Some(n.appearance.effects.as_slice()),
|
||||
Some(i) => n.appearance.items.get(i).filter(|it| it.visible()).map(|it| it.effects().as_slice()),
|
||||
};
|
||||
list.and_then(|l| l.get(stage.effect)).is_some_and(|e| e.visible && e.id == vectorcraft_plugins::effect::effect_id(plugin))
|
||||
}
|
||||
|
||||
/// Drops the records of `fx`'s stages whose object or plug-in effect is no longer at their place
|
||||
/// in `d` ([`stage_holds`]), and gives the objects of the others ([`stage_objects`]).
|
||||
fn prune(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> std::collections::HashMap<u64, (Arc<Node>, bool)> {
|
||||
let objects = stage_objects(d, fx);
|
||||
fx.retain(|stage, plugin| stage_holds(objects.get(&stage.object).map(|(n, _)| &**n), stage, plugin));
|
||||
objects
|
||||
}
|
||||
|
||||
/// The deferred stages of `d` as `effect.deferredStatus` lists them. The records of stages whose
|
||||
/// object or plug-in effect is no longer at their place in `d` are dropped first.
|
||||
fn deferred_effects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> Vec<Value> {
|
||||
prune(d, fx);
|
||||
fx.list()
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
let mut v = json!({"objectId": x.stage.object, "effectIndex": x.stage.effect, "pluginId": x.plugin, "reason": x.reason.name()});
|
||||
if let Some(i) = x.stage.item {
|
||||
v["item"] = json!(i);
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `effect.deferredStatus`.
|
||||
fn deferred_status(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
Ok(json!({"budgetMs": vectorcraft_plugins::deferred::OPENING_BUDGET_MS, "effects": deferred_effects(&st.doc, &st.plugin_effects)}))
|
||||
}
|
||||
|
||||
/// Draws `n` alone, small, as the canvas would (its live-effect plug-ins run inside the view that
|
||||
/// applies): what matters is that it is drawn, not its pixels. Is every part of it drawn, none left
|
||||
/// out for its size?
|
||||
fn draw_small(renderer: &mut vectorcraft_render::Renderer, doc: &Document, n: &Arc<Node>) -> bool {
|
||||
let Some(b) = n.geometric_bounds() else { return false };
|
||||
let scale = 64.0 / b.width().max(b.height()).max(1.0);
|
||||
let view = vectorcraft_geom::Affine::scale(scale) * vectorcraft_geom::Affine::translate((1.0 - b.x0, 1.0 - b.y0));
|
||||
renderer.stats = Default::default();
|
||||
renderer.render_node(doc, n, 66, 66, view);
|
||||
renderer.stats.culled == 0
|
||||
}
|
||||
|
||||
/// `effect.refreshDeferred`: each object of the document's layers is drawn again alone, small,
|
||||
/// inside the document's view, so its stages are run with the input they were deferred with; a
|
||||
/// hidden object, or one in a hidden layer or group, is not drawn. An object in the art of a
|
||||
/// symbol, pattern, brush or opacity mask runs where that art is used: the visible layers are
|
||||
/// drawn then. A stage input left out of a small drawing for its size stays deferred.
|
||||
fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone());
|
||||
let ids = super::named_ids(p)?;
|
||||
let objects = prune(&doc, &fx);
|
||||
if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
let ids: Option<Vec<u64>> = ids.map(|ids| ids.iter().map(|id| id.0).collect());
|
||||
let counts = fx.refresh(ids.as_deref(), |targets| {
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let mut whole = Vec::new();
|
||||
fx.view(|| {
|
||||
let mut elsewhere = false;
|
||||
for id in targets {
|
||||
match objects.get(id) {
|
||||
Some((n, true)) if doc.is_visible(NodeId(*id)) && draw_small(&mut renderer, &doc, n) => whole.push(*id),
|
||||
Some((_, false)) => elsewhere = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if elsewhere {
|
||||
for layer in doc.layers.iter().filter(|l| l.visible) {
|
||||
draw_small(&mut renderer, &doc, layer);
|
||||
}
|
||||
}
|
||||
});
|
||||
whole
|
||||
});
|
||||
Ok(json!({"refreshed": counts.refreshed, "stillDeferred": counts.still_deferred, "failed": counts.failed}))
|
||||
}
|
||||
|
||||
fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!(ids.iter().map(|i| i.0).collect::<Vec<_>>())
|
||||
}
|
||||
@@ -674,11 +820,19 @@ fn load_texture(params: &mut Value, cmd: &str) -> Result<()> {
|
||||
/// fills, strokes or effects of its own or such members, other objects with effects, or type with
|
||||
/// fills or strokes of its own?
|
||||
pub(crate) fn expandable(n: &Node) -> bool {
|
||||
expandable_except(n, &[])
|
||||
}
|
||||
|
||||
/// [`expandable`], leaving out the objects `skip` lists and what they hold.
|
||||
pub(crate) fn expandable_except(n: &Node, skip: &[NodeId]) -> bool {
|
||||
if skip.contains(&n.id) {
|
||||
return false;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } => false,
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => !n.appearance.is_basic() || vectorcraft_brush::has_brush(n),
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
!n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable(c))
|
||||
!n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable_except(c, skip))
|
||||
}
|
||||
NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(),
|
||||
NodeKind::Image(_) => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(),
|
||||
@@ -688,9 +842,11 @@ pub(crate) fn expandable(n: &Node) -> bool {
|
||||
|
||||
fn can_expand(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
let d = &s.doc().map_err(|e| e.to_string())?.doc;
|
||||
let ids = appearance_targets(s, &Value::Null).map_err(|e| e.to_string())?;
|
||||
if ids.iter().filter_map(|id| d.node(*id)).any(expandable) {
|
||||
let d = &s.doc().map_err(|e| e.to_string())?.doc;
|
||||
// A dimension selected with the art it measures is left as it is.
|
||||
let kept = super::dimension::with_their_art(d, &ids);
|
||||
if ids.iter().filter_map(|id| d.node(*id)).any(|n| expandable_except(n, &kept)) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("select (or target) objects whose appearance isn't basic".into())
|
||||
@@ -975,7 +1131,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
|
||||
// geometry it hasn't changed.
|
||||
if vectorcraft_plugins::safe_mode::active() {
|
||||
let d = &s.doc()?.doc;
|
||||
// A dimension selected with the art it measures is left as it is.
|
||||
let d = &*super::dimension::without_kept(&s.doc()?.doc, &roots);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
if roots.iter().filter_map(|id| d.node(*id)).any(|n| holds_plugin_effect(d, n, false, &mut seen)) {
|
||||
return Err(EngineError::Other("Expand Appearance: a plug-in effect in the selection can't be expanded in Safe Mode".into()));
|
||||
@@ -985,20 +1142,24 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let ids = s.edit("Expand Appearance", |d, _| {
|
||||
let before = d.clone();
|
||||
let mut ended = super::dimension::end_links(d, &roots);
|
||||
// A dimension selected with the art it measures keeps its own lines and label: it is out
|
||||
// of the document while the art expands.
|
||||
let lifted = super::dimension::lift(d, &roots);
|
||||
let kept = !lifted.is_empty();
|
||||
let ended = super::dimension::end_links(d, &roots);
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let mut out = vec![];
|
||||
let threaded = super::threads::frames(d);
|
||||
for id in &roots {
|
||||
expand_node(d, *id, &brushes, &mut out);
|
||||
}
|
||||
// A dimension whose source was replaced stays plain: its link no longer fits that art.
|
||||
ended.retain(|e| e.source_kept(&before, d));
|
||||
super::dimension::restore_unchanged(d, ended);
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was replaced stays where it was, no longer linked.
|
||||
super::dimension::restore_unchanged(&before, d, ended);
|
||||
// Outlined frames of threaded text leave their threads with the text they show; type that
|
||||
// stays type under a new id takes its frame's place.
|
||||
super::threads::leave_threads(d, &threaded);
|
||||
if out.is_empty() {
|
||||
if out.is_empty() || (kept && d.layers == before.layers) {
|
||||
return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into()));
|
||||
}
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?;
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//! gradient mesh, or solid strips / concentric ellipses, inside a clip group shaped like the object; a freeform
|
||||
//! gradient becomes a mesh shaped like the object. A pattern fill becomes the tiles it paints inside a clip
|
||||
//! group shaped like the object. Create Gradient Mesh shares the sampling. A dimension whose art
|
||||
//! Expand changes becomes a plain group of that art.
|
||||
//! Expand changes becomes a plain group of that art, except one selected with art it measures,
|
||||
//! which Expand leaves as it is.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
@@ -43,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand…",
|
||||
["Object"],
|
||||
None,
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art → {ids}",
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
has_selection,
|
||||
expand
|
||||
),
|
||||
@@ -55,7 +56,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
|
||||
has_selection,
|
||||
|s, _| {
|
||||
let e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
|
||||
let roots = selected_roots(s)?;
|
||||
let e = Expandable::of(&super::dimension::without_kept(&s.doc()?.doc, &roots), &roots);
|
||||
let mut info =
|
||||
json!({"object": e.object(), "fill": e.fill, "stroke": e.stroke, "gradient": e.gradient, "appearance": has_appearance(s)});
|
||||
if e.symbols {
|
||||
@@ -74,7 +76,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// (#3089); `object.expand` itself still bakes them.
|
||||
pub fn has_appearance(s: &Session) -> bool {
|
||||
let (Ok(st), Ok(roots)) = (s.doc(), selected_roots(s)) else { return false };
|
||||
roots.iter().filter_map(|r| st.doc.node(*r)).any(super::effectcmd::expandable)
|
||||
// A dimension selected with the art it measures is left as it is.
|
||||
let kept = super::dimension::with_their_art(&st.doc, &roots);
|
||||
roots.iter().filter_map(|r| st.doc.node(*r)).any(|n| super::effectcmd::expandable_except(n, &kept))
|
||||
}
|
||||
|
||||
/// Every placed document in `roots` of `d` (at any depth) replaced by an editable copy of the art it
|
||||
@@ -241,9 +245,18 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stroke = switch_or(p, "stroke", true, C)?;
|
||||
let to = GradientTo::parse(p)?;
|
||||
let from = s.doc()?.history.undo.len();
|
||||
let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
|
||||
// Before anything expands: outlining the art a dimension measures would leave the dimension unlinked.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let selected = s.doc()?.selection.objects.clone();
|
||||
// A dimension selected with the art it measures keeps its own lines and label: it is out of the
|
||||
// document while the art expands, so no step below reaches it.
|
||||
let roots = selected_roots(s)?;
|
||||
let mut lifted = vec![];
|
||||
if !super::dimension::with_their_art(&before, &roots).is_empty() {
|
||||
lifted = s.edit("Expand", |d, _| Ok(super::dimension::lift(d, &roots)))?;
|
||||
}
|
||||
let kept: Vec<NodeId> = lifted.iter().map(super::dimension::Lifted::id).collect();
|
||||
let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
|
||||
let mut ended = vec![];
|
||||
end_dimension_links(s, &mut ended)?;
|
||||
let rev0 = s.doc()?.revision;
|
||||
@@ -339,14 +352,25 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.doc()?.revision == rev0 {
|
||||
return Err(EngineError::Other("Expand: nothing to expand".into()));
|
||||
}
|
||||
if !ended.is_empty() {
|
||||
// A dimension whose source Expand replaced stays plain: its link no longer fits that art.
|
||||
let after = s.doc()?.doc.clone();
|
||||
ended.retain(|e| e.source_kept(&before, &after));
|
||||
s.edit("Expand", |d, _| {
|
||||
super::dimension::restore_unchanged(d, std::mem::take(&mut ended));
|
||||
if !ended.is_empty() || !lifted.is_empty() {
|
||||
s.edit("Expand", |d, sel| {
|
||||
if !lifted.is_empty() {
|
||||
super::dimension::put_back(d, lifted);
|
||||
// The dimensions put back follow what Expand made of the art they measure: a
|
||||
// dimension whose art no longer fits its link stays where it was, no longer linked.
|
||||
super::dimension::refresh(&before, d)?;
|
||||
let mut ids = sel.objects.clone();
|
||||
let again: Vec<NodeId> = kept.iter().copied().filter(|id| selected.contains(id) && !ids.contains(id)).collect();
|
||||
ids.extend(again);
|
||||
sel.set(ids);
|
||||
}
|
||||
// A dimension whose source Expand replaced stays where it was, no longer linked.
|
||||
super::dimension::restore_unchanged(&before, d, ended);
|
||||
Ok(())
|
||||
})?;
|
||||
if !kept.is_empty() && s.doc()?.doc.layers == before.layers {
|
||||
return Err(EngineError::Other("Expand: nothing to expand".into()));
|
||||
}
|
||||
}
|
||||
squash(s, from, "Expand");
|
||||
Ok(json!({ "ids": s.doc()?.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
|
||||
@@ -270,7 +270,9 @@ fn flattened(src: &Document, at: usize, id: NodeId) -> Result<Option<Flat>> {
|
||||
let pt = im.xf.determinant().abs().sqrt();
|
||||
let ppi = if pt.is_finite() && pt > 0.0 { (72.0 / pt).clamp(MIN_PPI, MAX_PPI) } else { MIN_PPI };
|
||||
let area = (bounds.width() * bounds.height()).max(1.0);
|
||||
let scale = (ppi / 72.0).min((super::super::menucmds::MAX_PIXELS / area).sqrt());
|
||||
// No side longer than the renderer draws (rounded up to whole pixels below).
|
||||
let longest = (f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0) / bounds.width().max(bounds.height()).max(1.0);
|
||||
let scale = (ppi / 72.0).min((super::super::menucmds::MAX_PIXELS / area).sqrt()).min(longest);
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -507,7 +507,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// document keeps its text as saved), and every frame of a thread takes its first frame's
|
||||
// Optical Margin Alignment setting and writing direction. When that changes the direction of a
|
||||
// frame of a restored document, the story flows through that frame's thread again. Threaded
|
||||
// frames keep their size: Auto Size is off for them.
|
||||
// frames keep their size: Auto Size is off for them. The story is laid out in the document's
|
||||
// own composite fonts.
|
||||
let fonts = if doc.text_threads.is_empty() { Default::default() } else { doc.composite_fonts.clone() };
|
||||
let lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&fonts);
|
||||
if !doc.text_threads.is_empty() && !restored {
|
||||
crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc);
|
||||
} else if !doc.text_threads.is_empty() {
|
||||
@@ -518,6 +521,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// paragraph's first-line indent and list marker.
|
||||
crate::cmd::threads::mark_continued(&mut doc);
|
||||
}
|
||||
drop(lent);
|
||||
if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) {
|
||||
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays);
|
||||
}
|
||||
|
||||
@@ -484,6 +484,9 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
|
||||
fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Option<PathData>, o: &FlattenOptions) -> Result<Raster> {
|
||||
let mut scale = ppi / 72.0;
|
||||
scale = scale.min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt());
|
||||
// No side longer than the renderer draws: the image grows by a pixel on each side and is
|
||||
// rounded up to whole pixels below.
|
||||
scale = scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0));
|
||||
let px = 1.0 / scale;
|
||||
let rect = rect.inflate(px, px);
|
||||
let clip = clip.map(|c| Some(po::offset_path(&c, px, po::Join::Miter, 4.0)).filter(|g| !g.is_empty()).unwrap_or(c));
|
||||
|
||||
@@ -10,7 +10,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flatten Transparency…",
|
||||
["Object"],
|
||||
None,
|
||||
"{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach (only where a clip group's or clipping layer's clipping path shows them, over its fill; transparent objects such a path hides entirely are removed); objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach; an image larger than 64 Mpx or 32,768 px a side is made at a lower resolution), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach (only where a clip group's or clipping layer's clipping path shows them, over its fill; transparent objects such a path hides entirely are removed); objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
has_doc,
|
||||
flatten
|
||||
),
|
||||
|
||||
@@ -43,8 +43,8 @@ use generate::generate;
|
||||
#[cfg(test)]
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
capture_label_styles, capture_series_object_opacity, capture_series_opacity, capture_series_paints, capture_series_top_paints, paint_targets,
|
||||
series_object_opacity_differs, shown_paint,
|
||||
capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity,
|
||||
capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2,7 +2,8 @@ use super::axis::{LABEL_SIZE, MAX_CATEGORY_TICKS, MAX_TICK_MARKS, one_line, rada
|
||||
use super::columns::{Allowance, ColumnArt, column_art, column_designs};
|
||||
use super::data::fmt_value;
|
||||
use super::labels::{
|
||||
Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, filled_lines_on, label_size, label_width, polyline, recolour_text, runs, shadow_of,
|
||||
Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, filled_lines_on, label_extra_height, label_shift, label_size, label_width, polyline,
|
||||
recolour_text, runs, shadow_of,
|
||||
};
|
||||
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
|
||||
use super::series::{series_marks, with_series_opacity};
|
||||
@@ -901,18 +902,21 @@ impl<'a> Plot<'a> {
|
||||
|
||||
fn legend_label(&mut self, (x, y): (f64, f64), label: &str) -> Arc<Node> {
|
||||
let ls = self.ls;
|
||||
let (dx, dy) = label_shift(&self.g.label_styles, label, self.b.d.setup.system_layout);
|
||||
let (x, y) = (x + dx, y + dy);
|
||||
self.b.label(Role::Legend, Point::new(x + 12.0, y + 7.5 + (ls - LABEL_SIZE) * 0.35), label, Justify::Left, false)
|
||||
}
|
||||
|
||||
/// Add Legend Across Top: swatch and label after swatch and label, in rows as wide as the plot, the last row
|
||||
/// just above it.
|
||||
fn legend_across_top(&mut self) -> Vec<Arc<Node>> {
|
||||
let (g, r, ls) = (self.g, self.r, self.ls);
|
||||
let (g, r, ls, system_layout) = (self.g, self.r, self.ls, self.b.d.setup.system_layout);
|
||||
let entries: Vec<(usize, String)> = (0..self.legend_series()).map(|s| (s, self.legend_text(s))).filter(|(_, l)| !blank_label(l)).collect();
|
||||
let mut rows: Vec<Vec<(usize, String, f64)>> = vec![vec![]];
|
||||
let mut rows: Vec<Vec<(usize, String, f64, f64)>> = vec![vec![]];
|
||||
let mut used = 0.0;
|
||||
for (s, label) in entries {
|
||||
let w = 12.0 + label_width(&g.label_styles, &label) + 12.0;
|
||||
let w = 12.0 + label_width(&g.label_styles, &label, system_layout) + 12.0;
|
||||
let h = ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&g.label_styles, &label, system_layout);
|
||||
// The gap after an entry may run past the plot's edge.
|
||||
if used + w - 12.0 > r.width() && rows.last().is_some_and(|row| !row.is_empty()) {
|
||||
rows.push(vec![]);
|
||||
@@ -920,10 +924,10 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
used += w;
|
||||
if let Some(row) = rows.last_mut() {
|
||||
row.push((s, label, w));
|
||||
row.push((s, label, w, h));
|
||||
}
|
||||
}
|
||||
let height = |row: &[(usize, String, f64)]| ls * 1.8 * row.iter().map(|(_, l, _)| l.split('|').count()).max().unwrap_or(1) as f64;
|
||||
let height = |row: &[(usize, String, f64, f64)]| row.iter().map(|(.., h)| *h).fold(ls * 1.8, f64::max);
|
||||
// Above the plot and anything drawn over it (radar and stacked-pie labels).
|
||||
let top = self.b.out.iter().chain(self.on_top.iter()).filter_map(|n| n.geometric_bounds()).map(|bb| bb.y0).fold(r.y0, f64::min);
|
||||
let top = self.bars_reach.map_or(top, |b| top.min(b.y0));
|
||||
@@ -931,7 +935,7 @@ impl<'a> Plot<'a> {
|
||||
let mut labels = vec![];
|
||||
for row in &rows {
|
||||
let mut x = r.x0;
|
||||
for (s, label, w) in row {
|
||||
for (s, label, w, _) in row {
|
||||
self.legend_swatch(*s, (x, y));
|
||||
labels.push(self.legend_label((x, y), label));
|
||||
x += w;
|
||||
@@ -954,7 +958,7 @@ impl<'a> Plot<'a> {
|
||||
y += ls * 1.8;
|
||||
continue;
|
||||
}
|
||||
y += ls * 1.8 * label.split('|').count() as f64;
|
||||
y += ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&self.g.label_styles, &label, self.b.d.setup.system_layout);
|
||||
self.legend_swatch(s, (x, row_y));
|
||||
labels.push(self.legend_label((x, row_y), &label));
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use super::{
|
||||
pub(super) struct Gen<'a> {
|
||||
pub(super) d: &'a mut Document,
|
||||
pub(super) out: Vec<Arc<Node>>,
|
||||
/// The labels' kept character styles.
|
||||
/// The labels' kept character styles and paragraph attributes.
|
||||
pub(super) styles: &'a vectorcraft_doc::LabelStyles,
|
||||
/// What the column designs may still add.
|
||||
pub(super) columns: Allowance,
|
||||
@@ -45,6 +45,34 @@ pub(super) fn label_style(styles: &vectorcraft_doc::LabelStyles, role: Role) ->
|
||||
st
|
||||
}
|
||||
|
||||
/// The paragraph attributes labels of `role` are set with: the kept ones, else the defaults. The caller sets the
|
||||
/// alignment.
|
||||
pub(super) fn label_para(styles: &vectorcraft_doc::LabelStyles, role: Role) -> vectorcraft_doc::ParaStyle {
|
||||
let mut para = kept_para(styles, role).cloned().unwrap_or_default();
|
||||
// A file's attributes within the limits the Paragraph controls keep to (they are copied onto every label).
|
||||
para.keep_spacing_in_range();
|
||||
para
|
||||
}
|
||||
|
||||
/// The paragraph attributes labels of `role` keep, if any.
|
||||
fn kept_para(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vectorcraft_doc::ParaStyle> {
|
||||
match role {
|
||||
Role::Value => styles.values_para.as_ref(),
|
||||
Role::Category => styles.categories_para.as_ref(),
|
||||
Role::Legend => styles.legend_para.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The anti-aliasing method labels of `role` are drawn with: the kept one, else Sharp.
|
||||
pub(super) fn label_anti_alias(styles: &vectorcraft_doc::LabelStyles, role: Role) -> vectorcraft_doc::text::TypeAntiAlias {
|
||||
let kept = match role {
|
||||
Role::Value => styles.values_anti_alias,
|
||||
Role::Category => styles.categories_anti_alias,
|
||||
Role::Legend => styles.legend_anti_alias,
|
||||
};
|
||||
kept.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// How big labels of `role` are set: a kept style's size, else 9 pt. The labels' spacing follows it.
|
||||
pub(super) fn label_size(styles: &vectorcraft_doc::LabelStyles, role: Role) -> f64 {
|
||||
label_style(styles, role).size
|
||||
@@ -61,19 +89,39 @@ impl Gen<'_> {
|
||||
self.path(PathData::from_bezpath(&bp), Paint::None, Paint::solid(Color::BLACK), 0.5)
|
||||
}
|
||||
pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc<Node> {
|
||||
let t = self.text_object(role, at, s, justify);
|
||||
Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t))))
|
||||
}
|
||||
/// Label `s` of `role` set at `at` and laid out, not yet in the document.
|
||||
fn text_object(&self, role: Role, at: Point, s: &str, justify: Justify) -> TextObject {
|
||||
let style = label_style(self.styles, role);
|
||||
let mut t = TextObject::point(at, s, style);
|
||||
t.para = label_para(self.styles, role);
|
||||
t.anti_alias = label_anti_alias(self.styles, role);
|
||||
t.para.justify = justify;
|
||||
t.system_layout = self.d.setup.system_layout;
|
||||
refresh_bounds(&mut t);
|
||||
Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t))))
|
||||
t
|
||||
}
|
||||
/// A category or series label: a `|` in it starts a new line (Add graph labels). `middle`: the lines are centred
|
||||
/// on `at` (labels beside an axis or in a wedge) instead of running down from it.
|
||||
pub(super) fn label(&mut self, role: Role, at: Point, s: &str, justify: Justify, middle: bool) -> Arc<Node> {
|
||||
let lines = s.split('|').count();
|
||||
let at = if middle { Point::new(at.x, at.y - (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0) } else { at };
|
||||
self.text(role, at, &s.replace('|', "\n"), justify)
|
||||
// Default leading puts the first and last baselines this far above and below `at`.
|
||||
let half = (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0;
|
||||
let start = if middle { Point::new(at.x, at.y - half) } else { at };
|
||||
let mut t = self.text_object(role, start, &s.replace('|', "\n"), justify);
|
||||
// Kept leading or paragraph spacing moves the lines: put the middle of the first and last baselines on `at`. An
|
||||
// empty line has no baseline: an empty first or last line leaves the label where the default leading puts it.
|
||||
if middle && kept_para(self.styles, role).is_some() {
|
||||
let ys: Vec<f64> = t.baselines().map(|(a, _)| a.y).collect();
|
||||
let ends_set = s.split('|').next().is_some_and(|l| !l.is_empty()) && s.split('|').next_back().is_some_and(|l| !l.is_empty());
|
||||
let set = s.split('|').filter(|l| !l.is_empty()).count();
|
||||
if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ends_set && ys.len() == set) {
|
||||
t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf;
|
||||
}
|
||||
}
|
||||
Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t))))
|
||||
}
|
||||
pub(super) fn group(&mut self, name: &str, children: Vec<Arc<Node>>) -> Arc<Node> {
|
||||
let mut g = Node::group(self.d.alloc_id(), children);
|
||||
@@ -162,12 +210,47 @@ pub(super) fn shadow_of(d: &mut Document, n: &Node) -> Arc<Node> {
|
||||
Arc::new(d.reid(&c))
|
||||
}
|
||||
|
||||
/// How wide label `s` is set (its widest line), without adding it to a document.
|
||||
pub(super) fn label_width(styles: &vectorcraft_doc::LabelStyles, s: &str) -> f64 {
|
||||
/// The bounds of legend label `s` set from the origin with paragraph attributes `para` and the document's System
|
||||
/// Layout setting `system_layout`, as [`Gen::text`] sets it, without adding it to a document.
|
||||
fn legend_label_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str, para: vectorcraft_doc::ParaStyle, system_layout: bool) -> Option<Rect> {
|
||||
let style = label_style(styles, Role::Legend);
|
||||
let mut t = TextObject::point(Point::ZERO, &s.replace('|', "\n"), style);
|
||||
t.para = para;
|
||||
t.para.justify = Justify::Left;
|
||||
t.system_layout = system_layout;
|
||||
refresh_bounds(&mut t);
|
||||
Node::new(NodeId(0), NodeKind::Text(Box::new(t))).geometric_bounds().map_or(0.0, |b| b.width())
|
||||
Node::new(NodeId(0), NodeKind::Text(Box::new(t))).geometric_bounds()
|
||||
}
|
||||
|
||||
/// How far label `s` reaches right of where it starts (its widest line and any indent), after the legend moves it right
|
||||
/// by [`label_shift`], without adding it to a document.
|
||||
pub(super) fn label_width(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> f64 {
|
||||
legend_label_bounds(styles, s, label_para(styles, Role::Legend), system_layout)
|
||||
.map_or(0.0, |b| (b.x1 + label_shift(styles, s, system_layout).0).max(0.0))
|
||||
}
|
||||
|
||||
/// The bounds of legend label `s` set with its kept paragraph attributes and with the defaults, when it has kept ones.
|
||||
fn kept_and_default_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> Option<(Rect, Rect)> {
|
||||
styles.legend_para.as_ref()?;
|
||||
Some((
|
||||
legend_label_bounds(styles, s, label_para(styles, Role::Legend), system_layout)?,
|
||||
legend_label_bounds(styles, s, vectorcraft_doc::ParaStyle::default(), system_layout)?,
|
||||
))
|
||||
}
|
||||
|
||||
/// How much further left and further up legend label `s` reaches with its kept paragraph attributes than with the
|
||||
/// defaults (a negative indent or negative spacing), so the legend moves it right and down by that much and it stays
|
||||
/// clear of its swatch and of the entries before it.
|
||||
pub(super) fn label_shift(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> (f64, f64) {
|
||||
kept_and_default_bounds(styles, s, system_layout)
|
||||
.map_or((0.0, 0.0), |(kept, default)| ((default.x0 - kept.x0).max(0.0), (default.y0 - kept.y0).max(0.0)))
|
||||
}
|
||||
|
||||
/// How much further down legend label `s` reaches with its kept paragraph attributes than with the defaults (more
|
||||
/// leading, or space before or after), after the legend moves it down by [`label_shift`], so the legend makes room
|
||||
/// for it.
|
||||
pub(super) fn label_extra_height(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> f64 {
|
||||
kept_and_default_bounds(styles, s, system_layout).map_or(0.0, |(kept, default)| (kept.y1 + (default.y0 - kept.y0).max(0.0) - default.y1).max(0.0))
|
||||
}
|
||||
|
||||
/// A label with nothing to show (empty, or only `|` line breaks).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use vectorcraft_color::BlendMode;
|
||||
|
||||
use super::axis::radar_axis;
|
||||
use super::labels::{Role, filled_lines_on, label_style};
|
||||
use super::labels::{Role, filled_lines_on, label_para, label_style};
|
||||
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
|
||||
|
||||
// ---------- generation ----------
|
||||
@@ -406,23 +406,34 @@ fn graph_labels(doc: &Document) -> HashMap<NodeId, (NodeId, Role)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels
|
||||
/// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or
|
||||
/// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so
|
||||
/// they undo together. Returns whether a kept style changed.
|
||||
pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool {
|
||||
if ids.is_empty() {
|
||||
return false;
|
||||
}
|
||||
/// Keep the anti-aliasing method `method` given to graph labels `ids` for every label of their kind, as
|
||||
/// [`capture_label_styles`] keeps a formatting change. Returns whether a kept method changed.
|
||||
pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], method: vectorcraft_doc::text::TypeAntiAlias) -> bool {
|
||||
let labels = graph_labels(doc);
|
||||
if labels.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut kinds: Vec<(NodeId, Role)> = ids.iter().filter_map(|id| labels.get(id).copied()).collect();
|
||||
kinds.sort_by_key(|(g, r)| (g.0, *r as u8));
|
||||
kinds.dedup();
|
||||
let mut changed = false;
|
||||
for (graph, role) in kinds {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let slot = match role {
|
||||
Role::Value => &mut spec.label_styles.values_anti_alias,
|
||||
Role::Category => &mut spec.label_styles.categories_anti_alias,
|
||||
Role::Legend => &mut spec.label_styles.legend_anti_alias,
|
||||
};
|
||||
changed |= *slot != Some(method);
|
||||
*slot = Some(method);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels
|
||||
/// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or
|
||||
/// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so
|
||||
/// they undo together. Returns whether a kept style changed.
|
||||
pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool {
|
||||
let mut changed = false;
|
||||
for (graph, role) in label_kinds(doc, ids) {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let mut style = label_style(&spec.label_styles, role);
|
||||
change(&mut style);
|
||||
@@ -437,6 +448,42 @@ pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &
|
||||
changed
|
||||
}
|
||||
|
||||
/// Keep a paragraph change made to all of the text of graph labels `ids` (Paragraph, on the whole graph or on labels
|
||||
/// picked with Group Selection) for every label of their kind, as [`capture_label_styles`] does for character
|
||||
/// formats. Returns whether kept attributes changed, or the error `change` returns for the kept attributes.
|
||||
pub(crate) fn capture_label_paragraphs(
|
||||
doc: &mut Document,
|
||||
ids: &[NodeId],
|
||||
change: &dyn Fn(&mut vectorcraft_doc::ParaStyle) -> Result<()>,
|
||||
) -> Result<bool> {
|
||||
let mut changed = false;
|
||||
for (graph, role) in label_kinds(doc, ids) {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let mut para = label_para(&spec.label_styles, role);
|
||||
change(&mut para)?;
|
||||
let slot = match role {
|
||||
Role::Value => &mut spec.label_styles.values_para,
|
||||
Role::Category => &mut spec.label_styles.categories_para,
|
||||
Role::Legend => &mut spec.label_styles.legend_para,
|
||||
};
|
||||
changed |= slot.as_ref() != Some(¶);
|
||||
*slot = Some(para);
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// The graphs and kinds of label among `ids`, each once.
|
||||
fn label_kinds(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role)> {
|
||||
if ids.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
let mut kinds: Vec<(NodeId, Role)> = ids.iter().filter_map(|id| labels.get(id).copied()).collect();
|
||||
kinds.sort_by_key(|(g, r)| (g.0, *r as u8));
|
||||
kinds.dedup();
|
||||
kinds
|
||||
}
|
||||
|
||||
/// The series a command on graph `id` (of `count` series) applies to: `seriesIndexes`, else, with no `id` param, a
|
||||
/// selection made only of this graph's series (Group Selection). Empty: the whole graph.
|
||||
pub(super) fn picked_series(s: &Session, p: &Value, id: NodeId, count: usize, cmd: &str) -> Result<Vec<usize>> {
|
||||
|
||||
@@ -4055,6 +4055,45 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() {
|
||||
assert_eq!(spec(&s, id).label_styles, vectorcraft_doc::LabelStyles::default());
|
||||
}
|
||||
|
||||
/// An anti-aliasing method given to one category label is kept for every category label when the graph is drawn
|
||||
/// again, through save and open, and undoes with the change.
|
||||
#[test]
|
||||
fn a_graph_labels_anti_aliasing_method_survives_it_being_drawn_again() {
|
||||
use vectorcraft_doc::text::TypeAntiAlias;
|
||||
let methods = |s: &Session, id: NodeId| -> Vec<(String, TypeAntiAlias)> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let mut out = vec![];
|
||||
for g in ["Axes", "Legend"] {
|
||||
for c in group(&n, g).children().unwrap() {
|
||||
if let NodeKind::Text(t) = &c.kind {
|
||||
out.push((t.plain_text(), t.anti_alias));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let c = text_id(&s, id, "Axes", "Q2");
|
||||
s.execute("text.setFormat", &json!({"ids": [c.0], "antiAlias": "strong"})).unwrap();
|
||||
label_looks(&mut s, id);
|
||||
let drawn = methods(&s, id);
|
||||
let method = |t: &str| drawn.iter().find(|(x, _)| x == t).map(|(_, m)| *m).unwrap();
|
||||
assert_eq!((method("Q1"), method("Q3")), (TypeAntiAlias::Strong, TypeAntiAlias::Strong), "every category label: {drawn:?}");
|
||||
assert_eq!((method("0"), method("2024")), (TypeAntiAlias::Sharp, TypeAntiAlias::Sharp), "other labels: {drawn:?}");
|
||||
// One undo takes the data change back, the next the method and the kept method together.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.categories_anti_alias, None);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
let path = vectorcraft_testkit::temp_dir("graph-label-anti-alias").join("labels.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.categories_anti_alias, Some(TypeAntiAlias::Strong));
|
||||
assert!(serde_json::to_value(GraphSpec::default()).unwrap().get("labelStyles").is_none());
|
||||
}
|
||||
|
||||
/// A stroke given to all of a graph's text without a weight is kept at 1 pt, as `paint.setStroke` keeps it.
|
||||
#[test]
|
||||
fn a_stroke_given_to_the_whole_graphs_text_is_kept_at_1_pt() {
|
||||
@@ -4219,3 +4258,243 @@ fn csv_round_trip_keeps_blank_row_in_single_column_graph() {
|
||||
assert!(c.is_empty());
|
||||
assert_eq!(r, g.cells());
|
||||
}
|
||||
|
||||
/// Each generated label's text, paragraph attributes and alignment.
|
||||
fn label_paras(s: &Session, id: NodeId) -> Vec<(String, vectorcraft_doc::ParaStyle)> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let mut out = vec![];
|
||||
for name in ["Axes", "Legend"] {
|
||||
for c in group(&n, name).children().unwrap() {
|
||||
if let NodeKind::Text(t) = &c.kind {
|
||||
out.push((t.plain_text(), t.para.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_formats_are_kept_when_the_graph_is_drawn_again() {
|
||||
use vectorcraft_doc::{Composer, ParaDirection, text::Kashida};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let aligned: Vec<_> = label_paras(&s, id).into_iter().map(|(t, p)| (t, p.justify)).collect();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"composer": "singleLine", "kashida": "long", "direction": "rightToLeft", "wordSpacing": [70, 90, 120]}))
|
||||
.unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
let paras = label_paras(&s, id);
|
||||
assert!(!paras.is_empty());
|
||||
for (text, p) in ¶s {
|
||||
assert_eq!(p.composer, Composer::SingleLine, "{text}");
|
||||
assert_eq!(p.kashida, Kashida::Long, "{text}");
|
||||
assert_eq!(p.direction, Some(ParaDirection::RightToLeft), "{text}");
|
||||
assert_eq!(p.justification.word_spacing, [70.0, 90.0, 120.0], "{text}");
|
||||
}
|
||||
// The graph still aligns each label to its place.
|
||||
assert_eq!(paras.iter().map(|(t, p)| (t.clone(), p.justify)).collect::<Vec<_>>(), aligned);
|
||||
// One kind of label: only that kind keeps it, also through save and open.
|
||||
let col = graph(&mut s, "column");
|
||||
let v = text_id(&s, col, "Axes", "4");
|
||||
s.execute("select.set", &json!({"ids": [v.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"composer": "singleLine"})).unwrap();
|
||||
let path = vectorcraft_testkit::temp_dir("graph-label-paras").join("labels.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [col.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": col.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
let paras = label_paras(&s, col);
|
||||
let composer = |t: &str| paras.iter().find(|(x, _)| x == t).unwrap().1.composer;
|
||||
assert_eq!(composer("0"), Composer::SingleLine, "every value axis number");
|
||||
assert_eq!(composer("Q1"), Composer::default(), "category labels as they were");
|
||||
assert_eq!(composer("2024"), Composer::default(), "legend labels as they were");
|
||||
// Part of a label's text: nothing kept.
|
||||
let q = text_id(&s, col, "Axes", "Q2");
|
||||
s.execute("select.set", &json!({"ids": [q.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"kashida": "short", "start": 0, "end": 1})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": col.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
assert!(label_paras(&s, col).iter().all(|(_, p)| p.kashida == Kashida::default()));
|
||||
// Spacing that would be out of order in the kept attributes is refused, even when it is in order on the label.
|
||||
let v = text_id(&s, col, "Axes", "4");
|
||||
s.execute("select.set", &json!({"ids": [col.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"wordSpacing": [60, 70, 80]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [v.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"wordSpacing": [80, 100, 133], "start": 0, "end": 1})).unwrap();
|
||||
assert!(s.execute("text.setFormat", &json!({"wordSpacing": {"min": 90}})).is_err());
|
||||
let kept = spec(&s, col).label_styles.values_para.unwrap();
|
||||
assert_eq!(kept.justification.word_spacing, [60.0, 70.0, 80.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legend_across_top_spaces_its_labels_by_their_kept_paragraph_settings() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("graph.setType", &json!({"legendAcrossTop": true})).unwrap();
|
||||
let l = text_id(&s, id, "Legend", "2024");
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"leftIndent": 40})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "2024")).unwrap();
|
||||
let label = label.geometric_bounds().unwrap();
|
||||
let next = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap();
|
||||
assert!(next.x0 >= label.x1, "the next swatch starts after the indented label: {label:?} {next:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_centered_label_with_kept_leading_stays_centered_when_the_graph_is_drawn_again() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",2024,2025\nQ|1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
let id = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let middle = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let label = group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "Q\n1")).unwrap();
|
||||
let b = label.geometric_bounds().unwrap();
|
||||
(b.y0 + b.y1) / 2.0
|
||||
};
|
||||
let before = middle(&s);
|
||||
let l = text_id(&s, id, "Axes", "Q\n1");
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"autoLeading": 400, "spaceBefore": 6})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let after = middle(&s);
|
||||
assert!((after - before).abs() < 0.01, "the two-line category label keeps its middle: {before} {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_centered_label_with_an_empty_middle_line_and_kept_leading_stays_centered() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",2024,2025\nQ||1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
let id = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let middle = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let label =
|
||||
group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "Q\n\n1")).unwrap();
|
||||
let b = label.geometric_bounds().unwrap();
|
||||
(b.y0 + b.y1) / 2.0
|
||||
};
|
||||
let before = middle(&s);
|
||||
let l = text_id(&s, id, "Axes", "Q\n\n1");
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let after = middle(&s);
|
||||
assert!((after - before).abs() < 0.01, "the three-line category label keeps its middle: {before} {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legend_across_top_measures_its_labels_with_system_layout() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("type.systemLayout", &json!({"on": true})).unwrap();
|
||||
// Each `i` at 2 pt advances a whole point with System Layout, far more than its own width.
|
||||
let name = "i".repeat(60);
|
||||
let csv = format!(",{name},2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6");
|
||||
let id = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("graph.setType", &json!({"legendAcrossTop": true})).unwrap();
|
||||
let l = text_id(&s, id, "Legend", &name);
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"size": 2})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"leftIndent": 1})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == name)).unwrap();
|
||||
let label = label.geometric_bounds().unwrap();
|
||||
let next = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap();
|
||||
assert!(next.x0 >= label.x1, "the next swatch starts after the label set with System Layout: {label:?} {next:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legend_label_with_a_kept_negative_indent_stays_clear_of_its_swatch() {
|
||||
for across_top in [true, false] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("graph.setType", &json!({"legendAcrossTop": across_top})).unwrap();
|
||||
let l = text_id(&s, id, "Legend", "2025");
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"leftIndent": -40})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let bounds = |text: &str| {
|
||||
let label =
|
||||
group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap();
|
||||
label.geometric_bounds().unwrap()
|
||||
};
|
||||
let (first, label) = (bounds("2024"), bounds("2025"));
|
||||
let swatch = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap();
|
||||
assert!(label.x0 >= swatch.x1, "the label starts after its swatch (across top: {across_top}): {swatch:?} {label:?}");
|
||||
if across_top {
|
||||
assert!(swatch.x0 >= first.x1, "the swatch starts after the label before it: {first:?} {swatch:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legend_makes_room_for_the_kept_leading_of_its_labels() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",20|24,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
let id = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let l = text_id(&s, id, "Legend", "20\n24");
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let bounds = |text: &str| {
|
||||
let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap();
|
||||
label.geometric_bounds().unwrap()
|
||||
};
|
||||
let (first, next) = (bounds("20\n24"), bounds("2025"));
|
||||
assert!(next.y0 >= first.y1, "the next legend label starts below the first one: {first:?} {next:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legend_label_with_kept_negative_space_before_stays_below_the_entry_above_it() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",2024,20|25\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
let id = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let l = text_id(&s, id, "Legend", "20\n25");
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"spaceBefore": -60})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let bounds = |text: &str| {
|
||||
let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap();
|
||||
label.geometric_bounds().unwrap()
|
||||
};
|
||||
let (first, next) = (bounds("2024"), bounds("20\n25"));
|
||||
assert!(next.y0 >= first.y1, "the second legend label starts below the first one: {first:?} {next:?}");
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rasterize…",
|
||||
["Object"],
|
||||
None,
|
||||
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
|
||||
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
|
||||
has_selection,
|
||||
rasterize
|
||||
),
|
||||
@@ -670,7 +670,11 @@ fn render_pixels(
|
||||
opts: &vectorcraft_render::RenderOptions,
|
||||
color: RasterColorModel,
|
||||
) -> Result<(vectorcraft_render::Rendered, Option<&'static str>)> {
|
||||
if region.width() * region.height() * scale * scale > MAX_PIXELS || region.width() * scale > 65535.0 || region.height() * scale > 65535.0 {
|
||||
// No side longer than the renderer draws: it would cut the image off there. The sides are
|
||||
// measured in the renderer's whole pixels.
|
||||
let side = vectorcraft_render::MAX_RASTER_SIDE;
|
||||
let (w, h) = vectorcraft_render::region_pixels(region, scale);
|
||||
if region.width() * region.height() * scale * scale > MAX_PIXELS || w > side || h > side {
|
||||
return Err(EngineError::Other("image would be too large; lower the resolution".into()));
|
||||
}
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Outline Stroke",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{} replace stroked paths with filled outlines; a dimension whose lines are outlined, or selected with the art it measures when that art is outlined, becomes a plain group of its art → {ids}",
|
||||
"{} replace stroked paths with filled outlines; a dimension whose lines are outlined becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines stay as they are, and if the outlined art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
has_selection,
|
||||
outline_stroke
|
||||
),
|
||||
@@ -719,7 +719,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
/// Pathfinder panel › Trap ([`vectorcraft_render::effects::trap`]): the traps between the selected
|
||||
/// objects' leaf shapes, as one group of overprinting paths above the topmost selected object.
|
||||
fn trap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, traps};
|
||||
use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, try_traps};
|
||||
const ID: &str = "object.pathfinder.trap";
|
||||
let mut q = p.clone();
|
||||
if let Some(t) = length_given(p, "thickness", ID)? {
|
||||
@@ -758,7 +758,12 @@ fn trap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if sources.iter().filter(|s| s.fill.color().is_some()).count() < 2 {
|
||||
return Err(EngineError::Other("Trap: select two or more objects filled with solid colours".into()));
|
||||
}
|
||||
let made = traps(&sources, &options);
|
||||
let Some(made) = try_traps(&sources, &options) else {
|
||||
return Err(EngineError::Other(format!(
|
||||
"Trap: more than {} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time",
|
||||
vectorcraft_render::effects::trap::MAX_NEAR_PAIRS
|
||||
)));
|
||||
};
|
||||
if made.is_empty() {
|
||||
return Err(EngineError::Other("Trap: no edges of different colours meet among the selected objects".into()));
|
||||
}
|
||||
@@ -1074,7 +1079,11 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let roots = selected_roots(s)?;
|
||||
let ids = s.edit("Outline Stroke", |d, sel| {
|
||||
let before = d.clone();
|
||||
let mut ended = super::dimension::end_links(d, &roots);
|
||||
// A dimension selected with the art it measures keeps its own lines: it is out of the
|
||||
// document while the art is outlined.
|
||||
let lifted = super::dimension::lift(d, &roots);
|
||||
let kept = !lifted.is_empty();
|
||||
let ended = super::dimension::end_links(d, &roots);
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let mut new_sel = vec![];
|
||||
let mut changed = 0;
|
||||
@@ -1083,10 +1092,10 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
new_sel.push(id);
|
||||
changed += n;
|
||||
}
|
||||
// A dimension whose source was outlined stays plain: its link no longer fits that art.
|
||||
ended.retain(|e| e.source_kept(&before, d));
|
||||
super::dimension::restore_unchanged(d, ended);
|
||||
if changed == 0 {
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was outlined stays where it was, no longer linked.
|
||||
super::dimension::restore_unchanged(&before, d, ended);
|
||||
if changed == 0 || (kept && d.layers == before.layers) {
|
||||
return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into()));
|
||||
}
|
||||
sel.set(new_sel.iter().copied());
|
||||
|
||||
@@ -152,6 +152,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"edit.findNext",
|
||||
"edit.findReplace",
|
||||
"effect.apply",
|
||||
"effect.deferredStatus",
|
||||
"effect.duplicate",
|
||||
"effect.expandAppearance",
|
||||
"effect.list",
|
||||
@@ -662,11 +663,13 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows.
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, or run
|
||||
/// plug-ins again.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
"addon.pen.nextSegment",
|
||||
"effect.refreshDeferred",
|
||||
"graphicStyle.setOptions",
|
||||
"object.blend.options",
|
||||
"object.liquify",
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Setup",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
has_doc,
|
||||
setup
|
||||
),
|
||||
|
||||
@@ -76,9 +76,11 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b
|
||||
let mut images = vec![];
|
||||
for (_, r) in regions {
|
||||
let area = outset(r, bleed);
|
||||
// At most MAX_PIXELS, and 65535 pixels a side.
|
||||
// At most MAX_PIXELS, and no side longer than the renderer draws (rounded up to whole
|
||||
// pixels below).
|
||||
let side = area.width().max(area.height()).max(1.0);
|
||||
let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(65_535.0 / side);
|
||||
let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0;
|
||||
let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side);
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1280,19 +1280,25 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// out (overflowing text) is shaped alone in its writing direction, with the rest of its grapheme
|
||||
// in the grapheme's own styles.
|
||||
let plain = t.plain_text();
|
||||
let unchosen = holder.as_ref().filter(|_| !styled).and_then(|_| {
|
||||
let mut probe = t.clone();
|
||||
edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe);
|
||||
own_glyph(&plain, &lay, ch, &bytes, &face).unwrap_or_else(|| shaped_alone(&probe, ch, &bytes, &face).0)
|
||||
});
|
||||
let mut probe = t.clone();
|
||||
edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None);
|
||||
let probe_lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe);
|
||||
let unchosen = holder
|
||||
.as_ref()
|
||||
.filter(|_| !styled)
|
||||
.and_then(|_| own_glyph(&plain, &probe_lay, ch, &bytes, &face).unwrap_or_else(|| shaped_alone(&probe, ch, &bytes, &face).0));
|
||||
let substituted = unchosen.is_some_and(|g| g != default);
|
||||
let choice = match gid.filter(|g| *g != default || substituted) {
|
||||
None => None,
|
||||
Some(g) if g == default || face.alternates(ch).iter().any(|a| a.gid == g) => Some(face.choice(ch, g)),
|
||||
Some(g) => return Err(bad(C, format!("glyph {g} is not an alternate of {ch} in {} {}", face.family, face.style))),
|
||||
};
|
||||
let drawn = choice.as_ref().map_or(unchosen.unwrap_or(default), |c| c.gid);
|
||||
// Without a choice, the glyph drawn in whatever face draws the character, as
|
||||
// `text.glyphAlternates` reports it (a fallback face's glyph, the capital of All Caps).
|
||||
let drawn = match &choice {
|
||||
Some(c) => c.gid,
|
||||
None => drawn_glyph(&plain, &probe_lay, ch, &bytes, &face).or_else(|| shaped_alone(&probe, ch, &bytes, &face).1).unwrap_or(default),
|
||||
};
|
||||
// The run holding the character. The request changes nothing when the choice is the one the
|
||||
// character's run holds and that run holds the character alone; otherwise the edit splits the
|
||||
// run, so that the following text does not take the character into a ligature.
|
||||
@@ -1315,6 +1321,16 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
if held == choice && (choice.is_none() || alone) {
|
||||
// The text is left as it is, so the glyph is the one the unchanged text draws. The probe
|
||||
// splits a run that holds an earlier character's choice, and the split can break a ligature
|
||||
// that takes in this character.
|
||||
let drawn = match &choice {
|
||||
None if probe.runs != t.runs => {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
drawn_glyph(&plain, &lay, ch, &bytes, &face).or_else(|| shaped_alone(&t, ch, &bytes, &face).1).unwrap_or(default)
|
||||
}
|
||||
_ => drawn,
|
||||
};
|
||||
return Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn}));
|
||||
}
|
||||
s.edit("Glyphs", |d, _| {
|
||||
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_doc::{AreaFit, Document, Justify, Node, NodeId, NodeKind, RubyAl
|
||||
use vectorcraft_geom::{Affine, PathData, Vec2};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::{len_param, length_given, number_given, shape_node};
|
||||
use super::pathops::{length_given, number_given, shape_node};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, id_param, index, number_or, ok,
|
||||
str_param, switch_or, targets, text_param,
|
||||
@@ -596,6 +596,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if texts.is_empty() {
|
||||
return Err(EngineError::Other("Create Outlines: select text objects".into()));
|
||||
}
|
||||
let before = (!super::dimension::reached(d, &roots).is_empty()).then(|| d.clone());
|
||||
let ended = super::dimension::end_links(d, &roots);
|
||||
let mut new_sel: Vec<NodeId> = roots.iter().copied().filter(|r| !texts.contains(r)).collect();
|
||||
let mut out = vec![];
|
||||
@@ -691,7 +692,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
new_sel.push(gid);
|
||||
}
|
||||
}
|
||||
super::dimension::restore_unchanged(d, ended);
|
||||
if let Some(before) = &before {
|
||||
super::dimension::restore_unchanged(before, d, ended);
|
||||
}
|
||||
// Outlined frames of threaded text leave their threads with the text they show.
|
||||
super::threads::leave_threads(d, &threaded);
|
||||
sel.set(new_sel);
|
||||
@@ -821,7 +824,9 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let leading = match p.get("leading") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(None),
|
||||
Some(_) => Some(Some(len_param(p, "leading").ok_or_else(|| bad(C, "leading must be a number or \"auto\""))?.clamp(0.1, 5000.0))),
|
||||
Some(_) => {
|
||||
Some(Some(length_given(p, "leading", C).ok().flatten().ok_or_else(|| bad(C, "leading must be a number or \"auto\""))?.clamp(0.1, 5000.0)))
|
||||
}
|
||||
};
|
||||
let tracking = number_given(p, "tracking", C)?;
|
||||
let justify = match text_param(p, "justify", C)? {
|
||||
|
||||
@@ -110,6 +110,9 @@ pub struct DocState {
|
||||
/// paths the document links to are looked at within them later too, when the Links panel
|
||||
/// asks about a link outside any caller's scope.
|
||||
pub opened_by: Option<Arc<file_access::AutomationRoots>>,
|
||||
/// The live-effect plug-in stages deferred while the document is drawn on screen, and the time
|
||||
/// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved.
|
||||
pub plugin_effects: vectorcraft_plugins::deferred::Deferrals,
|
||||
/// What [`DocState::any_empty_artboards`] last measured. Not saved.
|
||||
empty_artboards: std::cell::RefCell<EmptyArtboards>,
|
||||
/// What [`DocState::any_art_to_fit`] last measured. Not saved.
|
||||
@@ -326,6 +329,7 @@ impl DocState {
|
||||
last_perspective: None,
|
||||
opened_by: file_access::current(),
|
||||
empty_artboards: Default::default(),
|
||||
plugin_effects: Default::default(),
|
||||
art_to_fit: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +106,8 @@ impl Entry {
|
||||
Entry::End(e) => format!("ended: {}", e.id()),
|
||||
Entry::Report { ms, host_calls, slowest } => {
|
||||
let time = ms.map_or_else(|| "time unavailable".to_string(), |ms| format!("{ms} ms"));
|
||||
let mut s = format!("{time}, {host_calls} host calls");
|
||||
let calls = if *host_calls == 1 { "host call" } else { "host calls" };
|
||||
let mut s = format!("{time}, {host_calls} {calls}");
|
||||
if !slowest.is_empty() {
|
||||
let list: Vec<String> = slowest.iter().map(|c| format!("{} ×{} {} ms", c.id, c.calls, c.total_ms)).collect();
|
||||
s.push_str("; slowest: ");
|
||||
@@ -207,7 +208,7 @@ impl Console {
|
||||
|
||||
/// `c` as the console shows it: a control character as its Control Picture, a line or paragraph
|
||||
/// separator as U+2424, anything else as it is.
|
||||
fn shown(c: char) -> char {
|
||||
pub(crate) fn shown(c: char) -> char {
|
||||
match c {
|
||||
'\u{0}'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
|
||||
'\u{7f}' => '\u{2421}',
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
//! `alert(message[, title, errorIcon])`, `confirm(message[, noAsDflt, title])` and
|
||||
//! `prompt(message, preset[, title])`: the dialogs a script opens while it runs.
|
||||
//!
|
||||
//! A message and a preset arrive as the string `String(value)` gives, a title the same way unless
|
||||
//! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the
|
||||
//! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and
|
||||
//! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel.
|
||||
//!
|
||||
//! In the app the run waits at the call for the person's answer, and spends no fuel while it
|
||||
//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with
|
||||
//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no
|
||||
//! answer left, or with the next answer for another kind of dialog, ends the run. The report's
|
||||
//! `dialogs` lists each dialog and its answer.
|
||||
//!
|
||||
//! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`],
|
||||
//! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and
|
||||
//! [`MAX_RECORD_BYTES`].
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError};
|
||||
|
||||
use super::{Host, console};
|
||||
|
||||
/// The most bytes (UTF-8) of a dialog's message.
|
||||
pub const MAX_MESSAGE_BYTES: usize = 16 << 10;
|
||||
/// The most bytes (UTF-8) of a dialog's title.
|
||||
pub const MAX_TITLE_BYTES: usize = 256;
|
||||
/// The most bytes (UTF-8) of a prompt's preset and of the text it returns.
|
||||
pub const MAX_PROMPT_BYTES: usize = 16 << 10;
|
||||
/// The most answers `script.run` takes.
|
||||
pub const MAX_ANSWERS: usize = 10_000;
|
||||
/// The most bytes of `answers`, as JSON.
|
||||
pub const MAX_ANSWERS_BYTES: usize = 1 << 20;
|
||||
/// The most dialogs a report lists.
|
||||
pub const MAX_RECORDS: usize = 10_000;
|
||||
/// The most bytes of the dialogs a report lists, as JSON.
|
||||
pub const MAX_RECORD_BYTES: usize = 1 << 20;
|
||||
/// A dialog's title when the script gives none, in English; the app translates it when it shows it.
|
||||
pub const DEFAULT_TITLE: &str = "Script Alert";
|
||||
|
||||
/// Which dialog a script opened.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DialogKind {
|
||||
Alert,
|
||||
Confirm,
|
||||
Prompt,
|
||||
}
|
||||
|
||||
impl DialogKind {
|
||||
/// The function's name, which is also the `kind` of an answer and of a report's dialog.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Alert => "alert",
|
||||
Self::Confirm => "confirm",
|
||||
Self::Prompt => "prompt",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog a script opened, which waits for its answer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ScriptDialog {
|
||||
pub kind: DialogKind,
|
||||
pub message: String,
|
||||
/// `None`: the script gave no title ([`DEFAULT_TITLE`]).
|
||||
pub title: Option<String>,
|
||||
/// `alert`: show the error icon.
|
||||
pub error_icon: bool,
|
||||
/// `confirm`: No is the default button.
|
||||
pub no_as_default: bool,
|
||||
/// `prompt`: the text its field starts with.
|
||||
pub preset: String,
|
||||
}
|
||||
|
||||
/// The answer to a [`ScriptDialog`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum DialogAnswer {
|
||||
/// OK, for `alert`.
|
||||
Ok,
|
||||
/// Yes (`true`) or No, for `confirm`.
|
||||
Confirm(bool),
|
||||
/// OK with the field's text, or Cancel (`None`), for `prompt`.
|
||||
Prompt(Option<String>),
|
||||
}
|
||||
|
||||
impl DialogAnswer {
|
||||
pub fn kind(&self) -> DialogKind {
|
||||
match self {
|
||||
Self::Ok => DialogKind::Alert,
|
||||
Self::Confirm(_) => DialogKind::Confirm,
|
||||
Self::Prompt(_) => DialogKind::Prompt,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns.
|
||||
fn data(&self) -> Data {
|
||||
match self {
|
||||
Self::Ok => Data::Undefined,
|
||||
Self::Confirm(b) => Data::Bool(*b),
|
||||
Self::Prompt(Some(t)) => Data::String(t.clone()),
|
||||
Self::Prompt(None) => Data::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string or `null`.
|
||||
fn json(&self) -> Value {
|
||||
match self {
|
||||
Self::Ok => json!("ok"),
|
||||
Self::Confirm(b) => json!(b),
|
||||
Self::Prompt(t) => json!(t),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together
|
||||
/// is a line break; every other control character, and with `lines` false every line break too,
|
||||
/// shows as its Unicode Control Picture, as the Script Console shows it.
|
||||
pub fn shown_text(text: &str, lines: bool) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'\r' if lines => {
|
||||
chars.next_if_eq(&'\n');
|
||||
out.push('\n');
|
||||
}
|
||||
'\n' if lines => out.push('\n'),
|
||||
c => out.push(console::shown(c)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The longest start of `text` that is at most `max` bytes, cut at a character boundary.
|
||||
pub fn cut_to(text: &str, max: usize) -> &str {
|
||||
if text.len() <= max {
|
||||
return text;
|
||||
}
|
||||
let mut end = max;
|
||||
while !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
text.get(..end).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
|
||||
/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter
|
||||
/// took before dialogs existed, is an empty list.
|
||||
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
|
||||
let list = match v {
|
||||
None => return Ok(Vec::new()),
|
||||
Some(Value::Object(o)) if o.is_empty() => return Ok(Vec::new()),
|
||||
Some(Value::Array(a)) => a,
|
||||
Some(_) => return Err("`answers` must be a list of answers".into()),
|
||||
};
|
||||
if list.len() > MAX_ANSWERS {
|
||||
return Err(format!("`answers` has more than {MAX_ANSWERS} answers"));
|
||||
}
|
||||
if serde_json::to_vec(list).map_or(true, |b| b.len() > MAX_ANSWERS_BYTES) {
|
||||
return Err("`answers` is larger than 1 MiB".into());
|
||||
}
|
||||
list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect()
|
||||
}
|
||||
|
||||
fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
|
||||
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") };
|
||||
if o.len() != 2 || !o.contains_key("value") {
|
||||
return Err("must have exactly `kind` and `value`");
|
||||
}
|
||||
match (o.get("kind").and_then(Value::as_str), &o["value"]) {
|
||||
(Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok),
|
||||
(Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""),
|
||||
(Some("confirm"), Value::Bool(b)) => Ok(DialogAnswer::Confirm(*b)),
|
||||
(Some("confirm"), _) => Err("is a confirm's answer, whose `value` must be true or false"),
|
||||
(Some("prompt"), Value::Null) => Ok(DialogAnswer::Prompt(None)),
|
||||
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
|
||||
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
|
||||
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
|
||||
_ => Err("must have `kind` alert, confirm or prompt"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialogs of one run: the answers left for a run with nobody to ask, the dialog that waits
|
||||
/// for the person's answer, and the list the report gives.
|
||||
pub(crate) struct Dialogs {
|
||||
/// Answers come from the person, not from `answers`.
|
||||
framed: bool,
|
||||
/// The realm's [`Realm::wait_flag`].
|
||||
can_wait: Rc<Cell<bool>>,
|
||||
answers: RefCell<VecDeque<DialogAnswer>>,
|
||||
waiting: RefCell<Option<ScriptDialog>>,
|
||||
/// The error that ended the run when an answer could not reach the script.
|
||||
failed: RefCell<Option<RunError>>,
|
||||
records: RefCell<Vec<Value>>,
|
||||
record_bytes: Cell<usize>,
|
||||
count: Cell<u64>,
|
||||
truncated: Cell<bool>,
|
||||
}
|
||||
|
||||
impl Dialogs {
|
||||
pub(crate) fn new(framed: bool, realm: &Realm, answers: Vec<DialogAnswer>) -> Self {
|
||||
Self {
|
||||
framed,
|
||||
can_wait: realm.wait_flag(),
|
||||
answers: RefCell::new(answers.into()),
|
||||
waiting: RefCell::default(),
|
||||
failed: RefCell::default(),
|
||||
records: RefCell::default(),
|
||||
record_bytes: Cell::new(0),
|
||||
count: Cell::new(0),
|
||||
truncated: Cell::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog that waits for its answer.
|
||||
pub(crate) fn waiting(&self) -> Option<ScriptDialog> {
|
||||
self.waiting.borrow().clone()
|
||||
}
|
||||
|
||||
pub(crate) fn is_waiting(&self) -> bool {
|
||||
self.waiting.borrow().is_some()
|
||||
}
|
||||
|
||||
/// The error that ended the run when its answer could not reach the script.
|
||||
pub(crate) fn take_failure(&self) -> Option<RunError> {
|
||||
self.failed.borrow_mut().take()
|
||||
}
|
||||
|
||||
/// How many of `answers` the run did not use.
|
||||
pub(crate) fn unused(&self) -> usize {
|
||||
self.answers.borrow().len()
|
||||
}
|
||||
|
||||
/// Gives the waiting dialog `answer`, which must be for its kind and, for a prompt, at most
|
||||
/// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits.
|
||||
pub(crate) fn answer(&self, realm: &mut Realm, answer: DialogAnswer) -> bool {
|
||||
let fits = match &answer {
|
||||
DialogAnswer::Prompt(Some(t)) => t.len() <= MAX_PROMPT_BYTES,
|
||||
_ => true,
|
||||
};
|
||||
let mut waiting = self.waiting.borrow_mut();
|
||||
let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false };
|
||||
self.record(d, answer.json());
|
||||
*waiting = None;
|
||||
if let Err(e) = realm.answer(answer.data()) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`.
|
||||
pub(crate) fn stopped(&self) {
|
||||
if let Some(d) = self.waiting.borrow_mut().take() {
|
||||
self.record(&d, json!("stop"));
|
||||
}
|
||||
}
|
||||
|
||||
fn record(&self, d: &ScriptDialog, answer: Value) {
|
||||
self.count.set(self.count.get().saturating_add(1));
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!(d.kind.id()));
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
match d.kind {
|
||||
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
|
||||
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
|
||||
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
|
||||
};
|
||||
r.insert("answer".into(), answer);
|
||||
let r = Value::Object(r);
|
||||
let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len());
|
||||
let mut records = self.records.borrow_mut();
|
||||
if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
|
||||
self.truncated.set(true);
|
||||
return;
|
||||
}
|
||||
self.record_bytes.set(self.record_bytes.get() + bytes);
|
||||
records.push(r);
|
||||
}
|
||||
|
||||
/// Adds `dialogs`, `dialogCount` and `dialogsTruncated` to a report.
|
||||
pub(crate) fn report(&self, report: &mut Map<String, Value>) {
|
||||
report.insert("dialogs".into(), Value::Array(self.records.borrow().clone()));
|
||||
report.insert("dialogCount".into(), json!(self.count.get()));
|
||||
report.insert("dialogsTruncated".into(), json!(self.truncated.get()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `alert`, `confirm` and `prompt` to the realm.
|
||||
pub(super) fn install(realm: &mut Realm, host: &Rc<Host>) -> Result<(), RunError> {
|
||||
use Arg::{Bool, Text, TextOrUndefined};
|
||||
let call = |kind: DialogKind| -> HostFunction {
|
||||
let h = host.clone();
|
||||
Rc::new(move |args| open(&h, kind, &args))
|
||||
};
|
||||
realm.define_host_function("alert", vec![Text, TextOrUndefined, Bool], call(DialogKind::Alert))?;
|
||||
realm.define_host_function("confirm", vec![Text, Bool, TextOrUndefined], call(DialogKind::Confirm))?;
|
||||
realm.define_host_function("prompt", vec![Text, Text, TextOrUndefined], call(DialogKind::Prompt))
|
||||
}
|
||||
|
||||
fn text(args: &[Data], i: usize) -> Option<String> {
|
||||
match args.get(i) {
|
||||
Some(Data::String(s)) => Some(s.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn flag(args: &[Data], i: usize) -> bool {
|
||||
matches!(args.get(i), Some(Data::Bool(true)))
|
||||
}
|
||||
|
||||
/// A call of `alert`, `confirm` or `prompt`.
|
||||
fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError> {
|
||||
let name = kind.id();
|
||||
host.charge_call(args.iter().map(super::data_size).sum())?;
|
||||
let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) };
|
||||
let (title, error_icon, no_as_default, preset) = match kind {
|
||||
DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()),
|
||||
DialogKind::Prompt => {
|
||||
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
|
||||
(text(args, 2), false, false, preset)
|
||||
}
|
||||
};
|
||||
if message.len() > MAX_MESSAGE_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB")));
|
||||
}
|
||||
if title.as_ref().is_some_and(|t| t.len() > MAX_TITLE_BYTES) {
|
||||
return Err(HostError::Range(format!("{name}: the title is longer than 256 bytes")));
|
||||
}
|
||||
if preset.len() > MAX_PROMPT_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
|
||||
}
|
||||
let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset };
|
||||
let d = &host.dialogs;
|
||||
if d.framed {
|
||||
if !d.can_wait.get() {
|
||||
return Err(HostError::Error(format!(
|
||||
"{name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code"
|
||||
)));
|
||||
}
|
||||
*d.waiting.borrow_mut() = Some(dialog);
|
||||
return Err(HostError::Wait);
|
||||
}
|
||||
let next = d.answers.borrow_mut().pop_front();
|
||||
match next {
|
||||
Some(a) if a.kind() == kind => {
|
||||
d.record(&dialog, a.json());
|
||||
Ok(a.data())
|
||||
}
|
||||
Some(a) => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id())))
|
||||
}
|
||||
None => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
Err(HostError::Abort(format!("{name}: `answers` has no answer left for this dialog")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! The members of a script's `$` object besides `$.write`, `$.writeln`, `$.evalFile`, `$.fileName`
|
||||
//! and `$.includePath`, from the Dollar object
|
||||
//! page (<https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/>), and
|
||||
//! the locale the global `localize` reads
|
||||
//! (<https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/>).
|
||||
//!
|
||||
//! Every value here belongs to one run: a run starts with the locale of the interface, the
|
||||
//! environment values of [`ENV_NAMES`] read from the process, localization off and a timer at zero,
|
||||
//! and what a script changes ends with its run. `$.setenv` never changes the process's environment.
|
||||
//!
|
||||
//! These are VectorCraft's own values and rules: `$.appEncoding` is always UTF-8; `$.build` and
|
||||
//! `$.version` give VectorCraft's version, `$.engineName` is `VectorCraft` and `$.buildDate` is
|
||||
//! `null`; `$.flags` takes only 512, which turns localization on; `$.level` and `$.memCache` are 0
|
||||
//! and `$.screens` is empty; `$.os` names the system without its version; `$.strict` is whether the
|
||||
//! realm reads scripts as strict mode code; `$.bp` and `$.colorPicker` throw, since scripts have no
|
||||
//! debugger and cannot show a dialog; `$.gc` does nothing, since the interpreter collects its own
|
||||
//! garbage; `$.getenv` and `$.setenv` know only [`ENV_NAMES`], with values of at most
|
||||
//! [`MAX_ENV_BYTES`] bytes of letters, digits and `_ . - @`; and `$.sleep` waits at most
|
||||
//! [`MAX_SLEEP_MS`] milliseconds, between two frames of the app, and does not wait on the web,
|
||||
//! which has no clock.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use vectorcraft_js::{Data, HostError, HostItem, Localization, ScriptItem};
|
||||
|
||||
use super::{Host, function};
|
||||
|
||||
/// The longest `$.sleep`, in milliseconds.
|
||||
pub const MAX_SLEEP_MS: f64 = 1_000.0;
|
||||
/// The environment variables `$.getenv` reads and `$.setenv` sets.
|
||||
pub const ENV_NAMES: &[&str] = &["LANG", "LC_MESSAGES", "LC_ALL", "OS"];
|
||||
/// The most bytes of an environment value.
|
||||
pub const MAX_ENV_BYTES: usize = 64;
|
||||
/// The value of `$.flags` that turns localization on, the only one a script may set.
|
||||
pub const LOCALIZE_FLAG: f64 = 512.0;
|
||||
|
||||
/// What `$` knows of a run.
|
||||
pub(crate) struct RunInfo {
|
||||
/// The locale the run starts with, such as `de_DE`.
|
||||
pub locale: String,
|
||||
/// The realm reads scripts as strict mode code.
|
||||
pub strict: bool,
|
||||
}
|
||||
|
||||
/// The locale for an interface language code such as `de`, `pt-br` or `zh-hant`: the language,
|
||||
/// with its region after `_` where the code gives one (`pt_BR`; `zh_CN` for `zh-hans` and `zh_TW`
|
||||
/// for `zh-hant`); `en` for a code that is not a language.
|
||||
pub(crate) fn ui_locale(code: &str) -> String {
|
||||
let mut parts = code.split(['-', '_']);
|
||||
let language = parts.next().unwrap_or_default().to_ascii_lowercase();
|
||||
if !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_lowercase()) {
|
||||
return "en".into();
|
||||
}
|
||||
let region = match parts.next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("hans") => Some("CN".to_string()),
|
||||
Some("hant") => Some("TW".to_string()),
|
||||
Some(r) if r.len() == 2 && r.bytes().all(|b| b.is_ascii_lowercase()) => Some(r.to_ascii_uppercase()),
|
||||
_ => None,
|
||||
};
|
||||
region.map_or(language.clone(), |r| format!("{language}_{r}"))
|
||||
}
|
||||
|
||||
/// A locale a script gives `$.locale`, as `ll` or `ll_RR`: a language of two or three letters and
|
||||
/// an optional region of two letters or three digits, joined by `_` or `-`, in any case.
|
||||
fn script_locale(text: &str) -> Option<String> {
|
||||
let mut parts = text.split(['-', '_']);
|
||||
let language = parts.next()?;
|
||||
let region = parts.next();
|
||||
if parts.next().is_some() || !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
let language = language.to_ascii_lowercase();
|
||||
match region {
|
||||
None => Some(language),
|
||||
Some(r) if r.len() == 2 && r.bytes().all(|b| b.is_ascii_alphabetic()) => Some(format!("{language}_{}", r.to_ascii_uppercase())),
|
||||
Some(r) if r.len() == 3 && r.bytes().all(|b| b.is_ascii_digit()) => Some(format!("{language}_{r}")),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The languages whose numbers are written with a decimal comma (VectorCraft's own list).
|
||||
const DECIMAL_COMMA: &[&str] = &[
|
||||
"bg", "ca", "cs", "da", "de", "el", "es", "et", "fi", "fr", "hr", "hu", "id", "it", "lt", "lv", "nb", "nl", "no", "pl", "pt", "ro", "ru", "sk",
|
||||
"sl", "sr", "sv", "tr", "uk", "vi",
|
||||
];
|
||||
|
||||
/// The character `locale` writes before a number's fraction.
|
||||
pub(crate) fn decimal_point(locale: &str) -> &'static str {
|
||||
let language = locale.split('_').next().unwrap_or_default();
|
||||
if DECIMAL_COMMA.contains(&language) { "," } else { "." }
|
||||
}
|
||||
|
||||
/// The platform suffix of a localization object's names on this system.
|
||||
pub(crate) fn platform() -> Option<&'static str> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
None
|
||||
} else if cfg!(windows) {
|
||||
Some("Win")
|
||||
} else if cfg!(target_os = "macos") {
|
||||
Some("Mac")
|
||||
} else {
|
||||
Some("Unix")
|
||||
}
|
||||
}
|
||||
|
||||
/// `$.os`: the system, without its version.
|
||||
fn os() -> &'static str {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
"Web"
|
||||
} else if cfg!(windows) {
|
||||
"Windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"macOS"
|
||||
} else if cfg!(target_os = "linux") {
|
||||
"Linux"
|
||||
} else if cfg!(target_os = "freebsd") {
|
||||
"FreeBSD"
|
||||
} else {
|
||||
"Unix"
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `value` one an environment value may be?
|
||||
fn env_value_ok(value: &str) -> bool {
|
||||
value.len() <= MAX_ENV_BYTES && value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-' | b'@'))
|
||||
}
|
||||
|
||||
/// The values of [`ENV_NAMES`] in the process's environment, each left out when it is not one an
|
||||
/// environment value may be.
|
||||
fn process_env() -> Vec<(&'static str, Option<String>)> {
|
||||
ENV_NAMES.iter().map(|&n| (n, std::env::var(n).ok().filter(|v| env_value_ok(v)))).collect()
|
||||
}
|
||||
|
||||
fn one_string(args: &[Data], name: &str) -> Result<String, HostError> {
|
||||
match args.first() {
|
||||
Some(Data::String(s)) => Ok(s.clone()),
|
||||
_ => Err(HostError::Type(format!("$.{name}: give a name, as a string"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn value(v: Data) -> HostItem {
|
||||
HostItem::Value(v)
|
||||
}
|
||||
|
||||
fn text(s: impl Into<String>) -> Data {
|
||||
Data::String(s.into())
|
||||
}
|
||||
|
||||
/// The members `$` has besides `write`, `writeln`, `evalFile`, `fileName` and `includePath`.
|
||||
pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localization>) -> Vec<(String, HostItem)> {
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let host_locale = info.locale.clone();
|
||||
localization.set_locale(&info.locale);
|
||||
localization.set_platform(platform());
|
||||
let env = Rc::new(RefCell::new(process_env()));
|
||||
let timer = Rc::new(Cell::new(Duration::ZERO));
|
||||
let getter = |f: Rc<dyn Fn() -> Data>| HostItem::Getter(function(move |_| Ok(f())));
|
||||
let property = |get: Rc<dyn Fn() -> Data>, set: Rc<dyn Fn(Data) -> Result<(), HostError>>| HostItem::Property {
|
||||
get: function(move |_| Ok(get())),
|
||||
set: function(move |mut a| {
|
||||
set(if a.is_empty() { Data::Undefined } else { a.swap_remove(0) })?;
|
||||
Ok(Data::Undefined)
|
||||
}),
|
||||
};
|
||||
let fail = |message: &'static str| HostItem::Function(function(move |_| Err(HostError::Error(message.to_string()))));
|
||||
|
||||
let locale = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || text(l.locale())),
|
||||
Rc::new(move |v| {
|
||||
let locale = match v {
|
||||
Data::Null | Data::Undefined => host_locale.clone(),
|
||||
Data::String(t) if t.is_empty() => host_locale.clone(),
|
||||
Data::String(t) => script_locale(&t).ok_or_else(|| HostError::Range(BAD_LOCALE.to_string()))?,
|
||||
_ => return Err(HostError::Type(BAD_LOCALE.to_string())),
|
||||
};
|
||||
s.set_locale(&locale);
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
};
|
||||
let localize = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || Data::Bool(l.enabled())),
|
||||
Rc::new(move |v| match v {
|
||||
Data::Bool(on) => {
|
||||
s.set_enabled(on);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(HostError::Type("$.localize: give true or false".into())),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let flags = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || Data::Number(if l.enabled() { LOCALIZE_FLAG } else { 0.0 })),
|
||||
Rc::new(move |v| match v {
|
||||
Data::Number(n) if n == 0.0 || n == LOCALIZE_FLAG => {
|
||||
s.set_enabled(n == LOCALIZE_FLAG);
|
||||
Ok(())
|
||||
}
|
||||
Data::Number(_) => Err(HostError::Range("$.flags: only 512, which turns localization on, or 0 can be set".into())),
|
||||
_ => Err(HostError::Type("$.flags: give a number".into())),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let decimal = {
|
||||
let l = localization.clone();
|
||||
getter(Rc::new(move || text(decimal_point(&l.locale()))))
|
||||
};
|
||||
let app_encoding = property(
|
||||
Rc::new(|| text("UTF-8")),
|
||||
Rc::new(|v| match v {
|
||||
Data::String(t) if t.eq_ignore_ascii_case("utf-8") || t.eq_ignore_ascii_case("utf8") => Ok(()),
|
||||
Data::String(_) => Err(HostError::Range("$.appEncoding: scripts here read and write UTF-8 only".into())),
|
||||
_ => Err(HostError::Type("$.appEncoding: give an encoding's name, as a string".into())),
|
||||
}),
|
||||
);
|
||||
let mem_cache =
|
||||
property(Rc::new(|| Data::Number(0.0)), Rc::new(|_| Err(HostError::Error("$.memCache: the memory cache size cannot be set".into()))));
|
||||
let hires_timer = {
|
||||
let (h, last) = (host.clone(), timer.clone());
|
||||
getter(Rc::new(move || {
|
||||
let Some(now) = h.elapsed() else { return Data::Number(0.0) };
|
||||
let since = now.saturating_sub(last.replace(now));
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
Data::Number(since.as_micros() as f64)
|
||||
}))
|
||||
};
|
||||
let getenv = {
|
||||
let (h, env) = (host.clone(), env.clone());
|
||||
function(move |a| {
|
||||
let name = one_string(&a, "getenv")?;
|
||||
h.charge_call(name.len() as u64 + 2)?;
|
||||
let env = env.borrow();
|
||||
let found = env.iter().find(|(n, _)| *n == name).and_then(|(_, v)| v.clone());
|
||||
Ok(found.map_or(Data::Null, Data::String))
|
||||
})
|
||||
};
|
||||
let setenv = {
|
||||
let (h, env) = (host.clone(), env.clone());
|
||||
function(move |a| {
|
||||
let name = one_string(&a, "setenv")?;
|
||||
let Some(Data::String(v)) = a.get(1) else { return Err(HostError::Type("$.setenv: give a value, as a string".into())) };
|
||||
h.charge_call((name.len() + v.len()) as u64 + 4)?;
|
||||
let mut env = env.borrow_mut();
|
||||
let Some(slot) = env.iter_mut().find(|(n, _)| *n == name) else {
|
||||
return Err(HostError::Error(format!("$.setenv: only {} can be set", ENV_NAMES.join(", "))));
|
||||
};
|
||||
if !env_value_ok(v) {
|
||||
return Err(HostError::Range(format!("$.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @")));
|
||||
}
|
||||
slot.1 = Some(v.clone());
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
};
|
||||
let sleep = {
|
||||
let h = host.clone();
|
||||
function(move |a| {
|
||||
let ms = match a.first() {
|
||||
Some(Data::Number(n)) if (0.0..=MAX_SLEEP_MS).contains(n) => *n,
|
||||
Some(Data::Number(_)) => return Err(HostError::Range(format!("$.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS}"))),
|
||||
_ => return Err(HostError::Type("$.sleep: give a number of milliseconds".into())),
|
||||
};
|
||||
h.charge_call(8)?;
|
||||
h.sleep(Duration::from_secs_f64(ms / 1000.0))?;
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
};
|
||||
let about = text(format!("VectorCraft script engine {version}"));
|
||||
|
||||
vec![
|
||||
("about".into(), HostItem::Function(function(move |_| Ok(about.clone())))),
|
||||
("appEncoding".into(), app_encoding),
|
||||
("bp".into(), fail("$.bp: scripts here have no debugger")),
|
||||
("build".into(), value(text(version))),
|
||||
("buildDate".into(), value(Data::Null)),
|
||||
("colorPicker".into(), fail("$.colorPicker: scripts cannot show a dialog yet")),
|
||||
("decimalPoint".into(), decimal),
|
||||
("engineName".into(), value(text("VectorCraft"))),
|
||||
("error".into(), HostItem::Script(ScriptItem::LastError)),
|
||||
("flags".into(), flags),
|
||||
("gc".into(), HostItem::Function(function(|_| Ok(Data::Undefined)))),
|
||||
("getenv".into(), HostItem::Function(getenv)),
|
||||
("global".into(), HostItem::Script(ScriptItem::Global)),
|
||||
("hiresTimer".into(), hires_timer),
|
||||
("level".into(), value(Data::Number(0.0))),
|
||||
("line".into(), HostItem::Script(ScriptItem::Line)),
|
||||
("locale".into(), locale),
|
||||
("localize".into(), localize),
|
||||
("memCache".into(), mem_cache),
|
||||
("os".into(), value(text(os()))),
|
||||
("screens".into(), value(Data::Array(Vec::new()))),
|
||||
("setenv".into(), HostItem::Function(setenv)),
|
||||
("sleep".into(), HostItem::Function(sleep)),
|
||||
("stack".into(), HostItem::Script(ScriptItem::Stack)),
|
||||
("strict".into(), value(Data::Bool(info.strict))),
|
||||
("version".into(), value(text(version))),
|
||||
]
|
||||
}
|
||||
|
||||
const BAD_LOCALE: &str = "$.locale: give a locale such as \"en\" or \"de_DE\", or null for the interface's";
|
||||
@@ -1,8 +1,11 @@
|
||||
//! A script's preprocessor lines, read before it runs, as the public guide lists them
|
||||
//! (<https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/>):
|
||||
//! `#include` and `//@include` put the text of another file in place of the line, `#includepath`
|
||||
//! sets the folders `#include` looks in, `#script` names the run, and `#target` and `#strict off`
|
||||
//! are accepted. The same lines are read in a file `$.evalFile` runs.
|
||||
//! sets the folders `#include` looks in, `#script` names the run, `#strict on` turns on the checks
|
||||
//! of `$.strict` (<https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/>:
|
||||
//! a write to a read-only property is a runtime error, and objects that take no new properties
|
||||
//! refuse them), and `#target` and `#strict off` are accepted. The same lines are read in a file
|
||||
//! `$.evalFile` runs.
|
||||
//!
|
||||
//! VectorCraft's own rules:
|
||||
//!
|
||||
@@ -13,9 +16,15 @@
|
||||
//! the `JSINCLUDE` environment variable. A later `#includepath` replaces the list.
|
||||
//! - Files are read through the script's [`ScriptScope`]: a refused path ends the run, except a
|
||||
//! `JSINCLUDE` folder outside the scope, which is passed over.
|
||||
//! - `#target` takes any value and changes nothing. `#targetengine`, `#engine` and `#strict on` are
|
||||
//! refused as unsupported, and any other `#name` as unknown; `//@name` with another name stays a
|
||||
//! comment.
|
||||
//! - `#target` takes any value and changes nothing. `#targetengine` and `#engine` are refused as
|
||||
//! unsupported, and any other `#name` as unknown; `//@name` with another name stays a comment.
|
||||
//! - The last `#strict on` or `#strict off` of the script and the files it includes sets the checks
|
||||
//! for the whole run; without one they are off. A write to a property that has only a getter is
|
||||
//! checked as a read-only one, the objects that take no new properties are those that are not
|
||||
//! extensible (`Object.preventExtensions`, `Object.seal`, `Object.freeze`), and the rest of ES5
|
||||
//! strict mode is left to `'use strict'`. Code that `eval` and `Function` compile takes the
|
||||
//! checks of the code that compiles it; a file `$.evalFile` runs takes its own `#strict` line if
|
||||
//! it has one, and otherwise the caller's.
|
||||
//! - A run reads at most [`MAX_DEPTH`] levels of nested files, [`MAX_FILES`] files,
|
||||
//! [`MAX_TOTAL_BYTES`] of source in all (the script's own included) and 8 MiB a file, and looks up
|
||||
//! at most [`MAX_PROBES`] paths. A file may be included again once its earlier inclusion has
|
||||
@@ -97,12 +106,13 @@ pub(crate) struct Failure {
|
||||
pub column: u32,
|
||||
}
|
||||
|
||||
/// A source with its preprocessor lines read: the text to run, where its lines came from, and the
|
||||
/// name its `#script` line gave.
|
||||
/// A source with its preprocessor lines read: the text to run, where its lines came from, the
|
||||
/// name its `#script` line gave, and what its last `#strict` line set (`None` without one).
|
||||
pub(crate) struct Expanded {
|
||||
pub source: String,
|
||||
pub map: SourceMap,
|
||||
pub name: Option<String>,
|
||||
pub strict: Option<bool>,
|
||||
}
|
||||
|
||||
/// A file being run: its name for people and the folder its relative paths start from (none for a
|
||||
@@ -130,13 +140,14 @@ pub(crate) struct Files {
|
||||
}
|
||||
|
||||
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
|
||||
/// and whether its last unit is a carriage return.
|
||||
/// whether its last unit is a carriage return, and what the last `#strict` line so far set.
|
||||
struct Out {
|
||||
units: Vec<u16>,
|
||||
line: u32,
|
||||
column: u32,
|
||||
after_cr: bool,
|
||||
map: SourceMap,
|
||||
strict: Option<bool>,
|
||||
}
|
||||
|
||||
impl Out {
|
||||
@@ -330,7 +341,7 @@ impl Files {
|
||||
/// `text`, the file `shown` in folder `dir`, with its preprocessor lines read. With `script`,
|
||||
/// its `#script` line names the run.
|
||||
fn expand(&mut self, shown: Arc<str>, dir: Option<PathBuf>, text: &str, script: bool) -> Result<Expanded, Failure> {
|
||||
let mut out = Out { units: Vec::with_capacity(text.len()), line: 1, column: 0, after_cr: false, map: SourceMap::default() };
|
||||
let mut out = Out { units: Vec::with_capacity(text.len()), line: 1, column: 0, after_cr: false, map: SourceMap::default(), strict: None };
|
||||
let mut name = None;
|
||||
self.file(&mut out, shown, dir.as_deref(), text, script, &mut name)?;
|
||||
let source = String::from_utf16(&out.units).map_err(|_| Failure {
|
||||
@@ -341,7 +352,7 @@ impl Files {
|
||||
line: 0,
|
||||
column: 0,
|
||||
})?;
|
||||
Ok(Expanded { source, map: out.map, name })
|
||||
Ok(Expanded { source, map: out.map, name, strict: out.strict })
|
||||
}
|
||||
|
||||
/// Adds file `shown` (in folder `dir`, with text `text`) to `out`, its included files in place
|
||||
@@ -414,8 +425,8 @@ impl Files {
|
||||
}
|
||||
}
|
||||
Some(DirectiveName::Strict) => match value.to_ascii_lowercase().as_str() {
|
||||
"off" => {}
|
||||
"on" => return Err(at(FailKind::Syntax, format!("unsupported strict checking: {label} on"))),
|
||||
"off" => out.strict = Some(false),
|
||||
"on" => out.strict = Some(true),
|
||||
_ => return Err(at(FailKind::Syntax, format!("{label} takes on or off"))),
|
||||
},
|
||||
Some(DirectiveName::TargetEngine) => return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))),
|
||||
|
||||
+218
-50
@@ -31,11 +31,19 @@
|
||||
//! A run writes to the Script Console with `$.write` and `$.writeln`, and `vc.log` adds a line
|
||||
//! there too. The session's console gets a start line, the run's output, its uncaught error, an end
|
||||
//! line and a report line; the run's report holds its own output and error, its time, its host
|
||||
//! calls by kind and its slowest commands.
|
||||
//! calls by kind and its slowest commands. The rest of `$`, and the global `localize` and
|
||||
//! `toSource`, are in [`dollar`].
|
||||
//!
|
||||
//! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the
|
||||
//! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`.
|
||||
|
||||
pub mod console;
|
||||
pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod include;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
@@ -88,7 +96,7 @@ const MAX_BRIDGE_BYTES: u64 = 4 << 30;
|
||||
/// The version `vc.api.version` gives.
|
||||
pub const API_VERSION: &str = "1.0";
|
||||
/// The features `vc.api.has` knows.
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console"];
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"];
|
||||
/// The most commands a run's report lists in `slowestCommands`.
|
||||
pub const SLOWEST_COMMANDS: usize = 5;
|
||||
|
||||
@@ -147,6 +155,10 @@ pub(crate) struct Request {
|
||||
pub source: String,
|
||||
pub args: Map<String, Value>,
|
||||
pub fuel: u64,
|
||||
/// The locale the run starts with (`$.locale`).
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -158,21 +170,27 @@ thread_local! {
|
||||
static NEXT_JOB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// A session's hold on its running job: while one exists the lease is held. Dropping it ends the job.
|
||||
/// It keeps the run's number and its name as console lines give it, so the run's console entry can
|
||||
/// end when the job is gone.
|
||||
#[derive(Debug)]
|
||||
pub struct JobKey(u64);
|
||||
pub struct JobKey {
|
||||
id: u64,
|
||||
run: u64,
|
||||
name: Arc<str>,
|
||||
}
|
||||
|
||||
impl Drop for JobKey {
|
||||
fn drop(&mut self) {
|
||||
let _ = JOBS.try_with(|jobs| {
|
||||
if let Ok(mut jobs) = jobs.try_borrow_mut() {
|
||||
jobs.remove(&self.0);
|
||||
jobs.remove(&self.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn with_job<T>(key: &JobKey, f: impl FnOnce(&mut Job) -> T) -> Option<T> {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.0).map(f))
|
||||
JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.id).map(f))
|
||||
}
|
||||
|
||||
/// The state a script changes that a rollback puts back.
|
||||
@@ -480,20 +498,27 @@ struct Host {
|
||||
commands: RefCell<HashMap<&'static str, (u64, u128, u128)>>,
|
||||
/// The time the run's slices took, in nanoseconds.
|
||||
run_nanos: Cell<u128>,
|
||||
/// `alert`, `confirm` and `prompt`: their answers and the list the report gives.
|
||||
dialogs: dialogs::Dialogs,
|
||||
/// The files the run reads: its includes and `$.evalFile`'s.
|
||||
files: RefCell<include::Files>,
|
||||
/// Where the lines of the script's expanded source came from.
|
||||
script_map: RefCell<include::SourceMap>,
|
||||
/// The same for each source `$.evalFile` gave, in order.
|
||||
eval_maps: RefCell<Vec<include::SourceMap>>,
|
||||
/// The last error `$.evalFile` raised for a file it could not run, with the file, line and
|
||||
/// column that error is at.
|
||||
eval_failure: RefCell<Option<EvalFailure>>,
|
||||
/// The file, line and column of each error `$.evalFile` raised for a file it could not run, in
|
||||
/// order: the error's mark ([`HostError::Marked`]) is its index.
|
||||
eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>,
|
||||
/// When the run started, where the platform has a clock.
|
||||
started: Option<std::time::Instant>,
|
||||
/// The time since [`Host::started`] at which a `$.sleep` ends.
|
||||
wake_at: Cell<Option<std::time::Duration>>,
|
||||
/// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]).
|
||||
can_wait: Rc<Cell<bool>>,
|
||||
/// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one).
|
||||
eval_strict: Cell<Option<bool>>,
|
||||
}
|
||||
|
||||
/// An error `$.evalFile` raised, as thrown, and the file, line and column it is at.
|
||||
type EvalFailure = (String, Arc<str>, u32, u32);
|
||||
|
||||
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
|
||||
#[derive(Default)]
|
||||
struct Counts {
|
||||
@@ -566,10 +591,64 @@ impl Host {
|
||||
pending.end_line(|line, cut| self.line(console::Entry::Output(line), cut));
|
||||
}
|
||||
}
|
||||
|
||||
/// The time since the run started; none without a clock.
|
||||
fn elapsed(&self) -> Option<std::time::Duration> {
|
||||
#[cfg(test)]
|
||||
if TEST_NO_CLOCK.with(Cell::get) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(d) = TEST_ELAPSED.with(Cell::get) {
|
||||
return Some(d);
|
||||
}
|
||||
self.started.map(|s| s.elapsed())
|
||||
}
|
||||
|
||||
/// `$.sleep`: ends the slice, and the run does not go on until `d` has passed. Without a clock
|
||||
/// it does not wait. A getter, a conversion, a built-in's callback or a file `$.evalFile` runs
|
||||
/// cannot stop at the call, so a wait there is an error, with or without a clock.
|
||||
fn sleep(&self, d: std::time::Duration) -> std::result::Result<(), HostError> {
|
||||
if d.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
if !self.can_wait.get() {
|
||||
return Err(HostError::Error(
|
||||
"$.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if let Some(now) = self.elapsed() {
|
||||
self.wake_at.set(Some(now.saturating_add(d)));
|
||||
self.pause.set(true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The time left of a `$.sleep`, or none when the run is not asleep.
|
||||
fn asleep(&self) -> Option<std::time::Duration> {
|
||||
let wake = self.wake_at.get()?;
|
||||
let left = self.elapsed().map_or(std::time::Duration::ZERO, |now| wake.saturating_sub(now));
|
||||
if left.is_zero() {
|
||||
self.wake_at.set(None);
|
||||
return None;
|
||||
}
|
||||
Some(left)
|
||||
}
|
||||
|
||||
fn over(&self, limit: &str) -> HostError {
|
||||
HostError::Abort(limit.to_string())
|
||||
}
|
||||
|
||||
/// `error`, marked as an error at `file`, `line` and `column`, the place [`located`] gives when
|
||||
/// the run ends with it uncaught.
|
||||
fn placed(&self, error: HostError, file: Arc<str>, line: u32, column: u32) -> HostError {
|
||||
let mut places = self.eval_failures.borrow_mut();
|
||||
let Ok(mark) = u32::try_from(places.len()) else { return error };
|
||||
places.push((file, line, column));
|
||||
HostError::Marked { error: Box::new(error), mark }
|
||||
}
|
||||
|
||||
fn charge_call(&self, bytes: u64) -> std::result::Result<(), HostError> {
|
||||
let calls = self.calls.get() + 1;
|
||||
self.calls.set(calls);
|
||||
@@ -924,8 +1003,9 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) {
|
||||
/// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)`
|
||||
/// gives them, one after another, and `$.writeln(...values)` does the same and ends the line.
|
||||
/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file
|
||||
/// being run and `$.includePath` the `#includepath` list.
|
||||
fn dollar_object(host: &Rc<Host>) -> Vec<(String, HostItem)> {
|
||||
/// being run and `$.includePath` the `#includepath` list. Its other members are
|
||||
/// [`dollar::members`].
|
||||
fn dollar_object(host: &Rc<Host>, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> {
|
||||
let writer = |end: bool| {
|
||||
let h = host.clone();
|
||||
HostItem::TextFunction(function(move |a| {
|
||||
@@ -947,15 +1027,22 @@ fn dollar_object(host: &Rc<Host>) -> Vec<(String, HostItem)> {
|
||||
let eval_file = {
|
||||
let h = host.clone();
|
||||
let end = host.clone();
|
||||
HostItem::Evaluator { source: function(move |a| eval_file(&h, a)), end: Rc::new(move || end.files.borrow_mut().end_eval()) }
|
||||
let strict = host.clone();
|
||||
HostItem::Evaluator {
|
||||
source: function(move |a| eval_file(&h, a)),
|
||||
end: Rc::new(move || end.files.borrow_mut().end_eval()),
|
||||
strict_writes: Rc::new(move || strict.eval_strict.get()),
|
||||
}
|
||||
};
|
||||
vec![
|
||||
let mut items = vec![
|
||||
("write".into(), writer(false)),
|
||||
("writeln".into(), writer(true)),
|
||||
("evalFile".into(), eval_file),
|
||||
("fileName".into(), getter(include::Files::file_name)),
|
||||
("includePath".into(), getter(include::Files::include_path)),
|
||||
]
|
||||
];
|
||||
items.extend(dollar::members(host, info, localization));
|
||||
items
|
||||
}
|
||||
|
||||
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
|
||||
@@ -977,14 +1064,12 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
host.charge_call(path.len() as u64 + 2)?;
|
||||
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
|
||||
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
|
||||
if f.line > 0 {
|
||||
*host.eval_failure.borrow_mut() = Some((message.clone(), f.file.clone(), f.line, f.column));
|
||||
}
|
||||
match f.kind {
|
||||
let error = match f.kind {
|
||||
include::FailKind::Limit => HostError::Abort(message),
|
||||
include::FailKind::Syntax => HostError::Syntax(message),
|
||||
include::FailKind::Error => HostError::Error(message),
|
||||
}
|
||||
};
|
||||
if f.line > 0 { host.placed(error, f.file, f.line, f.column) } else { error }
|
||||
})?;
|
||||
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
|
||||
let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
|
||||
@@ -992,10 +1077,10 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
host.files.borrow_mut().end_eval();
|
||||
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
|
||||
let message = format!("{file}:{line}:{column}: {}", e.message);
|
||||
*host.eval_failure.borrow_mut() = Some((message.clone(), file, line, column));
|
||||
return Err(HostError::Syntax(message));
|
||||
return Err(host.placed(HostError::Syntax(message), file, line, column));
|
||||
}
|
||||
host.eval_maps.borrow_mut().push(expanded.map);
|
||||
host.eval_strict.set(expanded.strict);
|
||||
Ok(Data::String(expanded.source))
|
||||
}
|
||||
|
||||
@@ -1061,7 +1146,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
|
||||
|
||||
/// `message`, with what to do about a failure that comes from a script written for another program.
|
||||
fn explained(kind: &RunErrorKind, message: &str) -> String {
|
||||
const HOST_OBJECTS: &[&str] = &["app", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"];
|
||||
const HOST_OBJECTS: &[&str] = &["app", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"];
|
||||
let names_host_object =
|
||||
message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o)));
|
||||
if *kind == RunErrorKind::Thrown && names_host_object {
|
||||
@@ -1085,18 +1170,20 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
(RunError { kind, message, line: f.line, column: f.column }, file)
|
||||
}
|
||||
|
||||
/// `e`, which the realm raised in source `tag` ([`Realm::error_source`]), at the line and column of
|
||||
/// the file it is in, with that file's name unless it is the script's own.
|
||||
fn located(host: &Host, tag: u32, e: &RunError) -> (RunError, Option<Arc<str>>) {
|
||||
/// `e`, which the realm raised in source `tag` ([`Realm::error_source`]) with host error mark `mark`
|
||||
/// ([`Realm::error_mark`]), at the line and column of the file it is in, with that file's name
|
||||
/// unless it is the script's own.
|
||||
fn located(host: &Host, tag: u32, mark: Option<u32>, e: &RunError) -> (RunError, Option<Arc<str>>) {
|
||||
let map = |m: &include::SourceMap, own: bool| {
|
||||
let (index, file, line, column) = m.locate(e.line, e.column);
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
(RunError { kind: e.kind.clone(), message, line, column }, (!own || index > 0).then_some(file))
|
||||
};
|
||||
// An error `$.evalFile` raised for a file it could not run is at that file's place.
|
||||
if let Some((_, file, line, column)) = host.eval_failure.borrow().as_ref().filter(|(thrown, ..)| e.message.contains(thrown.as_str())) {
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, *line, *column) } else { e.message.clone() };
|
||||
return (RunError { kind: e.kind.clone(), message, line: *line, column: *column }, Some(file.clone()));
|
||||
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
|
||||
// file's place.
|
||||
if let Some((file, line, column)) = mark.and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
return (RunError { kind: e.kind.clone(), message, line, column }, Some(file));
|
||||
}
|
||||
if e.line == 0 {
|
||||
return (e.clone(), None);
|
||||
@@ -1163,6 +1250,32 @@ impl Session {
|
||||
!self.script_stop.is_set() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.waiting.get())).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The time left of the running script's `$.sleep`, or none when it is not asleep. A run asked
|
||||
/// to stop is not asleep: the next [`Session::script_pump`] ends it.
|
||||
pub fn script_sleep_left(&self) -> Option<std::time::Duration> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.asleep())).flatten()
|
||||
}
|
||||
|
||||
/// The dialog (`alert`, `confirm` or `prompt`) the running script waits at for the person's
|
||||
/// answer. A run asked to stop no longer waits: the next [`Session::script_pump`] ends it.
|
||||
pub fn script_dialog(&self) -> Option<ScriptDialog> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting())).flatten()
|
||||
}
|
||||
|
||||
/// Gives the dialog the running script waits at its answer; the next [`Session::script_pump`]
|
||||
/// goes on from the call. → false when nothing waits, the answer is for another kind of
|
||||
/// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`].
|
||||
pub fn script_answer(&mut self, answer: DialogAnswer) -> bool {
|
||||
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false };
|
||||
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The name of the running script.
|
||||
pub fn script_name(&self) -> Option<String> {
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone()))
|
||||
@@ -1195,12 +1308,8 @@ impl Session {
|
||||
/// ([`Self::script_report`]). False with none running.
|
||||
pub fn script_abandon(&mut self) -> bool {
|
||||
let Some(key) = self.script_key.take() else { return false };
|
||||
let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else {
|
||||
drop(key);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
|
||||
self.script_gone(key, console::Ending::Stopped);
|
||||
return true;
|
||||
};
|
||||
drop(key);
|
||||
@@ -1210,6 +1319,19 @@ impl Session {
|
||||
true
|
||||
}
|
||||
|
||||
/// Ends the run whose job is no longer held: its console entry ends with `ending`, with no
|
||||
/// report line, since its time and host calls went with the job, and the session's state is
|
||||
/// put back as at the end of any run.
|
||||
fn script_gone(&mut self, key: JobKey, ending: console::Ending) {
|
||||
let line = console::ConsoleLine { run: key.run, name: key.name.clone(), entry: console::Entry::End(ending) };
|
||||
self.script_console.push(line, false);
|
||||
drop(key);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
@@ -1243,6 +1365,7 @@ impl Session {
|
||||
};
|
||||
let limits = Limits { fuel: request.fuel, heap_bytes: HEAP_BYTES, ..Limits::default() };
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
|
||||
let strict = options.strict;
|
||||
let mut realm = Realm::with_options(options, limits);
|
||||
realm.share_interrupt(&self.script_stop);
|
||||
realm.set_data_limits(DataLimits::default());
|
||||
@@ -1270,24 +1393,34 @@ impl Session {
|
||||
counts: Counts::default(),
|
||||
commands: RefCell::default(),
|
||||
run_nanos: Cell::new(0),
|
||||
dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers),
|
||||
files: RefCell::new(files),
|
||||
script_map: RefCell::default(),
|
||||
eval_maps: RefCell::default(),
|
||||
eval_failure: RefCell::default(),
|
||||
eval_failures: RefCell::default(),
|
||||
started: clock(),
|
||||
wake_at: Cell::new(None),
|
||||
can_wait: realm.wait_flag(),
|
||||
eval_strict: Cell::new(None),
|
||||
});
|
||||
let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0))
|
||||
.map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?;
|
||||
let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start };
|
||||
self.script_console.push(line, false);
|
||||
let info = dollar::RunInfo { locale: request.locale, strict };
|
||||
let localization = realm.localization();
|
||||
let started = match expanded {
|
||||
Err(f) => Err(preprocessor_error(f)),
|
||||
Ok(expanded) => {
|
||||
*host.script_map.borrow_mut() = expanded.map;
|
||||
realm.set_strict_writes(expanded.strict == Some(true));
|
||||
realm
|
||||
.define_host_object("vc", vc_object(&host, args))
|
||||
.and_then(|()| realm.define_host_object("$", dollar_object(&host)))
|
||||
.add_script_extensions()
|
||||
.and_then(|()| realm.define_host_object("vc", vc_object(&host, args)))
|
||||
.and_then(|()| realm.define_host_object("$", dollar_object(&host, info, &localization)))
|
||||
.and_then(|()| dialogs::install(&mut realm, &host))
|
||||
.and_then(|()| realm.start(&expanded.source))
|
||||
.map_err(|e| located(&host, realm.error_source(), &e))
|
||||
.map_err(|e| located(&host, realm.error_source(), realm.error_mark(), &e))
|
||||
}
|
||||
};
|
||||
if let Err((e, file)) = started {
|
||||
@@ -1298,10 +1431,11 @@ impl Session {
|
||||
return Err(EngineError::Other(message));
|
||||
}
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
let (run, line_name) = (host.run, host.name.clone());
|
||||
let job = Job { realm, host, world: World::working(self), start_uids: open, name: name.clone(), scope };
|
||||
let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(id, job));
|
||||
self.script_key = Some(JobKey(id));
|
||||
self.script_key = Some(JobKey { id, run, name: line_name });
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
@@ -1309,14 +1443,24 @@ impl Session {
|
||||
/// run has ended: its report, or the error that ended it, with the documents put back.
|
||||
pub fn script_pump(&mut self) -> Option<Result<Value>> {
|
||||
let key = self.script_key.take()?;
|
||||
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else {
|
||||
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
|
||||
self.script_gone(key, console::Ending::Internal);
|
||||
return Some(Err(EngineError::Other(JOB_GONE.to_string())));
|
||||
};
|
||||
if job.host.waiting.get() && !self.script_stop.is_set() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job));
|
||||
if let Some(e) = job.host.dialogs.take_failure() {
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
|
||||
if job.realm.waits() {
|
||||
let kind = LimitKind::Interrupted;
|
||||
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
if vectorcraft_doc::cancel::check().is_err() {
|
||||
self.script_stop.set();
|
||||
}
|
||||
@@ -1329,10 +1473,16 @@ impl Session {
|
||||
}
|
||||
Ok(Err(e)) => Some(self.script_failed(job, &e)),
|
||||
Ok(Ok(Progress::Paused)) => {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job));
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => {
|
||||
let n = job.host.dialogs.unused();
|
||||
let kind = LimitKind::Host;
|
||||
let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" });
|
||||
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 }))
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => {
|
||||
let r = self.script_commit(job);
|
||||
self.trim_histories();
|
||||
@@ -1342,8 +1492,9 @@ impl Session {
|
||||
}
|
||||
|
||||
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
|
||||
job.host.dialogs.stopped();
|
||||
let fuel_left = job.realm.fuel_left();
|
||||
let (e, file) = located(&job.host, job.realm.error_source(), e);
|
||||
let (e, file) = located(&job.host, job.realm.error_source(), job.realm.error_mark(), e);
|
||||
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
close_run(self, &job.host, &mut report, ending(&e.kind));
|
||||
drop(job);
|
||||
@@ -1438,9 +1589,14 @@ impl Session {
|
||||
if let Some(result) = self.script_pump() {
|
||||
return result;
|
||||
}
|
||||
if self.script_waiting() {
|
||||
if self.script_waiting() || self.script_dialog().is_some() {
|
||||
self.script_stop.set();
|
||||
}
|
||||
// A `$.sleep` waits here, where nothing is drawn, instead of turning the loop over.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(left) = self.script_sleep_left() {
|
||||
std::thread::sleep(left.min(std::time::Duration::from_millis(100)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1504,8 +1660,8 @@ fn line_to(s: &mut Session, host: &Host, entry: console::Entry, cut: bool) {
|
||||
|
||||
/// Ends the console lines of `host`'s run: the line `$.write` left unended, then for a failed run
|
||||
/// (`report["ok"]` false) its error as `name:line:column: message`, then an end line and a report
|
||||
/// line in the session's console. Adds the run's time, host calls by kind, slowest commands and
|
||||
/// console to `report`.
|
||||
/// line in the session's console. Adds the run's time, host calls by kind, slowest commands,
|
||||
/// console and dialogs to `report`.
|
||||
fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::Ending) {
|
||||
let mut pending = std::mem::take(&mut *host.pending.borrow_mut());
|
||||
if !pending.is_empty() {
|
||||
@@ -1539,6 +1695,7 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
|
||||
o.insert("hostCallCounts".into(), host.counts.json());
|
||||
o.insert("slowestCommands".into(), Value::Array(slow_json));
|
||||
o.insert("console".into(), host.console.borrow().report());
|
||||
host.dialogs.report(o);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1592,6 +1749,13 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
r
|
||||
}
|
||||
|
||||
/// Tests: removes the session's running job while the session keeps its hold on it. → whether a
|
||||
/// job was removed.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn forget_job(s: &Session) -> bool {
|
||||
s.script_key.as_ref().is_some_and(|k| JOBS.with(|jobs| jobs.borrow_mut().remove(&k.id)).is_some())
|
||||
}
|
||||
|
||||
/// The objects a run may add before it is asked to continue or stop.
|
||||
fn growth_objects() -> u64 {
|
||||
#[cfg(test)]
|
||||
@@ -1620,4 +1784,8 @@ thread_local! {
|
||||
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the `JSINCLUDE` folders in place of the environment's.
|
||||
pub(crate) static TEST_JSINCLUDE: RefCell<Option<Vec<std::path::PathBuf>>> = const { RefCell::new(None) };
|
||||
/// Tests: the time since a run started, in place of its clock's.
|
||||
pub(crate) static TEST_ELAPSED: Cell<Option<std::time::Duration>> = const { Cell::new(None) };
|
||||
/// Tests: runs have no clock, as in a wasm build.
|
||||
pub(crate) static TEST_NO_CLOCK: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
@@ -151,6 +151,8 @@ mod save;
|
||||
mod saveoptions;
|
||||
mod scalestrokes;
|
||||
mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
mod script_run;
|
||||
|
||||
@@ -350,6 +350,31 @@ fn gradients_rasterize_and_flat_areas_stay_vector() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_rasterized_area_is_placed_whole() {
|
||||
let _settings = settings_lock();
|
||||
let mut s = session();
|
||||
// 5569 pt long: more than the renderer's 32,768 pixels a side at the 64 Mpx limit's scale.
|
||||
let g = rect(&mut s, 10.0, 10.0, 100.0, 5569.0, "#000000");
|
||||
run(
|
||||
&mut s,
|
||||
"paint.setFill",
|
||||
json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}),
|
||||
);
|
||||
run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40}));
|
||||
let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "lineArtPpi": 1200, "gradientPpi": 1200}));
|
||||
assert_eq!(rasterized, 1);
|
||||
let mut placed = vec![];
|
||||
node(&s, ids[0]).walk(&mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
placed.push((im.height, im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)))));
|
||||
}
|
||||
});
|
||||
let [(height, b)] = placed[..] else { panic!("one image: {placed:?}") };
|
||||
assert!(height <= vectorcraft_render::MAX_RASTER_SIDE, "{height} pixels");
|
||||
assert!(b.y0 <= 10.0 && b.y1 >= 5579.0, "the image covers the strip: {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_says_when_an_image_could_not_be_decoded() {
|
||||
let _settings = settings_lock();
|
||||
|
||||
@@ -368,6 +368,31 @@ fn a_transparent_image_is_flattened_with_the_art_under_it_which_stays() {
|
||||
assert_eq!(colour_at(page, 10.0, 20.0), [255, 0, 0], "the square outside the image");
|
||||
}
|
||||
|
||||
/// A transparent image longer than the renderer draws at its own resolution (32,768 pixels a
|
||||
/// side) is flattened whole, at a lower resolution.
|
||||
#[test]
|
||||
fn a_long_transparent_image_is_flattened_whole() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 4600})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 4600})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let p = json!({"name": "i.png", "dataBase64": vectorcraft_format::base64_encode(&png(2000, 1600, [0, 0, 0, 128])), "at": [50, 50]});
|
||||
s.execute("file.place", &p).unwrap();
|
||||
// 10 × 4500 pt: about 600 ppi, so 37,500 pixels long.
|
||||
s.execute("object.setBounds", &json!({"x": 10, "y": 10, "width": 10, "height": 4500, "reference": 0})).unwrap();
|
||||
let before = [colour_at(&s.doc().unwrap().doc, 15.0, 100.0), colour_at(&s.doc().unwrap().doc, 15.0, 4400.0)];
|
||||
assert!(before.iter().all(|c| c[0] < 200), "the image darkens the red: {before:?}");
|
||||
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7"})).unwrap();
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("flattened with the art under them")), "{r}");
|
||||
s.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let after = [colour_at(d, 15.0, 100.0), colour_at(d, 15.0, 4400.0)];
|
||||
for (a, b) in before.iter().zip(&after) {
|
||||
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 3), "{before:?} {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `size`×`size` PNG of a black disk of radius `r` pixels with an anti-aliased edge, clear
|
||||
/// around it, 72 ppi.
|
||||
fn disk(size: u32, r: f64) -> Vec<u8> {
|
||||
|
||||
@@ -1461,6 +1461,42 @@ fn rasterize_replaces_selection_with_image() {
|
||||
assert_eq!(selected(&s), vec![img]);
|
||||
}
|
||||
|
||||
/// Rasterize refuses art that would be longer than the renderer draws (32,768 pixels a side), and
|
||||
/// the art stays as it was; at a resolution that fits, the image covers all of it.
|
||||
#[test]
|
||||
fn rasterize_refuses_an_image_longer_than_the_renderer_draws() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 100.0, 5569.0);
|
||||
sel(&mut s, &[a]);
|
||||
let vb = s.doc().unwrap().doc.bounds_of(&[a], true).unwrap();
|
||||
let before = (undo_len(&s), node(&s, a));
|
||||
let e = s.execute("object.rasterize", &json!({"ppi": 600, "padding": 0})).unwrap_err().to_string();
|
||||
assert!(e.contains("too large"), "{e}");
|
||||
assert_eq!((undo_len(&s), node(&s, a)), before);
|
||||
let img = id_of(&s.execute("object.rasterize", &json!({"ppi": 400, "padding": 0})).unwrap());
|
||||
let n = node(&s, img);
|
||||
let NodeKind::Image(im) = &n.kind else { panic!() };
|
||||
assert!(im.height <= vectorcraft_render::MAX_RASTER_SIDE, "{} pixels", im.height);
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(close(b.y0, vb.y0) && b.y1 >= vb.y1, "{b:?} covers {vb:?}");
|
||||
}
|
||||
|
||||
/// Art that snaps to exactly 32,768 pixels a side is rasterized, wherever it is on the canvas.
|
||||
#[test]
|
||||
fn rasterize_takes_art_that_snaps_to_32768_pixels_a_side() {
|
||||
let scale = 400.0 / 72.0;
|
||||
for y in [100_000.0, 250_000.0, 333_333.3, 777_777.7] {
|
||||
let mut s = session();
|
||||
let probe = rect(&mut s, 10.0, y, 100.0, 5898.0);
|
||||
let vb = s.doc().unwrap().doc.bounds_of(&[probe], true).unwrap();
|
||||
let h = 5898.0 + (32_767.8 / scale - vb.height());
|
||||
let a = rect(&mut s, 200.0, y, 100.0, h);
|
||||
sel(&mut s, &[a]);
|
||||
let r = s.execute("object.rasterize", &json!({"ppi": 400, "padding": 0})).unwrap_or_else(|e| panic!("at y = {y}: {e}"));
|
||||
assert_eq!(r["height"].as_u64(), Some(u64::from(vectorcraft_render::MAX_RASTER_SIDE)), "at y = {y}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rasterize refuses a resolution given as text or as another value that is not a number, and the
|
||||
/// selected art stays as it was.
|
||||
#[test]
|
||||
|
||||
@@ -980,6 +980,174 @@ fn painted_pieces_keep_to_the_effects_budget() {
|
||||
assert!((350..=100_000).contains(&paths), "{paths} paths");
|
||||
}
|
||||
|
||||
/// A clock for a document's deferrals that reads `step` milliseconds later each time it is read;
|
||||
/// the test changes the step as it goes.
|
||||
fn stepping_clock(step: &std::sync::Arc<std::sync::atomic::AtomicU64>) -> vectorcraft_plugins::deferred::Clock {
|
||||
let (now, step) = (std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), step.clone());
|
||||
std::sync::Arc::new(move || Some(now.fetch_add(step.load(std::sync::atomic::Ordering::Relaxed), std::sync::atomic::Ordering::Relaxed)))
|
||||
}
|
||||
|
||||
/// While a document is drawn on screen, the plug-in effects of its first view share a time budget.
|
||||
/// A stage left out draws its input art, is listed by `effect.deferredStatus`, and stays left out
|
||||
/// on later drawings; Effect › Refresh Deferred Effects runs it again with a fresh budget, and an
|
||||
/// export draws every stage. Another document has a budget of its own.
|
||||
#[test]
|
||||
fn the_first_view_defers_plug_in_effects_past_its_budget() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, "#ff0000");
|
||||
let b = rect(&mut s, 30.0, "#ff0000");
|
||||
for (id, x) in [("test.engine.deferred.a", 100.0), ("test.engine.deferred.b", 140.0)] {
|
||||
let out = json!({"objects": [{"path": square_at(x)}]}).to_string();
|
||||
install_wat(&mut s, &tpl::returning(&tpl::manifest(id, "effect", "{}"), &out));
|
||||
}
|
||||
run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.deferred.a"}));
|
||||
run(&mut s, "effect.apply", json!({"ids": [b.0], "effect": "plugin.test.engine.deferred.b"}));
|
||||
// Each reading is 3 s later: the first run's result comes back after the budget, and the
|
||||
// second run doesn't start.
|
||||
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
|
||||
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
|
||||
s.doc_mut().unwrap().plugin_effects = fx.clone();
|
||||
let img = fx.view(|| drawn(&s));
|
||||
fx.first_view_done();
|
||||
assert_eq!((img.pixel(15, 15), img.pixel(35, 15), img.pixel(110, 50), img.pixel(150, 50)), (RED, RED, WHITE, WHITE), "the input art");
|
||||
assert_eq!(fx.take_report(), Some(2));
|
||||
let status = run(&mut s, "effect.deferredStatus", json!({}));
|
||||
let listed = |id: NodeId, plugin: &str| json!({"objectId": id.0, "effectIndex": 0, "pluginId": plugin, "reason": "budget"});
|
||||
assert_eq!(status, json!({"budgetMs": 2000, "effects": [listed(a, "test.engine.deferred.a"), listed(b, "test.engine.deferred.b")]}));
|
||||
assert_eq!(fx.view(|| drawn(&s)).pixel(110, 50), WHITE, "a later drawing leaves it deferred");
|
||||
|
||||
// Refreshed with a fresh budget, in which the clock stands still.
|
||||
assert!(s.execute("effect.refreshDeferred", &json!({"ids": ["a"]})).is_err());
|
||||
assert!(s.execute("effect.refreshDeferred", &json!({"ids": [999_999]})).is_err(), "not an object of the document");
|
||||
step.store(0, std::sync::atomic::Ordering::Relaxed);
|
||||
let refreshed = run(&mut s, "effect.refreshDeferred", json!({"ids": [a.0]}));
|
||||
assert_eq!(refreshed, json!({"refreshed": 1, "stillDeferred": 0, "failed": 0}));
|
||||
let img = fx.view(|| drawn(&s));
|
||||
assert_eq!((img.pixel(110, 50), img.pixel(150, 50)), (RED, WHITE));
|
||||
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([listed(b, "test.engine.deferred.b")]));
|
||||
|
||||
// An export draws every stage; the view then uses the result.
|
||||
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
|
||||
let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert!(svg.contains(r#"<rect x="140" y="40" width="20" height="20""#), "the square at 140: {svg}");
|
||||
assert_eq!(fx.view(|| drawn(&s)).pixel(150, 50), RED);
|
||||
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([]));
|
||||
assert!(s.execute("effect.refreshDeferred", &json!({})).is_err(), "nothing is deferred");
|
||||
|
||||
// Another document: its first view has a budget of its own.
|
||||
let mut other = session();
|
||||
let c = rect(&mut other, 50.0, "#ff0000");
|
||||
let out = json!({"objects": [{"path": square_at(170.0)}]}).to_string();
|
||||
install_wat(&mut other, &tpl::returning(&tpl::manifest("test.engine.deferred.c", "effect", "{}"), &out));
|
||||
run(&mut other, "effect.apply", json!({"ids": [c.0], "effect": "plugin.test.engine.deferred.c"}));
|
||||
let still = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
let fx_c = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&still));
|
||||
other.doc_mut().unwrap().plugin_effects = fx_c.clone();
|
||||
assert_eq!(fx_c.view(|| drawn(&other)).pixel(180, 50), RED);
|
||||
fx_c.first_view_done();
|
||||
assert_eq!(fx_c.take_report(), Some(0));
|
||||
}
|
||||
|
||||
/// Deferred stages are listed where their effects are: after an effect that changes no geometry,
|
||||
/// and on a fill after a Transform effect that reaches its appearance, each of two instances of
|
||||
/// one plug-in at its own place.
|
||||
#[test]
|
||||
fn deferred_stages_are_listed_at_their_effects_places() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, "#ff0000");
|
||||
let b = rect(&mut s, 60.0, "#ff0000");
|
||||
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
|
||||
// An effect that paints its pieces: the object is drawn from its reshaped art.
|
||||
install_wat(&mut s, &tpl::returning(&painting("test.engine.deferred.at", true), &out));
|
||||
const FX: &str = "plugin.test.engine.deferred.at";
|
||||
run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "stylize.dropShadow"}));
|
||||
for _ in 0..2 {
|
||||
run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": FX}));
|
||||
}
|
||||
run(&mut s, "effect.apply", json!({"ids": [b.0], "effect": "distort.transform", "params": {"strokes": true}, "item": 0}));
|
||||
for _ in 0..2 {
|
||||
run(&mut s, "effect.apply", json!({"ids": [b.0], "effect": FX, "item": 0}));
|
||||
}
|
||||
// No run has time to give a result.
|
||||
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
|
||||
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
|
||||
s.doc_mut().unwrap().plugin_effects = fx.clone();
|
||||
fx.view(|| drawn(&s));
|
||||
let places = run(&mut s, "effect.deferredStatus", json!({}))["effects"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| (e["objectId"].as_u64().unwrap(), e["item"].as_u64(), e["effectIndex"].as_u64().unwrap()))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(places, [(a.0, None, 1), (a.0, None, 2), (b.0, Some(0), 1), (b.0, Some(0), 2)]);
|
||||
}
|
||||
|
||||
/// A refresh that does not draw a stage (its object, or a group holding it, is hidden) leaves it
|
||||
/// deferred, and a stage whose effect has been removed or hidden, or whose object has been removed,
|
||||
/// is no longer listed and does not enable Effect › Refresh Deferred Effects.
|
||||
#[test]
|
||||
fn refresh_keeps_stages_it_did_not_draw_and_drops_removed_ones() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, "#ff0000");
|
||||
let b = rect(&mut s, 30.0, "#ff0000");
|
||||
let c = rect(&mut s, 50.0, "#ff0000");
|
||||
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
|
||||
install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.kept", "effect", "{}"), &out));
|
||||
run(&mut s, "effect.apply", json!({"ids": [a.0, b.0, c.0], "effect": "plugin.test.engine.deferred.kept"}));
|
||||
run(&mut s, "select.set", json!({"ids": [c.0]}));
|
||||
let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
|
||||
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
|
||||
s.doc_mut().unwrap().plugin_effects = fx.clone();
|
||||
fx.view(|| drawn(&s));
|
||||
fx.first_view_done();
|
||||
let listed = |s: &mut Session| {
|
||||
run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(listed(&mut s), [a.0, b.0, c.0]);
|
||||
|
||||
s.execute("object.hide", &json!({"ids": [a.0, g.0]})).unwrap();
|
||||
step.store(0, std::sync::atomic::Ordering::Relaxed);
|
||||
let refreshed = run(&mut s, "effect.refreshDeferred", json!({"ids": [a.0, c.0]}));
|
||||
assert_eq!(refreshed, json!({"refreshed": 0, "stillDeferred": 2, "failed": 0}), "a hidden object is not drawn");
|
||||
assert_eq!(listed(&mut s), [a.0, b.0, c.0]);
|
||||
|
||||
run(&mut s, "effect.remove", json!({"ids": [a.0], "index": 0}));
|
||||
assert_eq!(listed(&mut s), [b.0, c.0], "its effect was removed");
|
||||
run(&mut s, "effect.setParams", json!({"ids": [b.0], "index": 0, "visible": false}));
|
||||
assert_eq!(listed(&mut s), [c.0], "its effect was hidden");
|
||||
s.execute("edit.clear", &json!({"ids": [b.0, g.0]})).unwrap();
|
||||
assert_eq!(listed(&mut s), Vec::<u64>::new(), "its object was deleted");
|
||||
assert!(s.execute("effect.refreshDeferred", &json!({})).is_err(), "nothing is deferred");
|
||||
}
|
||||
|
||||
/// A deferred stage in a symbol's art is listed by the object in that art, and a refresh runs it
|
||||
/// where the symbol is placed.
|
||||
#[test]
|
||||
fn deferred_stages_in_symbol_art_are_listed_and_refreshed() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, "#ff0000");
|
||||
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
|
||||
install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.symbol", "effect", "{}"), &out));
|
||||
run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.deferred.symbol"}));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let instance = run(&mut s, "symbol.new", json!({"name": "Deferred"}))["id"].as_u64().unwrap();
|
||||
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
|
||||
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
|
||||
s.doc_mut().unwrap().plugin_effects = fx.clone();
|
||||
fx.view(|| drawn(&s));
|
||||
fx.first_view_done();
|
||||
assert_eq!(fx.take_report(), Some(1));
|
||||
let effects = run(&mut s, "effect.deferredStatus", json!({}))["effects"].clone();
|
||||
let object = effects[0]["objectId"].as_u64().unwrap();
|
||||
assert_eq!(effects.as_array().map(Vec::len), Some(1), "{effects}");
|
||||
assert!(object != instance && s.doc().unwrap().doc.node(NodeId(object)).is_none(), "an object of the symbol's art: {effects}");
|
||||
|
||||
step.store(0, std::sync::atomic::Ordering::Relaxed);
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0}));
|
||||
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([]));
|
||||
}
|
||||
|
||||
/// `CRAFT_PLUGIN_PAINTS_WASM=<folder>` saves a test live effect to try in the app
|
||||
/// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its
|
||||
/// object's stroke is 5 pt wide, and hands the geometry back otherwise.
|
||||
|
||||
@@ -130,6 +130,28 @@ fn print_as_bitmap_prints_an_image_of_each_artboard() {
|
||||
assert!(crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().is_none());
|
||||
}
|
||||
|
||||
/// Print as Bitmap of an artboard longer than the renderer draws at the raster effects resolution
|
||||
/// (32,768 pixels a side) prints an image of all of it, at a lower resolution.
|
||||
#[test]
|
||||
fn print_as_bitmap_prints_all_of_a_long_artboard() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 9000, "height": 100})).unwrap();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 100})).unwrap();
|
||||
let set = settings(json!({"advanced": {"printAsBitmap": true}}));
|
||||
let saved = s.prefs.flattener_presets.clone();
|
||||
let bitmap = crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().unwrap();
|
||||
let mut placed = vec![];
|
||||
bitmap.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
placed.push((im.width, im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)))));
|
||||
}
|
||||
});
|
||||
let [(width, b)] = placed[..] else { panic!("one image: {placed:?}") };
|
||||
assert!(width <= vectorcraft_render::MAX_RASTER_SIDE, "{width} pixels");
|
||||
assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}");
|
||||
}
|
||||
|
||||
/// Appearance of Black › Printing / Exporting (#394): Print as Bitmap draws pure CMYK black as RGB
|
||||
/// black when `rich_black` is on.
|
||||
#[test]
|
||||
|
||||
@@ -170,6 +170,55 @@ fn a_stopped_run_reports_its_diagnostics_and_its_unended_line() {
|
||||
assert_eq!(texts(&mut s, "end"), ["ended: stopped"]);
|
||||
}
|
||||
|
||||
/// A report line counts one host call in the singular, and gives a run without a clock as "time
|
||||
/// unavailable".
|
||||
#[test]
|
||||
fn a_report_line_counts_one_host_call_in_the_singular_and_says_when_time_is_unavailable() {
|
||||
use crate::script::console::{Entry, Slow};
|
||||
let report = |ms: Option<u64>, host_calls: u64| Entry::Report { ms, host_calls, slowest: vec![] }.text();
|
||||
assert_eq!(report(Some(3), 0), "3 ms, 0 host calls");
|
||||
assert_eq!(report(Some(3), 1), "3 ms, 1 host call");
|
||||
assert_eq!(report(Some(0), 2), "0 ms, 2 host calls");
|
||||
assert_eq!(report(None, 0), "time unavailable, 0 host calls");
|
||||
assert_eq!(report(None, 1), "time unavailable, 1 host call");
|
||||
assert_eq!(report(None, 2), "time unavailable, 2 host calls");
|
||||
let slowest = vec![Slow { id: "a.b".into(), calls: 1, total_ms: 4, max_ms: 4 }];
|
||||
assert_eq!(Entry::Report { ms: None, host_calls: 1, slowest }.text(), "time unavailable, 1 host call; slowest: a.b ×1 4 ms");
|
||||
}
|
||||
|
||||
/// A run whose job is gone still ends its console entry, once, with its own number and name and no
|
||||
/// report line: as stopped when it is abandoned, as an internal fault when a slice finds it gone.
|
||||
/// The session can start the next run.
|
||||
#[test]
|
||||
fn a_run_whose_job_is_gone_still_ends_its_console_entry() {
|
||||
for abandon in [true, false] {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
run(&mut s, "$.writeln('one'); while (true) {}").unwrap();
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(script::forget_job(&s));
|
||||
if abandon {
|
||||
assert!(s.script_abandon());
|
||||
} else {
|
||||
let e = s.script_pump().unwrap().unwrap_err();
|
||||
assert_eq!(e.to_string(), "the script's run is no longer available");
|
||||
}
|
||||
assert!(!s.script_running());
|
||||
let all = lines(&mut s);
|
||||
let kinds: Vec<&str> = all.iter().map(|(_, k, _)| k.as_str()).collect();
|
||||
assert_eq!(kinds, ["start", "output", "end"], "{all:?}");
|
||||
assert_eq!(all[2].2, if abandon { "ended: stopped" } else { "ended: internal" });
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
assert_eq!((c["lines"][2]["run"].as_u64(), c["lines"][2]["name"].as_str()), (Some(1), Some("t.js")));
|
||||
assert!(!s.script_abandon() && s.script_pump().is_none(), "nothing is left to end");
|
||||
assert_eq!(lines(&mut s).len(), 3, "the entry ends once");
|
||||
s.script_frames = false;
|
||||
run(&mut s, "$.writeln('two')").unwrap();
|
||||
assert_eq!(texts(&mut s, "end").last().map(String::as_str), Some("ended: finished"), "the next run starts");
|
||||
assert_eq!(lines(&mut s).last().map(|l| l.0), Some(2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_are_numbered_a_busy_run_adds_nothing_and_clear_keeps_the_report() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
//! `alert`, `confirm` and `prompt` in a script: their arguments and results, the answers a run with
|
||||
//! nobody to ask takes from `answers`, the wait in the app, Stop, and the report's `dialogs`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::{DialogAnswer, DialogKind, ScriptDialog, dialogs};
|
||||
use crate::*;
|
||||
|
||||
/// One open document with one rectangle.
|
||||
fn one_doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn art(s: &Session) -> (String, usize) {
|
||||
let d = &s.documents()[0];
|
||||
(format!("{:?}", d.doc.layers), d.history.undo.len())
|
||||
}
|
||||
|
||||
fn headless(s: &mut Session, source: &str, answers: Value) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "d.js", "answers": answers}))
|
||||
}
|
||||
|
||||
/// A run in the app of `source`, one slice in.
|
||||
fn framed(s: &mut Session, source: &str) {
|
||||
s.script_frames = true;
|
||||
assert_eq!(s.execute("script.run", &json!({"source": source, "name": "d.js"})).unwrap()["running"], true);
|
||||
assert!(s.script_pump().is_none());
|
||||
}
|
||||
|
||||
/// Pumps the run in the app until it ends or waits at a dialog (`None`).
|
||||
fn pump(s: &mut Session) -> Option<Result<Value>> {
|
||||
for _ in 0..10_000 {
|
||||
if s.script_dialog().is_some() {
|
||||
return None;
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
return Some(r);
|
||||
}
|
||||
}
|
||||
panic!("the run neither ended nor waited");
|
||||
}
|
||||
|
||||
fn answers(list: &[Value]) -> Value {
|
||||
Value::Array(list.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notification_signatures_and_returns() {
|
||||
let mut s = one_doc();
|
||||
let source = "vc.log(typeof alert('a')); alert(42, 'Title', 1);\
|
||||
vc.log(confirm('c')); vc.log(confirm('n', true, undefined));\
|
||||
vc.log(prompt('p', 'pre')); vc.log(prompt({toString: function () { return 'own'; }}, '', 'T'));";
|
||||
let r = headless(
|
||||
&mut s,
|
||||
source,
|
||||
answers(&[
|
||||
json!({"kind": "alert", "value": "ok"}),
|
||||
json!({"kind": "alert", "value": "ok"}),
|
||||
json!({"kind": "confirm", "value": true}),
|
||||
json!({"kind": "confirm", "value": false}),
|
||||
json!({"kind": "prompt", "value": "typed"}),
|
||||
json!({"kind": "prompt", "value": null}),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!(["undefined", true, false, "typed", null]), "{r}");
|
||||
assert_eq!(
|
||||
r["dialogs"],
|
||||
json!([
|
||||
{"kind": "alert", "message": "a", "title": "Script Alert", "errorIcon": false, "answer": "ok"},
|
||||
{"kind": "alert", "message": "42", "title": "Title", "errorIcon": true, "answer": "ok"},
|
||||
{"kind": "confirm", "message": "c", "title": "Script Alert", "noAsDefault": false, "answer": true},
|
||||
{"kind": "confirm", "message": "n", "title": "Script Alert", "noAsDefault": true, "answer": false},
|
||||
{"kind": "prompt", "message": "p", "title": "Script Alert", "preset": "pre", "answer": "typed"},
|
||||
{"kind": "prompt", "message": "own", "title": "T", "preset": "", "answer": null},
|
||||
])
|
||||
);
|
||||
assert_eq!((r["dialogCount"].clone(), r["dialogsTruncated"].clone()), (json!(6), json!(false)));
|
||||
let has = headless(&mut s, "vc.log(vc.api.has('dialogs'));", json!([])).unwrap();
|
||||
assert_eq!(has["log"], json!([true]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_answers_follow_call_order() {
|
||||
let mut s = one_doc();
|
||||
let source = "var out = []; [1, 2].forEach(function (i) { out.push(confirm('q' + i)); }); out.push(prompt('r', 'x')); vc.log(out.join());";
|
||||
let r = headless(
|
||||
&mut s,
|
||||
source,
|
||||
answers(&[json!({"kind": "confirm", "value": false}), json!({"kind": "confirm", "value": true}), json!({"kind": "prompt", "value": "z"})]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!(["false,true,z"]), "a callback of a built-in takes its answer too: {r}");
|
||||
assert_eq!(headless(&mut s, "1", json!({})).unwrap()["dialogCount"], 0, "an empty object is an empty list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_mismatched_answer_rolls_back() {
|
||||
let mut s = one_doc();
|
||||
let before = art(&s);
|
||||
let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});";
|
||||
for (source, given, says) in [
|
||||
(format!("{edit} try {{ alert('x'); }} catch (e) {{ vc.log('caught'); }}"), json!([]), "no answer left"),
|
||||
(format!("{edit} alert('x');"), answers(&[json!({"kind": "confirm", "value": true})]), "is for confirm, not alert"),
|
||||
(format!("{edit} alert('x');"), answers(&[json!({"kind": "alert", "value": "ok"}), json!({"kind": "alert", "value": "ok"})]), "1 answer"),
|
||||
] {
|
||||
let e = headless(&mut s, &source, given).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{e}");
|
||||
assert_eq!(art(&s), before, "{source}");
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["kind"], "limit", "{report}");
|
||||
assert_eq!(report["log"], json!([]), "a missing answer cannot be caught");
|
||||
assert_eq!(report["dialogCount"], 1);
|
||||
}
|
||||
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "ok");
|
||||
headless(&mut s, "alert('x')", json!([])).unwrap_err();
|
||||
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_answers_are_rejected_before_run() {
|
||||
let mut s = one_doc();
|
||||
let before = art(&s);
|
||||
let many: Vec<Value> = (0..=dialogs::MAX_ANSWERS).map(|_| json!({"kind": "alert", "value": "ok"})).collect();
|
||||
let big: Vec<Value> = (0..80).map(|_| json!({"kind": "prompt", "value": "x".repeat(16_000)})).collect();
|
||||
for given in [
|
||||
json!({"a": 1}),
|
||||
json!("ok"),
|
||||
json!([1]),
|
||||
json!([{"kind": "alert"}]),
|
||||
json!([{"kind": "alert", "value": true}]),
|
||||
json!([{"kind": "confirm", "value": "yes"}]),
|
||||
json!([{"kind": "prompt", "value": 3}]),
|
||||
json!([{"kind": "prompt", "value": "x".repeat(dialogs::MAX_PROMPT_BYTES + 1)}]),
|
||||
json!([{"kind": "other", "value": "ok"}]),
|
||||
json!([{"kind": "alert", "value": "ok", "extra": 1}]),
|
||||
Value::Array(many),
|
||||
Value::Array(big),
|
||||
] {
|
||||
let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});";
|
||||
let r = s.execute("script.run", &json!({"source": source, "answers": given}));
|
||||
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
|
||||
assert_eq!(art(&s), before);
|
||||
}
|
||||
s.script_frames = true;
|
||||
let r = s.execute("script.run", &json!({"source": "1", "answers": [{"kind": "alert", "value": "ok"}]}));
|
||||
assert!(matches!(r, Err(EngineError::BadParams { .. })), "a run in the app takes no answers: {r:?}");
|
||||
assert!(!s.script_running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() {
|
||||
let mut s = one_doc();
|
||||
framed(
|
||||
&mut s,
|
||||
"vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); var a = confirm('Go?', true, 'Ask'); var b = prompt('Name', 'n'); vc.log([a, b]);",
|
||||
);
|
||||
let want = ScriptDialog {
|
||||
kind: DialogKind::Confirm,
|
||||
message: "Go?".into(),
|
||||
title: Some("Ask".into()),
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
assert!(!s.script_answer(DialogAnswer::Confirm(true)), "nothing waits until the run goes on");
|
||||
assert!(pump(&mut s).is_none());
|
||||
assert_eq!(s.script_dialog().unwrap().preset, "n");
|
||||
assert!(!s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES + 1)))));
|
||||
assert!(s.script_answer(DialogAnswer::Prompt(Some("Ann".into()))));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([[true, "Ann"]]));
|
||||
assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step");
|
||||
assert_eq!(r["dialogs"][1]["answer"], "Ann");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_cancel_returns_null() {
|
||||
let mut s = one_doc();
|
||||
framed(&mut s, "vc.log(prompt('Name', '') === null);");
|
||||
assert!(s.script_answer(DialogAnswer::Prompt(None)));
|
||||
assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialog_loop_stops_or_exhausts() {
|
||||
let mut s = one_doc();
|
||||
let before = art(&s);
|
||||
let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); while (1) { alert('x'); }";
|
||||
let three: Vec<Value> = (0..3).map(|_| json!({"kind": "alert", "value": "ok"})).collect();
|
||||
let e = headless(&mut s, source, Value::Array(three)).unwrap_err().to_string();
|
||||
assert!(e.contains("no answer left"), "{e}");
|
||||
assert_eq!(s.script_report().unwrap()["dialogCount"], 4);
|
||||
assert_eq!(art(&s), before);
|
||||
framed(&mut s, source);
|
||||
for _ in 0..3 {
|
||||
assert!(s.script_answer(DialogAnswer::Ok));
|
||||
assert!(pump(&mut s).is_none());
|
||||
}
|
||||
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
|
||||
assert_eq!(s.script_dialog(), None, "a run asked to stop no longer waits");
|
||||
assert!(!s.script_answer(DialogAnswer::Ok));
|
||||
assert!(s.script_pump().unwrap().is_err());
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!((report["kind"].as_str(), report["dialogCount"].as_u64()), (Some("stopped"), Some(4)), "{report}");
|
||||
assert_eq!(report["dialogs"][3]["answer"], "stop");
|
||||
assert_eq!(art(&s), before, "Stop at the first or any later dialog leaves no undo step");
|
||||
framed(&mut s, source);
|
||||
assert!(s.script_abandon(), "quitting while a dialog waits abandons the run");
|
||||
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "stop");
|
||||
assert_eq!(art(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialog_text_limits_and_controls() {
|
||||
let mut s = one_doc();
|
||||
let source = format!(
|
||||
"var out = [];\
|
||||
function t(f) {{ try {{ f(); out.push('opened'); }} catch (e) {{ out.push(e.name); }} }}\
|
||||
t(function () {{ alert('x'); }});\
|
||||
t(function () {{ alert(new Array({m}).join('m')); }});\
|
||||
t(function () {{ alert('m', new Array({t}).join('t')); }});\
|
||||
t(function () {{ prompt('m', new Array({m}).join('p')); }});\
|
||||
t(function () {{ alert(); }});\
|
||||
t(function () {{ prompt('m'); }});\
|
||||
t(function () {{ alert({{toString: function () {{ throw new Error('no'); }}}}); }});\
|
||||
t(function () {{ alert(undefined); }});\
|
||||
vc.log(out.join());",
|
||||
m = dialogs::MAX_MESSAGE_BYTES + 2,
|
||||
t = dialogs::MAX_TITLE_BYTES + 2,
|
||||
);
|
||||
let r = headless(&mut s, &source, answers(&[json!({"kind": "alert", "value": "ok"}), json!({"kind": "alert", "value": "ok"})])).unwrap();
|
||||
assert_eq!(r["log"], json!(["opened,RangeError,RangeError,RangeError,TypeError,TypeError,Error,opened"]), "{r}");
|
||||
assert_eq!(r["dialogs"][1]["message"], "undefined", "an explicit undefined message is a message");
|
||||
assert_eq!(dialogs::shown_text("a\r\nb\rc\nd\te\u{7}\u{7f}", true), "a\nb\nc\nd\u{2409}e\u{2407}\u{2421}");
|
||||
assert_eq!(dialogs::shown_text("a\nb", false), "a\u{240a}b", "a title stays on one line");
|
||||
assert_eq!(dialogs::cut_to("aé", 2), "a", "a cut keeps whole characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialog_transcript_on_success_and_failure() {
|
||||
let mut s = one_doc();
|
||||
let r = headless(&mut s, "alert('one'); throw new Error('later');", answers(&[json!({"kind": "alert", "value": "ok"})])).unwrap_err();
|
||||
assert!(r.to_string().contains("later"));
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["dialogs"], json!([{"kind": "alert", "message": "one", "title": "Script Alert", "errorIcon": false, "answer": "ok"}]));
|
||||
let ok = headless(&mut s, "1", json!([])).unwrap();
|
||||
assert_eq!((ok["dialogs"].clone(), ok["dialogCount"].clone()), (json!([]), json!(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialog_wait_does_not_spend_fuel() {
|
||||
let mut s = one_doc();
|
||||
framed(&mut s, "alert('x'); 1");
|
||||
for _ in 0..20 {
|
||||
assert!(s.script_pump().is_none(), "the run waits");
|
||||
}
|
||||
assert!(s.script_answer(DialogAnswer::Ok));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
let mut t = one_doc();
|
||||
let plain = headless(&mut t, "alert('x'); 1", answers(&[json!({"kind": "alert", "value": "ok"})])).unwrap();
|
||||
assert_eq!((r["fuelUsed"].clone(), r["hostCalls"].clone()), (plain["fuelUsed"].clone(), plain["hostCalls"].clone()), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_run_is_busy_while_dialog_waits() {
|
||||
let mut s = one_doc();
|
||||
framed(&mut s, "alert('x');");
|
||||
assert!(s.execute("script.run", &json!({"source": "1"})).is_err());
|
||||
assert!(s.script_dialog().is_some(), "the first run still waits");
|
||||
assert!(s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 1, "height": 1})).is_err(), "edits are refused while it waits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_in_a_callback_throws_in_the_app() {
|
||||
let mut s = one_doc();
|
||||
s.script_frames = true;
|
||||
let source = "var m = ''; [1].forEach(function () { try { alert('x'); } catch (e) { m = e.message; } }); vc.log(m);";
|
||||
s.execute("script.run", &json!({"source": source})).unwrap();
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}");
|
||||
assert_eq!(r["dialogCount"], 0);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize` and
|
||||
//! `toSource`, and what of them one run keeps to itself.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::{TEST_ELAPSED, TEST_NO_CLOCK};
|
||||
use crate::*;
|
||||
|
||||
/// The values `source` gives `vc.log`, in a run of its text.
|
||||
fn logged(s: &mut Session, source: &str) -> Value {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}"))["log"].clone()
|
||||
}
|
||||
|
||||
/// The one value `expr` gives, logged.
|
||||
fn value(s: &mut Session, expr: &str) -> Value {
|
||||
logged(s, &format!("vc.log({expr});"))[0].clone()
|
||||
}
|
||||
|
||||
/// The name of the error `statement` throws and its message, as `Name: message`.
|
||||
fn thrown(s: &mut Session, statement: &str) -> String {
|
||||
value(s, &format!("(function () {{ try {{ {statement}; return 'no error'; }} catch (e) {{ return e.name + ': ' + e.message; }} }})()"))
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_member_has_its_value() {
|
||||
let mut s = Session::new();
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let os = if cfg!(target_arch = "wasm32") {
|
||||
"Web"
|
||||
} else if cfg!(windows) {
|
||||
"Windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"macOS"
|
||||
} else if cfg!(target_os = "linux") {
|
||||
"Linux"
|
||||
} else if cfg!(target_os = "freebsd") {
|
||||
"FreeBSD"
|
||||
} else {
|
||||
"Unix"
|
||||
};
|
||||
for (expr, want) in [
|
||||
("$.about()", json!(format!("VectorCraft script engine {version}"))),
|
||||
("$.appEncoding", json!("UTF-8")),
|
||||
("$.build", json!(version)),
|
||||
("$.buildDate", json!(null)),
|
||||
("$.decimalPoint", json!(".")),
|
||||
("$.engineName", json!("VectorCraft")),
|
||||
("$.error", json!(null)),
|
||||
("$.flags", json!(0)),
|
||||
("$.gc() === undefined", json!(true)),
|
||||
("$.global === this", json!(true)),
|
||||
("typeof $.hiresTimer === 'number' && $.hiresTimer >= 0", json!(true)),
|
||||
("$.level", json!(0)),
|
||||
("\n$.line", json!(2)),
|
||||
("$.locale", json!("en")),
|
||||
("$.localize", json!(false)),
|
||||
("$.memCache", json!(0)),
|
||||
("$.os", json!(os)),
|
||||
("$.screens.length", json!(0)),
|
||||
("$.stack", json!("[global]:1\n")),
|
||||
("$.strict", json!(false)),
|
||||
("$.version", json!(version)),
|
||||
("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")),
|
||||
("vc.api.has('dollar')", json!(true)),
|
||||
] {
|
||||
assert_eq!(value(&mut s, expr), want, "{expr}");
|
||||
}
|
||||
assert_eq!(thrown(&mut s, "$.bp()"), "Error: $.bp: scripts here have no debugger");
|
||||
assert_eq!(thrown(&mut s, "$.colorPicker(0)"), "Error: $.colorPicker: scripts cannot show a dialog yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_members_keep_their_values_and_settable_ones_check_what_they_are_given() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(value(&mut s, "($.build = 'x', $.level = 3, $.os = 'y', [$.build === 'x', $.level, $.os === 'y'])"), json!([false, 0, false]));
|
||||
assert!(thrown(&mut s, "(function () { 'use strict'; $.version = '9'; })()").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "(function () { 'use strict'; $.error = null; })()").starts_with("TypeError"));
|
||||
assert_eq!(value(&mut s, "($.appEncoding = 'utf-8', $.appEncoding)"), json!("UTF-8"));
|
||||
assert!(thrown(&mut s, "$.appEncoding = 'ISO-8859-1'").starts_with("RangeError"));
|
||||
assert!(thrown(&mut s, "$.appEncoding = 8").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "$.memCache = 1024").starts_with("Error"));
|
||||
assert_eq!(value(&mut s, "($.flags = 512, [$.flags, $.localize])"), json!([512, true]));
|
||||
assert_eq!(value(&mut s, "($.flags = 512, $.flags = 0, [$.flags, $.localize])"), json!([0, false]));
|
||||
for bad in ["$.flags = 2", "$.flags = 513", "$.flags = -512"] {
|
||||
assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}");
|
||||
}
|
||||
assert!(thrown(&mut s, "$.flags = '512'").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "$.localize = 1").starts_with("TypeError"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_locale_starts_as_the_interfaces_and_a_change_lasts_one_run() {
|
||||
let mut s = Session::new();
|
||||
for (ui, want) in [("de", "de"), ("pt-br", "pt_BR"), ("zh-hant", "zh_TW"), ("zh-hans", "zh_CN"), ("auto", "en"), ("x", "en")] {
|
||||
s.ui_language = Some(ui.into());
|
||||
assert_eq!(value(&mut s, "$.locale"), json!(want), "{ui}");
|
||||
}
|
||||
s.ui_language = None;
|
||||
s.prefs.interface_language = "fr".into();
|
||||
assert_eq!(value(&mut s, "$.locale"), json!("fr"), "without a language from the app, the preference");
|
||||
s.ui_language = Some("de".into());
|
||||
let lookup = "localize({en: 'e', de: 'd', fr: 'f', fr_CA: 'c'})";
|
||||
assert_eq!(value(&mut s, &format!("[{lookup}, $.decimalPoint]")), json!(["d", ","]));
|
||||
let changed = format!(
|
||||
"$.locale = 'FR-ca'; var a = [$.locale, {lookup}]; $.locale = 'fr'; a.push({lookup}); $.locale = null; a.push($.locale, {lookup}); a"
|
||||
);
|
||||
assert_eq!(value(&mut s, &format!("(function () {{ {changed}; return a; }})()")), json!(["fr_CA", "c", "f", "de", "d"]));
|
||||
assert_eq!(value(&mut s, "($.locale = '', $.locale)"), json!("de"), "an empty locale is the interface's");
|
||||
assert_eq!(value(&mut s, "($.locale = 'en_US', $.locale)"), json!("en_US"));
|
||||
assert_eq!(value(&mut s, "$.locale"), json!("de"), "the next run starts with the interface's again");
|
||||
for bad in ["$.locale = 'german'", "$.locale = 'de_DE_x'", "$.locale = 'd'"] {
|
||||
assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}");
|
||||
}
|
||||
assert!(thrown(&mut s, "$.locale = 5").starts_with("TypeError"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_to_string_is_on_only_while_the_run_turns_it_on() {
|
||||
let mut s = Session::new();
|
||||
s.ui_language = Some("de".into());
|
||||
let text = "String({en: 'Open', de: 'Öffnen'})";
|
||||
assert_eq!(value(&mut s, text), json!("[object Object]"));
|
||||
assert_eq!(value(&mut s, &format!("($.localize = true, {text})")), json!("Öffnen"));
|
||||
assert_eq!(value(&mut s, text), json!("[object Object]"), "the next run starts with it off");
|
||||
assert_eq!(value(&mut s, "localize('%1 of %2', 3, 7)"), json!("3 of 7"), "localize works with it off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_source_writes_plain_data() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(value(&mut s, "toSource({a: [1, 'x'], b: null})"), json!(r#"({"a":[1, "x"], "b":null})"#));
|
||||
assert_eq!(value(&mut s, "[true, 2].toSource()"), json!("[true, 2]"));
|
||||
assert!(thrown(&mut s, "var o = {}; o.o = o; toSource(o)").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "toSource(vc)").starts_with("TypeError"), "a host object is not plain data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() {
|
||||
let mut s = Session::new();
|
||||
for name in ["HOME", "PATH", "USERPROFILE", "TEMP", "lang", ""] {
|
||||
assert_eq!(value(&mut s, &format!("$.getenv('{name}')")), json!(null), "{name}");
|
||||
}
|
||||
let process = std::env::var("OS").ok();
|
||||
let before = value(&mut s, "$.getenv('OS')");
|
||||
if let Some(os) = process.as_deref().filter(|v| v.len() <= 64 && v.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-@".contains(&b))) {
|
||||
assert_eq!(before, json!(os));
|
||||
}
|
||||
assert_eq!(value(&mut s, "($.setenv('OS', 'Test-1'), $.getenv('OS'))"), json!("Test-1"));
|
||||
assert_eq!(std::env::var("OS").ok(), process, "the process's environment stays as it was");
|
||||
assert_eq!(value(&mut s, "$.getenv('OS')"), before, "the next run reads the process's value again");
|
||||
assert!(thrown(&mut s, "$.setenv('HOME', 'x')").starts_with("Error"));
|
||||
assert!(thrown(&mut s, "$.setenv('LANG', 'a b')").starts_with("RangeError"));
|
||||
assert!(thrown(&mut s, &format!("$.setenv('LANG', '{}')", "a".repeat(65))).starts_with("RangeError"));
|
||||
assert!(thrown(&mut s, "$.setenv('LANG')").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "$.getenv(1)").starts_with("TypeError"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_line_and_stack_follow_the_running_code() {
|
||||
let mut s = Session::new();
|
||||
let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());";
|
||||
assert_eq!(logged(&mut s, source)[0], json!([3, "[global]:5\nwhere:3\n", true]));
|
||||
assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_waits_between_slices_until_its_time_has_passed() {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
TEST_ELAPSED.set(Some(Duration::ZERO));
|
||||
s.execute("script.run", &json!({"source": "vc.log(1); $.sleep(250); vc.log(2);", "name": "t.js"})).unwrap();
|
||||
let logs =
|
||||
|s: &mut Session| s.execute("script.console", &json!({})).unwrap()["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "log").count();
|
||||
assert!(s.script_pump().is_none());
|
||||
assert_eq!(logs(&mut s), 1);
|
||||
TEST_ELAPSED.set(Some(Duration::from_millis(249)));
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(s.script_pump().is_none());
|
||||
assert_eq!(logs(&mut s), 1, "the run waits");
|
||||
assert_eq!(s.script_sleep_left(), Some(Duration::from_millis(1)), "the app can wait this long before the next frame");
|
||||
TEST_ELAPSED.set(Some(Duration::from_millis(250)));
|
||||
let r = s.script_pump().unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([1, 2]));
|
||||
TEST_ELAPSED.set(None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sleeping_run_stops_when_asked() {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
TEST_ELAPSED.set(Some(Duration::ZERO));
|
||||
s.execute("script.run", &json!({"source": "$.sleep(1000); vc.log(2);", "name": "t.js"})).unwrap();
|
||||
assert!(s.script_pump().is_none());
|
||||
assert_eq!(s.script_sleep_left(), Some(Duration::from_secs(1)));
|
||||
s.execute("script.stop", &json!({})).unwrap();
|
||||
assert_eq!(s.script_sleep_left(), None, "a run asked to stop does not wait");
|
||||
assert!(s.script_pump().unwrap().is_err());
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "stopped");
|
||||
TEST_ELAPSED.set(None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_takes_milliseconds_from_0_to_1000() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(value(&mut s, "($.sleep(0), $.sleep(1), 'woke')"), json!("woke"));
|
||||
for bad in ["$.sleep(-1)", "$.sleep(1001)"] {
|
||||
assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}");
|
||||
}
|
||||
for bad in ["$.sleep()", "$.sleep('5')", "$.sleep(NaN)", "$.sleep(Infinity)"] {
|
||||
assert!(thrown(&mut s, bad).starts_with("TypeError"), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_throws_where_the_run_cannot_wait_instead_of_running_on() {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
TEST_ELAPSED.set(Some(Duration::ZERO));
|
||||
let source = "var o = {}; Object.defineProperty(o, 'x', { get: function () { $.sleep(250); vc.log('after'); return 1; } });
|
||||
try { o.x; } catch (e) { vc.log(e.name + ': ' + e.message); }
|
||||
try { [1].map(function () { $.sleep(250); vc.log('after'); }); } catch (e) { vc.log(e.name + ': ' + e.message); }
|
||||
[1].map(function () { $.sleep(0); });
|
||||
vc.log('done');";
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
|
||||
let r = s.script_pump().expect("the run does not wait").unwrap();
|
||||
TEST_ELAPSED.set(None);
|
||||
let message = "Error: $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code";
|
||||
assert_eq!(r["log"], json!([message, message, "done"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_throws_where_the_run_cannot_wait_without_a_clock_too() {
|
||||
let mut s = Session::new();
|
||||
TEST_NO_CLOCK.set(true);
|
||||
let source = "var o = {}; Object.defineProperty(o, 'x', { get: function () { $.sleep(250); return 1; } });
|
||||
try { o.x; vc.log('no error'); } catch (e) { vc.log(e.name); }
|
||||
$.sleep(250);
|
||||
vc.log('done');";
|
||||
let log = logged(&mut s, source);
|
||||
TEST_NO_CLOCK.set(false);
|
||||
assert_eq!(log, json!(["Error", "done"]), "the script's own code does not wait without a clock");
|
||||
}
|
||||
@@ -194,7 +194,6 @@ fn script_target_other_app_does_not_route() {
|
||||
("#target\nvc.log(1);", "#target needs a value"),
|
||||
("#targetengine \"session\"", "unsupported script directive: #targetengine"),
|
||||
("#engine \"main\"", "unsupported script directive: #engine"),
|
||||
("#strict on", "unsupported strict checking: #strict on"),
|
||||
("#strict maybe", "#strict takes on or off"),
|
||||
("#frobnicate 1", "unknown script directive: #frobnicate"),
|
||||
("#include \"x.jsxinc", "unterminated quote in #include"),
|
||||
@@ -223,12 +222,134 @@ fn script_name_comes_from_the_script_line() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The script's `ro`, with a read-only `x`.
|
||||
const READ_ONLY: &str = "var ro = {};\nObject.defineProperty(ro, 'x', {value: 1});\n";
|
||||
|
||||
#[test]
|
||||
fn script_strict_on_is_refused() {
|
||||
fn strict_on_runs_and_read_only_write_throws() {
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("script.run", &json!({"source": "#strict on\nvc.log(1);"})).unwrap_err().to_string();
|
||||
assert!(e.contains("unsupported strict checking: #strict on"), "{e}");
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "syntax");
|
||||
for head in ["#strict on\n", "//@strict on\n", "#strict ON\n", "#strict off\n#strict on\n"] {
|
||||
let source = format!("{head}{READ_ONLY}vc.log(1);\n ro.x = 2;\nvc.log(2);");
|
||||
let e = s.execute("script.run", &json!({"source": source})).unwrap_err().to_string();
|
||||
assert!(e.contains("TypeError: cannot assign to property 'x': it is read-only"), "{head}: {e}");
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["kind"], "thrown", "{head}");
|
||||
assert_eq!(report["log"], json!([1]), "{head}: the script ran up to the write");
|
||||
let line = head.lines().count() as u64 + 4;
|
||||
assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(line), Some(3)), "{head}: {report}");
|
||||
}
|
||||
// The error can be caught, and every kind of assignment is checked.
|
||||
let source = format!(
|
||||
"#strict on\n{READ_ONLY}var out = [];\nfunction t(f) {{ try {{ f(); out.push('wrote'); }} catch (e) {{ out.push(e.name); }} }}\nt(function () {{ ro.x = 2; }});\nt(function () {{ ro['x'] += 1; }});\nt(function () {{ ro.x++; }});\nt(function () {{ undefined = 1; }});\nt(function () {{ [].concat.length = 0; }});\nvc.log(out);\nvc.log(ro.x);"
|
||||
);
|
||||
let r = s.execute("script.run", &json!({"source": source})).unwrap();
|
||||
assert_eq!(r["log"], json!([["TypeError", "TypeError", "TypeError", "TypeError", "TypeError"], 1]));
|
||||
// Without the line, or with `#strict off` last, the write is ignored as before.
|
||||
for head in ["", "#strict off\n", "#strict on\n#strict off\n"] {
|
||||
let r = s.execute("script.run", &json!({"source": format!("{head}{READ_ONLY}ro.x = 2;\nvc.log(ro.x);")})).unwrap();
|
||||
assert_eq!(r["log"], json!([1]), "{head}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_on_rejects_getter_only_and_nonextensible_additions() {
|
||||
let mut s = Session::new();
|
||||
let source = "#strict on\nvar out = [];\nfunction t(f) { try { f(); out.push('wrote'); } catch (e) { out.push(String(e)); } }\n\
|
||||
var g = {get v() { return 1; }}, set = {set v(x) { this.got = x; }};\n\
|
||||
t(function () { g.v = 2; });\n\
|
||||
t(function () { Object.preventExtensions({}).n = 1; });\n\
|
||||
t(function () { Object.seal({a: 1}).n = 1; });\n\
|
||||
t(function () { Object.freeze({a: 1}).a = 2; });\n\
|
||||
t(function () { vc.extra = 1; });\n\
|
||||
var open = {};\nt(function () { open.n = 1; });\nt(function () { set.v = 3; });\nt(function () { Object.seal({a: 1}).a = 2; });\n\
|
||||
vc.log(out);\nvc.log(open.n);\nvc.log(set.got);";
|
||||
let r = s.execute("script.run", &json!({"source": source})).unwrap();
|
||||
assert_eq!(
|
||||
r["log"],
|
||||
json!([
|
||||
[
|
||||
"TypeError: cannot assign to property 'v': it has only a getter",
|
||||
"TypeError: cannot assign to property 'n': the object is not extensible",
|
||||
"TypeError: cannot assign to property 'n': the object is not extensible",
|
||||
"TypeError: cannot assign to property 'a': it is read-only",
|
||||
"TypeError: cannot assign to property 'extra': the object is not extensible",
|
||||
"wrote",
|
||||
"wrote",
|
||||
"wrote"
|
||||
],
|
||||
1,
|
||||
3
|
||||
])
|
||||
);
|
||||
let r = s.execute("script.run", &json!({"source": source.replacen("#strict on", "#strict off", 1)})).unwrap();
|
||||
assert_eq!(r["log"][0], json!(["wrote", "wrote", "wrote", "wrote", "wrote", "wrote", "wrote", "wrote"]), "off, nothing is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_on_does_not_enable_es5_early_errors() {
|
||||
let mut s = Session::new();
|
||||
let source = "#strict on\nwith ({w: 1}) { vc.log(w); }\nfunction f(a, a) { return a; }\nvc.log(f(1, 2));\nvc.log(010);\nundeclared = 4;\nvc.log(undeclared);\n\
|
||||
vc.log((function () { return typeof this; })());\nvc.log(delete Object.prototype);\nvar eval2 = 5;\nvc.log((function () { arguments = 6; return arguments; })());";
|
||||
let r = s.execute("script.run", &json!({"source": source})).unwrap();
|
||||
assert_eq!(r["log"], json!([1, 2, 8, 4, "object", false, 6]));
|
||||
// 'use strict' still makes the code strict mode code.
|
||||
let e = s.execute("script.run", &json!({"source": "#strict on\n'use strict';\nundeclared2 = 1;"})).unwrap_err().to_string();
|
||||
assert!(e.contains("ReferenceError"), "{e}");
|
||||
let e = s.execute("script.run", &json!({"source": "#strict on\n'use strict';\nwith ({}) {}"})).unwrap_err().to_string();
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_on_in_include_controls_expanded_run() {
|
||||
let base = folder("strict");
|
||||
write(&base.join("main/on.jsxinc"), "#strict on\nvar inc = 1;");
|
||||
write(&base.join("main/off.jsxinc"), "//@strict off\n");
|
||||
write(&base.join("main/writes.jsxinc"), &format!("{READ_ONLY}\n ro.x = 2;\n"));
|
||||
// An included file's line sets the checks for the script's own code too.
|
||||
let report = failed(&base, &format!("#include \"on.jsxinc\"\n{READ_ONLY}ro.x = 2;"));
|
||||
assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}");
|
||||
assert_eq!(report["line"], 4, "{report}");
|
||||
assert!(report.get("file").is_none(), "{report}");
|
||||
// A write in an included file is reported at its own line.
|
||||
let report = failed(&base, "#strict on\n#include \"writes.jsxinc\"");
|
||||
assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}");
|
||||
assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(4), Some(3)), "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("writes.jsxinc"), "{report}");
|
||||
// The last line of the expanded run wins, wherever it is.
|
||||
let r = run(&base, &format!("#strict on\n#include \"off.jsxinc\"\n{READ_ONLY}ro.x = 2;\nvc.log(ro.x);")).unwrap();
|
||||
assert_eq!(r["log"], json!([1]));
|
||||
let report = failed(&base, &format!("#include \"off.jsxinc\"\n#strict on\n{READ_ONLY}ro.x = 2;"));
|
||||
assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_mode_in_eval_file_is_scoped() {
|
||||
let base = folder("strict-eval");
|
||||
write(
|
||||
&base.join("main/on.jsx"),
|
||||
&format!(
|
||||
"#strict on\n{READ_ONLY}function w(o) {{ o.x = 2; }}\nvar inner;\ntry {{ ro.x = 2; inner = 'wrote'; }} catch (e) {{ inner = e.name; }}\n"
|
||||
),
|
||||
);
|
||||
write(&base.join("main/off.jsx"), &format!("#strict off\n{READ_ONLY}ro.x = 2;\n'off ran';"));
|
||||
write(&base.join("main/plain.jsx"), &format!("{READ_ONLY}ro.x = 2;\n'plain ran';"));
|
||||
// A file's own `#strict on` holds for its code, its functions included, and not the caller's.
|
||||
let r = run(
|
||||
&base,
|
||||
"$.evalFile('on.jsx');\nvar after;\ntry { ro.x = 3; after = 'ignored'; } catch (e) { after = e.name; }\nvar called;\ntry { w(ro); called = 'wrote'; } catch (e) { called = e.name; }\nvc.log([inner, after, called]);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([["TypeError", "ignored", "TypeError"]]));
|
||||
// A file without the line takes the caller's checks, and its own `#strict off` turns them off.
|
||||
let r = run(&base, "#strict on\nvc.log($.evalFile('off.jsx'));\nvar e1;\ntry { ro.x = 2; } catch (e) { e1 = e.name; }\nvc.log(e1);").unwrap();
|
||||
assert_eq!(r["log"], json!(["off ran", "TypeError"]), "the caller keeps its own checks");
|
||||
let report = failed(&base, "#strict on\n$.evalFile('plain.jsx');");
|
||||
assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("plain.jsx"), "{report}");
|
||||
assert_eq!(report["line"], 3, "{report}");
|
||||
assert_eq!(run(&base, "vc.log($.evalFile('plain.jsx'));").unwrap()["log"], json!(["plain ran"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -332,3 +453,113 @@ fn script_included_error_has_local_file_and_line() {
|
||||
assert!(error.starts_with("main.jsx: ") && error.contains("lib.jsxinc:3:5: Error: boom"), "{error}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Pumps the run in the app until it ends or waits at a dialog (`None`).
|
||||
fn pump(s: &mut Session) -> Option<Result<Value>> {
|
||||
for _ in 0..10_000 {
|
||||
if s.script_dialog().is_some() {
|
||||
return None;
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
return Some(r);
|
||||
}
|
||||
}
|
||||
panic!("the run neither ended nor waited");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_dialogs_in_included_and_evaluated_files() {
|
||||
let base = folder("dialogs");
|
||||
write(&base.join("main/ask.jsxinc"), "var a = confirm('inc');\n");
|
||||
write(&base.join("main/ev.jsx"), "alert('ev'); 7");
|
||||
let text = "#include \"ask.jsxinc\"\nvar m = '';\ntry { m = $.evalFile('ev.jsx'); } catch (e) { m = e.message; }\nvc.log([a, m]);";
|
||||
let main = base.join("main/main.jsx");
|
||||
write(&main, text);
|
||||
let path = main.to_string_lossy().to_string();
|
||||
// In the app, an included file's dialog waits as the script's own does; one in a file
|
||||
// $.evalFile runs cannot wait there and throws an error the script can catch.
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
assert_eq!(s.execute("script.run", &json!({"path": path})).unwrap()["running"], true);
|
||||
assert!(pump(&mut s).is_none());
|
||||
assert_eq!(s.script_dialog().unwrap().message, "inc");
|
||||
assert!(s.script_answer(crate::script::DialogAnswer::Confirm(true)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
let m = r["log"][0][1].as_str().unwrap_or_default();
|
||||
assert_eq!(r["log"][0][0], true, "{r}");
|
||||
assert!(m.contains("alert") && m.contains("$.evalFile"), "the error names the call and why: {r}");
|
||||
assert_eq!(r["dialogCount"], 1, "{r}");
|
||||
// A run with nobody to ask takes both answers in order.
|
||||
let mut s = Session::new();
|
||||
let answers = json!([{"kind": "confirm", "value": false}, {"kind": "alert", "value": "ok"}]);
|
||||
let r = s.execute("script.run", &json!({"path": path, "answers": answers})).unwrap();
|
||||
assert_eq!((r["log"].clone(), r["dialogCount"].clone()), (json!([[false, 7]]), json!(2)), "{r}");
|
||||
// An error in an included file after its dialog is at that file's line, and the report keeps
|
||||
// both the file and the dialog.
|
||||
write(&base.join("main/ask.jsxinc"), "var a = confirm('inc');\nif (a) throw new Error('after');\n");
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
s.execute("script.run", &json!({"path": path})).unwrap();
|
||||
assert!(pump(&mut s).is_none());
|
||||
assert!(s.script_answer(crate::script::DialogAnswer::Confirm(true)));
|
||||
assert!(pump(&mut s).unwrap().is_err());
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["line"], 2, "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("ask.jsxinc"), "{report}");
|
||||
assert_eq!(report["dialogs"][0]["answer"], true, "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The line, column and file name of a failed run's report, and its console error line (the only
|
||||
/// line of a run without output that starts with the script's name).
|
||||
fn place(report: &Value) -> (u64, u64, Option<&str>, &str) {
|
||||
let file = report.get("file").map(|f| f.as_str().unwrap().rsplit(['/', '\\']).next().unwrap());
|
||||
let lines = report["console"]["lines"].as_array().unwrap();
|
||||
let error = lines.iter().filter_map(Value::as_str).find(|l| l.starts_with("main.jsx")).unwrap();
|
||||
(report["line"].as_u64().unwrap(), report["column"].as_u64().unwrap(), file, error)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_eval_file_error_caught_and_thrown_again_is_at_the_new_throw() {
|
||||
let base = folder("rethrow");
|
||||
write(&base.join("main/sub/broken.jsx"), "var a = 1;\n\nvar = 2;");
|
||||
write(&base.join("main/sub/directive.jsx"), "\n#frobnicate 1");
|
||||
write(&base.join("main/sub/rethrow.jsx"), "var r = 1;\n throw saved;");
|
||||
write(&base.join("main/sub/outer.jsx"), "var q = 1;\n$.evalFile('broken.jsx');");
|
||||
write(&base.join("main/sub/outer2.jsx"), "try { $.evalFile('broken.jsx'); } catch (e) {\n\n throw e;\n}");
|
||||
let caught = "var saved;\ntry { $.evalFile('sub/broken.jsx'); } catch (e) { saved = e; }\n";
|
||||
let cases = [
|
||||
// Thrown again in the script, or in another file $.evalFile runs.
|
||||
(format!("{caught}var b = 2;\n throw saved;"), (4, 3, None)),
|
||||
(format!("{caught}$.evalFile('sub/rethrow.jsx');"), (2, 3, Some("rethrow.jsx"))),
|
||||
// A new error whose message holds the failure's text, or is the same text.
|
||||
(format!("{caught}throw new Error(saved.message);"), (3, 1, None)),
|
||||
(format!("{caught}throw new SyntaxError(saved.message);"), (3, 1, None)),
|
||||
// A second failure, caught, does not move the first one.
|
||||
(format!("{caught}try {{ $.evalFile('sub/directive.jsx'); }} catch (e) {{}}\n throw saved;"), (4, 2, None)),
|
||||
// A second failure, uncaught, is at its own file's place.
|
||||
(format!("{caught}$.evalFile('sub/directive.jsx');"), (2, 1, Some("directive.jsx"))),
|
||||
// An uncaught failure is at the file's place, through a finally block and from a nested file.
|
||||
("var a = 1;\ntry { $.evalFile('sub/broken.jsx'); } finally { a = 2; }".to_string(), (3, 5, Some("broken.jsx"))),
|
||||
("$.evalFile('sub/outer.jsx');".to_string(), (3, 5, Some("broken.jsx"))),
|
||||
// Caught in a nested file and thrown again there.
|
||||
("$.evalFile('sub/outer2.jsx');".to_string(), (3, 5, Some("outer2.jsx"))),
|
||||
// A failure caught in a run after one that failed with it, and a different error.
|
||||
("try { $.evalFile('sub/broken.jsx'); } catch (e) {}\nthrow new Error('other');".to_string(), (2, 1, None)),
|
||||
];
|
||||
let mut s = Session::new();
|
||||
let main = base.join("main/main.jsx");
|
||||
for (text, (line, column, file)) in cases {
|
||||
write(&main, &text);
|
||||
assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "{text}");
|
||||
let report = s.script_report().unwrap().clone();
|
||||
let (l, c, f, error) = place(&report);
|
||||
assert_eq!((report["kind"].as_str(), l, c, f), (Some("thrown"), line, column, file), "{text}\n{report}");
|
||||
let at = match file {
|
||||
Some(f) => format!("{f}:{line}:{column}: "),
|
||||
None => format!("main.jsx:{line}:{column}: "),
|
||||
};
|
||||
assert!(error.starts_with("main.jsx") && error.contains(&at), "{error}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
@@ -41,8 +41,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
|
||||
let mut s = session();
|
||||
let list = run(&mut s, "graphicStyle.libraries", json!({}));
|
||||
let libs = list["libraries"].as_array().unwrap();
|
||||
assert!(libs.len() >= 7 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}");
|
||||
assert!(libs.len() >= 8 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}");
|
||||
assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}");
|
||||
assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}");
|
||||
for l in libs {
|
||||
let id = l["id"].as_str().unwrap();
|
||||
let g = run(&mut s, "graphicStyle.library", json!({"library": id}));
|
||||
@@ -60,6 +61,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
|
||||
let game = run(&mut s, "graphicStyle.library", json!({"library": "game-hud"}));
|
||||
let game_names: Vec<&str> = game["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(game_names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]);
|
||||
let status = run(&mut s, "graphicStyle.library", json!({"library": "status-effects"}));
|
||||
let status_names: Vec<&str> = status["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]);
|
||||
let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0);
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]}));
|
||||
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow")));
|
||||
@@ -67,6 +71,12 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
|
||||
assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#3498db").unwrap()));
|
||||
assert_eq!(node.appearance.stroke_paint(), Paint::None);
|
||||
assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["stylize.outerGlow"]);
|
||||
let id2 = rect(&mut s, 60.0, 20.0, 40.0, 30.0);
|
||||
let r2 = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "status-effects", "name": "Poison Tint", "apply": true, "ids": [id2.0]}));
|
||||
assert_eq!((names(&r2["added"]), r2["applied"].as_str()), (vec!["Poison Tint"], Some("Poison Tint")));
|
||||
let node2 = doc(&s).node(id2).unwrap();
|
||||
assert_eq!(node2.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#2ecc71").unwrap()));
|
||||
assert_eq!(node2.appearance.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["stylize.outerGlow"]);
|
||||
// By name in any case.
|
||||
assert_eq!(run(&mut s, "graphicStyle.library", json!({"library": "shadows and glows"}))["id"], "shadows-glows");
|
||||
assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err());
|
||||
|
||||
@@ -207,6 +207,121 @@ fn deleting_a_filter_in_use_leaves_the_effect_drawing_nothing() {
|
||||
assert_eq!(drawn(&s, a), json!(SHIFT_MORE));
|
||||
}
|
||||
|
||||
/// The `(name, xml)` of every `svg.filter` effect on the document's objects.
|
||||
fn filter_effects(s: &Session) -> Vec<(String, String)> {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
for e in n.appearance.effects.iter().filter(|e| e.id == vectorcraft_render::effects::SVG_FILTER) {
|
||||
out.push((e.params["name"].as_str().unwrap().to_string(), e.params["xml"].as_str().unwrap().to_string()));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Pasted art whose filter has a name the document gives another filter keeps its own filter
|
||||
/// under a free name, so editing or deleting the document's filter leaves it alone. Pasted back
|
||||
/// into the document it came from, it takes the document's filter as it is now.
|
||||
#[test]
|
||||
fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() {
|
||||
let mut s = session();
|
||||
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{SHIFT_MORE}</defs><rect width="30" height="30" filter="url(#Shift)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let pasted = filter_effects(&s);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(pasted[0].0, "Shift 2", "renamed: {pasted:?}");
|
||||
assert!(pasted[0].1.contains("id=\"Shift 2\"") && pasted[0].1.contains("dx=\"9\""), "its own filter: {pasted:?}");
|
||||
assert_eq!(names(&mut s), ["Shift"]);
|
||||
run(&mut s, "svgFilter.delete", json!({"name": "Shift"}));
|
||||
assert_eq!(filter_effects(&s), pasted, "the document's filter leaves it alone");
|
||||
// The same filter as the document's keeps its name.
|
||||
let mut t = session();
|
||||
run(&mut t, "svgFilter.define", json!({"xml": SHIFT}));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{SHIFT}</defs><rect width="30" height="30" filter="url(#Shift)"/></svg>"#
|
||||
);
|
||||
run(&mut t, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut t, "edit.pasteInPlace", json!({}));
|
||||
assert_eq!(filter_effects(&t), [("Shift".to_string(), SHIFT.to_string())]);
|
||||
// Copied, then the filter edited: pasted back, the copy draws the edited filter.
|
||||
let mut u = session();
|
||||
let a = rect(&mut u, 10.0);
|
||||
run(&mut u, "svgFilter.define", json!({"xml": SHIFT}));
|
||||
run(&mut u, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]}));
|
||||
run(&mut u, "select.set", json!({"ids": [a.0]}));
|
||||
run(&mut u, "edit.copy", json!({}));
|
||||
run(&mut u, "svgFilter.define", json!({"xml": SHIFT_MORE, "replace": "Shift"}));
|
||||
run(&mut u, "edit.pasteInPlace", json!({}));
|
||||
let both = filter_effects(&u);
|
||||
assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]);
|
||||
}
|
||||
|
||||
/// A pasted filter at the size limit, which "Shift 2" would make too long to draw, keeps its own
|
||||
/// definition under a free name no longer than its own (a free letter for a one-letter name), and
|
||||
/// its id is that name.
|
||||
#[test]
|
||||
fn pasted_art_with_a_filter_at_the_size_limit_still_draws_when_renamed() {
|
||||
for (name, held, renamed) in [("Shift", SHIFT, "Shif"), ("S", r#"<filter id="S"><feOffset dx="3" dy="3"/></filter>"#, "a")] {
|
||||
let mut s = session();
|
||||
run(&mut s, "svgFilter.define", json!({"xml": held}));
|
||||
let (open, close) = (format!(r#"<filter id="{name}"><feOffset dx="9" dy="9" result=""#), r#""/></filter>"#);
|
||||
let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len()));
|
||||
assert!(vectorcraft_render::effects::svg_filter::check(&big).is_ok());
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{big}</defs><rect width="30" height="30" filter="url(#{name})"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let pasted = filter_effects(&s);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(pasted[0].0, renamed, "renamed: {}", pasted[0].0);
|
||||
assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok(renamed.to_string()), "the pasted filter draws under its name");
|
||||
assert!(pasted[0].1.contains("dx=\"9\""), "its own filter");
|
||||
assert_eq!(names(&mut s), [name]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A pasted filter is not renamed to a name an effect in the document already gives, even one whose
|
||||
/// filter was deleted, so defining a filter of that name later changes only that effect.
|
||||
#[test]
|
||||
fn pasted_art_takes_no_name_the_documents_effects_use() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.define", json!({"xml": r#"<filter id="Shift 2"><feOffset dx="1" dy="1"/></filter>"#}));
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Shift 2", "ids": [a.0]}));
|
||||
run(&mut s, "svgFilter.delete", json!({"name": "Shift 2"}));
|
||||
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{SHIFT_MORE}</defs><rect width="30" height="30" filter="url(#Shift)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let names: Vec<String> = filter_effects(&s).into_iter().map(|(n, _)| n).collect();
|
||||
assert_eq!(names, ["Shift 2", "Shift 3"]);
|
||||
}
|
||||
|
||||
/// A pasted filter whose name holds a tab, a line feed or a carriage return keeps those characters
|
||||
/// in its id under its new name.
|
||||
#[test]
|
||||
fn a_renamed_paste_keeps_whitespace_characters_in_its_id() {
|
||||
for c in ["	", " ", " "] {
|
||||
let mut s = session();
|
||||
run(&mut s, "svgFilter.define", json!({"xml": format!(r#"<filter id="S{c}t"><feOffset dx="3" dy="3"/></filter>"#)}));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs><filter id="S{c}t"><feOffset dx="9" dy="9"/></filter></defs><rect width="30" height="30" filter="url(#S{c}t)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let pasted = filter_effects(&s);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_ne!(pasted[0].0, names(&mut s)[0], "renamed");
|
||||
assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok(pasted[0].0.clone()), "{c}: its id is its name");
|
||||
}
|
||||
}
|
||||
|
||||
/// Art in a symbol's definition that uses a filter follows its edits too.
|
||||
#[test]
|
||||
fn a_symbols_art_follows_a_filter_edit() {
|
||||
|
||||
@@ -522,6 +522,7 @@ fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() {
|
||||
("text.setStyle", json!({"size": 30, "justify": {"value": "center"}}), string("justify")),
|
||||
("text.setStyle", json!({"features": ["dlig", 5]}), tags.clone()),
|
||||
("text.setStyle", json!({"leading": true}), "leading must be a number or \"auto\"".to_string()),
|
||||
("text.setStyle", json!({"leading": "12abc"}), "leading must be a number or \"auto\"".to_string()),
|
||||
("text.setRangeStyle", json!({"id": id.0, "font": 5}), string("font")),
|
||||
("text.setRangeStyle", json!({"id": id.0, "size": 30, "style": false}), string("style")),
|
||||
("text.setRangeStyle", json!({"id": id.0, "features": [null]}), tags),
|
||||
@@ -3467,6 +3468,75 @@ fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() {
|
||||
assert_eq!(query["chosen"], json!(glyph.gid), "an overflowing character reports the fallback glyph it is drawn with");
|
||||
}
|
||||
|
||||
/// `text.setGlyphAlternate` with `gid: null` reports the glyph the character is drawn with, as
|
||||
/// `text.glyphAlternates` does: the fallback face's glyph for a character the font lacks, laid out
|
||||
/// or overflowing, and the capital that All Caps draws for an a.
|
||||
#[test]
|
||||
fn a_glyph_choice_taken_away_reports_the_glyph_drawn() {
|
||||
use vectorcraft_text::test_fonts::{alternates_family, alternates_font};
|
||||
let _fonts = crate::adding_fonts();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
db.add_font(alternates_font(true).expect("the test font builds"));
|
||||
let face = db.face(alternates_family(true), "Regular").expect("the test face");
|
||||
let mut s = session();
|
||||
let reset = |s: &mut Session, id: NodeId, start: usize| {
|
||||
s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": start, "gid": null})).unwrap()["gid"].clone()
|
||||
};
|
||||
let chosen = |s: &mut Session, id: NodeId, start: usize| {
|
||||
s.execute("text.glyphAlternates", &json!({"id": id.0, "start": start})).unwrap()["chosen"].clone()
|
||||
};
|
||||
|
||||
let ch = 'Ƃ';
|
||||
assert_eq!(face.glyph_for(ch), 0);
|
||||
let point = json!({"x": 0, "y": 0, "text": ch.to_string(), "font": alternates_family(true)});
|
||||
let id = NodeId(s.execute("text.create", &point).unwrap()["id"].as_u64().unwrap());
|
||||
let drawn = vectorcraft_text::layout(db, &obj(&s, id)).glyphs[0].gid;
|
||||
assert_ne!(drawn, 0);
|
||||
assert_eq!(reset(&mut s, id, 0), json!(drawn), "the fallback glyph");
|
||||
assert_eq!(chosen(&mut s, id, 0), json!(drawn));
|
||||
|
||||
let area = json!({"x": 0, "y": 300, "text": ch.to_string(), "font": alternates_family(true), "area": {"width": 200, "height": 2}});
|
||||
let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap());
|
||||
assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows");
|
||||
assert_eq!(reset(&mut s, boxed, 0), json!(drawn), "the overflowing character's fallback glyph");
|
||||
|
||||
let caps = NodeId(
|
||||
s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("text.setRangeStyle", &json!({"id": caps.0, "start": 0, "end": 4, "allCaps": true})).unwrap();
|
||||
let drawn = vectorcraft_text::layout(db, &obj(&s, caps)).glyphs.iter().find(|g| g.byte == 1).expect("the a is laid out").gid;
|
||||
assert_ne!(drawn, face.glyph_for('a'), "All Caps draws the a as A");
|
||||
assert_eq!(reset(&mut s, caps, 1), json!(drawn), "the capital drawn");
|
||||
assert_eq!(chosen(&mut s, caps, 1), json!(drawn));
|
||||
}
|
||||
|
||||
/// A run that holds a choice for its first character and goes on past it, as a file may have,
|
||||
/// draws Source Serif 4's fi ligature for the f and the i after that character. `gid: null` for the
|
||||
/// i leaves the text as it is and reports the ligature, as `text.glyphAlternates` does.
|
||||
#[test]
|
||||
fn a_glyph_choice_taken_away_inside_a_ligature_reports_the_ligature() {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let face = db.face("Source Serif 4", "Regular").expect("the bundled face");
|
||||
let mut s = session();
|
||||
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xfin", "size": 40, "font": "Source Serif 4"})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let mut runs = obj(&s, id).runs;
|
||||
runs[0].style.glyph_alternate = Some(face.choice('x', face.glyph_for('x')));
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let Some(NodeKind::Text(text)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("text") };
|
||||
text.runs = runs.clone();
|
||||
let ligature = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.iter().find(|g| g.byte == 1 && g.len == 2).expect("f + i is one glyph").gid;
|
||||
let chosen = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap()["chosen"].clone();
|
||||
assert_eq!(chosen, json!(ligature));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": null})).unwrap();
|
||||
assert_eq!(r["gid"], chosen, "the ligature drawn for the i");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no edit");
|
||||
assert_eq!(obj(&s, id).runs, runs, "the runs are kept");
|
||||
}
|
||||
|
||||
/// A fallback face draws Ka with the vowel sign I in one cluster, the vowel sign first. The glyph
|
||||
/// reported for Ka is the fallback face's glyph for Ka, laid out or overflowing, not the vowel
|
||||
/// sign's.
|
||||
|
||||
@@ -708,6 +708,14 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The artboard a guide made from a ruler belongs to: with the Artboard tool, its active
|
||||
/// artboard (an artboard guide); with any other tool, none (a canvas guide).
|
||||
pub fn ruler_guide_artboard(&self) -> Option<usize> {
|
||||
let boards = self.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let active = (self.tool.id() == "artboard").then(|| self.tool.options()["active"].as_u64()).flatten();
|
||||
active.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < boards)
|
||||
}
|
||||
|
||||
/// A guide dragged out of a ruler, whatever the tool: a vertical one out of the left ruler, a
|
||||
/// horizontal one out of the top ruler. `ev` is the pointer in document space (a drag, then the
|
||||
/// release), over the canvas or not (`on_canvas`). The guide shows where the pointer is over
|
||||
@@ -722,11 +730,9 @@ impl Session {
|
||||
let g = match self.ruler_guide.take() {
|
||||
Some(g) => Some(g),
|
||||
None => {
|
||||
let boards = self.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let artboard_tool = self.tool.id() == "artboard";
|
||||
let swap = self.prefs.cmd_ruler_drag_artboard_guides && ev.mods.cmd;
|
||||
let active = artboard_tool.then(|| self.tool.options()["active"].as_u64()).flatten();
|
||||
let artboard = active.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < boards);
|
||||
let artboard = self.ruler_guide_artboard();
|
||||
let view_board = view.artboard;
|
||||
self.with_tool_cx(view, |_, cx| {
|
||||
Some(match (swap, artboard_tool) {
|
||||
|
||||
Reference in New Issue
Block a user