mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 08:52:45 +01:00
Merge main into feat/palette-home-callout
This commit is contained in:
commit
bb2fa4629e
116 files changed
+4321
-289
No files matched your search
@@ -96,7 +96,24 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
Some(folder) => d.folder(folder),
|
||||
None => d,
|
||||
};
|
||||
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
|
||||
if pick.name.is_empty() {
|
||||
return d;
|
||||
}
|
||||
// Windows' save dialog changes the extension when a different file type is chosen only when
|
||||
// the suggested name has no explicit extension. rfd supplies the first filter's extension to
|
||||
// that dialog, so leave the suffix to Windows for saves that offer several formats (#5451).
|
||||
// A remaining dot in the stem would look like another explicit extension to Windows.
|
||||
#[cfg(windows)]
|
||||
if matches!(request, PickRequest::Save(_))
|
||||
&& pick.filters.len() > 1
|
||||
&& let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str())
|
||||
&& pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext)))
|
||||
&& let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str())
|
||||
&& !stem.contains('.')
|
||||
{
|
||||
return d.file_name(stem);
|
||||
}
|
||||
d.file_name(&pick.name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -796,7 +813,7 @@ mod dialog_tests {
|
||||
|
||||
/// The file types a dialog was given, by label.
|
||||
#[derive(Default)]
|
||||
struct Filters(Vec<(String, Vec<String>)>);
|
||||
struct Filters(Vec<(String, Vec<String>)>, Option<String>);
|
||||
|
||||
impl DialogSettings for Filters {
|
||||
fn parent(self, _window: &winit::window::Window) -> Self {
|
||||
@@ -812,7 +829,8 @@ mod dialog_tests {
|
||||
fn folder(self, _folder: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn file_name(self, _name: &str) -> Self {
|
||||
fn file_name(mut self, name: &str) -> Self {
|
||||
self.1 = Some(name.to_string());
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -869,4 +887,24 @@ mod dialog_tests {
|
||||
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
|
||||
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
|
||||
}
|
||||
|
||||
/// A format selected after the Windows Save As dialog opens can replace the suffix of the
|
||||
/// suggested name. Single-format saves and open dialogs keep the supplied name verbatim.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn save_dialog_with_several_formats_leaves_the_extension_to_windows() {
|
||||
let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])];
|
||||
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster"));
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft"));
|
||||
|
||||
let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster"));
|
||||
let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design"));
|
||||
let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft"));
|
||||
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft"));
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,18 @@ pub enum ArrowStyle {
|
||||
None,
|
||||
}
|
||||
|
||||
impl ArrowStyle {
|
||||
/// The stroke arrowhead drawn at each end of the dimension line, or None for no head.
|
||||
pub fn arrowhead(self) -> Option<crate::Arrowhead> {
|
||||
match self {
|
||||
Self::Filled => Some(crate::Arrowhead::Triangle),
|
||||
Self::Open => Some(crate::Arrowhead::TriangleOpen),
|
||||
Self::Tick => Some(crate::Arrowhead::Slash),
|
||||
Self::None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the label sits across the dimension line.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
|
||||
@@ -424,6 +424,44 @@ impl Document {
|
||||
out
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike
|
||||
/// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every
|
||||
/// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still
|
||||
/// checks out, the nodes are found along those paths; otherwise one walk of the tree finds
|
||||
/// them. As for every cached lookup, a second node given an existing id after the cache was
|
||||
/// built is not found while the first one's cached path checks out (see [`id_index`]).
|
||||
pub fn nodes_in_order(&self, ids: impl IntoIterator<Item = NodeId>) -> Vec<&Node> {
|
||||
let want: std::collections::HashSet<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = ids.into_iter().collect();
|
||||
// As in `index_paths`, one walk is quicker than checking the cached paths of a good share
|
||||
// of the document.
|
||||
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
|
||||
let mut paths = Vec::with_capacity(want.len());
|
||||
let cached = want.iter().all(|id| match cache.get(id) {
|
||||
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
|
||||
paths.push(p);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
if cached {
|
||||
// A node's path sorts after the paths of the nodes before it in tree order, its
|
||||
// ancestors included.
|
||||
paths.sort_unstable();
|
||||
return paths.iter().filter_map(|p| self.node_at(p)).collect();
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if !want.is_empty() {
|
||||
crate::id_index::note_tree_walk();
|
||||
self.walk(|n| {
|
||||
if want.contains(&n.id) {
|
||||
out.push(n);
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node at index path `path` (as [`Document::index_path`] gives it).
|
||||
pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
|
||||
+25
-6
@@ -2096,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving
|
||||
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
|
||||
/// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are
|
||||
/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a
|
||||
/// touched where the live geometry effects of a clipping path in their art show it, or where the
|
||||
/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except
|
||||
/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a
|
||||
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
|
||||
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
@@ -2265,8 +2267,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
|
||||
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
|
||||
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
|
||||
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
|
||||
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
|
||||
/// compound paths, layers and groups are touched by their box, and an image or a symbol
|
||||
/// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping
|
||||
/// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region
|
||||
/// ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
// A path or compound path whose geometry effects reshape it, or a group or layer whose own
|
||||
// geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]).
|
||||
@@ -2296,12 +2300,27 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
// A symbol instance is touched by its box, and outside it where the live geometry
|
||||
// effects of a clipping path in its art show the art. In the art of another instance
|
||||
// walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]).
|
||||
NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
|
||||
// effects of a clipping path in its art show the art, or where the geometry effects of
|
||||
// its active fill or stroke reshape the art ([`painted_touches`]). In the art of another
|
||||
// instance walked outside that instance's box, it is touched only by its own art
|
||||
// ([`ArtOnly`]) and those shapes.
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
!ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, whole_compounds) || painted_touches(n, s, r))
|
||||
}
|
||||
// An image is touched by its box, and outside it where its own fills and strokes paint.
|
||||
NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r),
|
||||
_ => box_touches(n, s, r),
|
||||
}
|
||||
}
|
||||
/// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol
|
||||
/// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is
|
||||
/// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when
|
||||
/// `r` meets the reach of `n` ([`Node::reach_bounds_with`]).
|
||||
fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
n.reach_bounds_with(s).is_some_and(meets)
|
||||
&& image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r))
|
||||
}
|
||||
/// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of
|
||||
/// a symbol that draws a straight line) is touched where the marquee crosses it.
|
||||
fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
|
||||
|
||||
@@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option<Quotes> {
|
||||
LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q)
|
||||
}
|
||||
|
||||
/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the
|
||||
/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written
|
||||
/// as in an exported file. `None` for a language not in the list.
|
||||
pub fn language_tag(language: &str) -> Option<&'static str> {
|
||||
LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t)
|
||||
}
|
||||
|
||||
/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's
|
||||
/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the
|
||||
/// first entry); `Err` for a language not in the list.
|
||||
@@ -404,6 +411,16 @@ impl DocSetup {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A document's language is written by its tag, the default's included (#3644).
|
||||
#[test]
|
||||
fn document_languages_have_their_tags() {
|
||||
assert_eq!(language_tag(&DocSetup::default().language), Some("en-US"));
|
||||
assert_eq!(language_tag("French"), Some("fr"));
|
||||
assert_eq!(language_tag("german: swiss"), Some("de-CH"));
|
||||
assert_eq!(language_tag("sr-latn"), Some("sr-Latn"));
|
||||
assert_eq!((language_tag("Klingon"), language_tag("")), (None, None));
|
||||
}
|
||||
|
||||
/// Characters store a language of the list by its tag, the default as none.
|
||||
#[test]
|
||||
fn char_languages_are_stored_by_tag() {
|
||||
|
||||
@@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, by walking the tree.
|
||||
fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> {
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
out.push(n as *const Node);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids
|
||||
/// included, with the cache built and without it, for a few ids (cached paths) and for many (a
|
||||
/// walk).
|
||||
#[test]
|
||||
fn nodes_in_order_match_a_walk() {
|
||||
for seed in 1..40 {
|
||||
let (d, ids) = tree(seed);
|
||||
let few: Vec<NodeId> = ids.iter().copied().step_by(17).collect();
|
||||
for cold in [true, false] {
|
||||
if cold {
|
||||
d.drop_lookup_cache();
|
||||
} else {
|
||||
d.node(ids[0]);
|
||||
}
|
||||
for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] {
|
||||
let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect();
|
||||
assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}");
|
||||
}
|
||||
}
|
||||
// An id that the tree repeats: every node with it.
|
||||
let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue };
|
||||
assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once");
|
||||
// A second node given an id once held once, after the cache was built: the lookup finds the
|
||||
// cached node, which has that id; with the cache built afresh, both.
|
||||
let mut d = d;
|
||||
let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer()));
|
||||
let Some(once) = once else { continue };
|
||||
d.node(once);
|
||||
let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art()));
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
ch.insert(0, copy);
|
||||
}
|
||||
let found = d.nodes_in_order([once]);
|
||||
assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}");
|
||||
d.drop_lookup_cache();
|
||||
d.node(once);
|
||||
let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect();
|
||||
assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh");
|
||||
}
|
||||
}
|
||||
|
||||
/// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each
|
||||
/// node it is in, appears in the tree once.
|
||||
fn picks(d: &Document, seed: u64) -> Vec<NodeId> {
|
||||
|
||||
@@ -840,6 +840,8 @@ pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
pub use object::{reflect_axis, scale_factors, shear_tangent};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
@@ -211,7 +211,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Symbol…",
|
||||
[],
|
||||
None,
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_selection,
|
||||
symbol_new
|
||||
),
|
||||
|
||||
@@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let nine = nine_slice_param(p, C, None)?.flatten();
|
||||
let dynamic = type_param(p, C)?.unwrap_or(false);
|
||||
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
|
||||
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
|
||||
let keep_art = switch_or(p, "keepArt", false, C)?;
|
||||
let iso = s.doc()?.isolation;
|
||||
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
|
||||
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
|
||||
let id = s.edit("New Symbol", |d, sel| {
|
||||
@@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_export_type(&name, export);
|
||||
d.set_symbol_nine_slice(&name, nine);
|
||||
d.set_symbol_pixel_aligned(&name, pixel);
|
||||
if keep_art {
|
||||
// The art stays where it is and stays selected, apart from art that is hidden or
|
||||
// locked, in a hidden or locked group or layer, or on a locked artboard.
|
||||
let locks = d.locked_artboards();
|
||||
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
|
||||
return Ok(None);
|
||||
}
|
||||
let id = instance_in_place(d, &ids, &name, place)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
Ok(Some(id))
|
||||
})?;
|
||||
Ok(json!({
|
||||
"name": name,
|
||||
"id": id.0,
|
||||
"id": id.map(|i| i.0),
|
||||
"registration": reg.0,
|
||||
"exportType": export.id(),
|
||||
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
|
||||
|
||||
@@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::dimension::{
|
||||
ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition,
|
||||
};
|
||||
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
|
||||
LineType::Solid => None,
|
||||
};
|
||||
if arrows {
|
||||
let head = match o.arrow_style {
|
||||
ArrowStyle::Filled => Some(Arrowhead::Triangle),
|
||||
ArrowStyle::Open => Some(Arrowhead::TriangleOpen),
|
||||
ArrowStyle::Tick => Some(Arrowhead::Slash),
|
||||
ArrowStyle::None => None,
|
||||
};
|
||||
let head = o.arrow_style.arrowhead();
|
||||
st.start_arrow = head.clone();
|
||||
st.end_arrow = head;
|
||||
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
|
||||
|
||||
@@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p
|
||||
}
|
||||
|
||||
/// Does a file of a document with `artboards` artboards, written in format `format` with options
|
||||
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
|
||||
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
|
||||
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates,
|
||||
/// EPS files and the files of an exporter plug-in's format (`plugin.<id>`, whose plug-in is given
|
||||
/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
|
||||
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
|
||||
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
|
||||
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
|
||||
@@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
|
||||
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
|
||||
match format {
|
||||
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
|
||||
_ if vectorcraft_plugins::export::plugin_id(format).is_some() => true,
|
||||
"ai" | "ait" => {
|
||||
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
|
||||
!legacy && !(format == "ai" && art_page()) && every_artboard()
|
||||
@@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
|
||||
|
||||
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
|
||||
/// always, unless read roots are in force, the file carries the native document (a native file or
|
||||
/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as
|
||||
/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter
|
||||
/// plug-in's file, as
|
||||
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
|
||||
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
|
||||
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
|
||||
|
||||
@@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
|
||||
/// The file exporter plug-in `plugin` writes of `doc` in its format `f`
|
||||
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
|
||||
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
|
||||
/// one named after the document) with that path's extension when the plug-in lists it, else its
|
||||
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
|
||||
/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots
|
||||
/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path`
|
||||
/// names (else one named after the document) with that path's extension when the plug-in lists it,
|
||||
/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
|
||||
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
use vectorcraft_plugins::{Error, export};
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let doc = doc.without_edit_modes();
|
||||
let doc = &*super::access::with_readable_settings_folder(&doc);
|
||||
let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let path = p.get("path").and_then(Value::as_str);
|
||||
let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e));
|
||||
|
||||
@@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{
|
||||
};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
pub use transform::{reflect_axis, scale_factors, shear_tangent};
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shear…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
shear
|
||||
),
|
||||
|
||||
@@ -369,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let sx = f64_req(p, "sx", "object.scale")? / 100.0;
|
||||
let sy = f64_or(p, "sy", sx * 100.0) / 100.0;
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err(bad("object.scale", "scale must be non-zero"));
|
||||
}
|
||||
let sx = f64_req(p, "sx", "object.scale")?;
|
||||
let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?;
|
||||
let frame = basis_frame(s, p, "object.scale", &ids)?;
|
||||
apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true)
|
||||
}
|
||||
|
||||
/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when
|
||||
/// either factor is 0.
|
||||
pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> {
|
||||
let (sx, sy) = (sx / 100.0, sy / 100.0);
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err("scale must be non-zero".into());
|
||||
}
|
||||
Ok((sx, sy))
|
||||
}
|
||||
|
||||
/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param:
|
||||
/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset
|
||||
/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with
|
||||
@@ -402,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
// A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page.
|
||||
let named = match p.get("axis") {
|
||||
Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)),
|
||||
Some(Value::Number(_)) => None,
|
||||
None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")));
|
||||
}
|
||||
};
|
||||
let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?;
|
||||
let m = match named {
|
||||
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
|
||||
None => {
|
||||
@@ -423,12 +421,47 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
apply_transform(s, "Reflect", ids, about(o, m), p, true)
|
||||
}
|
||||
|
||||
/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis
|
||||
/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle,
|
||||
/// which is a line on the page; or the error for any other value.
|
||||
pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result<Option<Affine>, String> {
|
||||
match axis {
|
||||
Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))),
|
||||
Some(Value::Number(_)) => Ok(None),
|
||||
None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
|
||||
Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It
|
||||
/// is far above the rounding error of an angle up to 359° and below any angle a field shows.
|
||||
const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An
|
||||
/// angle outside -359 to 359, or ±90 or ±270, is an error.
|
||||
pub fn shear_tangent(angle: f64) -> std::result::Result<f64, String> {
|
||||
if !(-359.0..=359.0).contains(&angle) {
|
||||
return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}"));
|
||||
}
|
||||
// ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded.
|
||||
let flat = angle.rem_euclid(180.0);
|
||||
if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE {
|
||||
return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"));
|
||||
}
|
||||
// 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0.
|
||||
Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() })
|
||||
}
|
||||
|
||||
pub(super) fn shear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["angle"], "object.shear")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?;
|
||||
let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan();
|
||||
let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]);
|
||||
// A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal.
|
||||
let m = match p.get("axis") {
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Package",
|
||||
[],
|
||||
None,
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied",
|
||||
has_doc,
|
||||
package
|
||||
)]
|
||||
@@ -113,27 +113,65 @@ thread_local! {
|
||||
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
|
||||
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
|
||||
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
if super::place::document::is_native(name, bytes) {
|
||||
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
|
||||
}
|
||||
let data =
|
||||
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
|
||||
vectorcraft_format::load(&data?).ok()
|
||||
/// The native document a linked file is or carries ([`carried_document`]).
|
||||
enum Carried {
|
||||
/// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file
|
||||
/// without editing data.
|
||||
Absent,
|
||||
/// The native document, read.
|
||||
Readable(Box<Document>),
|
||||
/// The file is a native document, or carries one, that can't be read: a damaged native file,
|
||||
/// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF
|
||||
/// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file
|
||||
/// whose attachments are too many to search to their end, or editing data that doesn't read as
|
||||
/// a native document.
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
|
||||
/// a PDF, `.ai` or EPS file.
|
||||
fn carried_document(name: &str, bytes: &[u8]) -> Carried {
|
||||
let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d)));
|
||||
if super::place::document::is_native(name, bytes) {
|
||||
return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc)));
|
||||
}
|
||||
if super::place::document::is_pdf(name, bytes) {
|
||||
// A PDF that can't be opened may carry editing data all the same.
|
||||
return match vectorcraft_pdf::open_pdf(bytes, None) {
|
||||
// Attachments left unsearched may list another editing file, which can't be checked.
|
||||
Ok(opened) if opened.editing_search_cut() => Carried::Unreadable,
|
||||
// An editing file listed whose data can't be resolved can't be checked either.
|
||||
Ok(opened) => match opened.editing() {
|
||||
Some(e) => read(&e.data),
|
||||
None if opened.has_editing_file() => Carried::Unreadable,
|
||||
None => Carried::Absent,
|
||||
},
|
||||
Err(_) => Carried::Unreadable,
|
||||
};
|
||||
}
|
||||
if !vectorcraft_eps::has_native(bytes) {
|
||||
return Carried::Absent;
|
||||
}
|
||||
vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data))
|
||||
}
|
||||
|
||||
/// The error for a linked file the package would copy whose native document can't be read to
|
||||
/// check the files and folders it names against the read roots.
|
||||
const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots";
|
||||
|
||||
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
|
||||
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
|
||||
/// relative path taken from the file's folder): the copy would name it.
|
||||
/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file
|
||||
/// outside them (a relative path taken from the file's folder): the copy would name it. A file
|
||||
/// whose native document can't be read is refused, as its links can't be checked. The error names
|
||||
/// no file or folder.
|
||||
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
|
||||
None => Ok(()),
|
||||
Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
|
||||
Carried::Unreadable => Err(bad(C, UNREADABLE)),
|
||||
Carried::Absent => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +188,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)),
|
||||
Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => {
|
||||
Err(bad(C, FOLDER_OUTSIDE))
|
||||
}
|
||||
Carried::Unreadable => Err(bad(C, UNREADABLE)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -498,6 +539,9 @@ pub struct Package {
|
||||
root: Option<PathBuf>,
|
||||
info: Option<String>,
|
||||
doc: std::sync::Arc<Document>,
|
||||
/// The read roots in force where the package was prepared: [`Package::write`] collects under
|
||||
/// them.
|
||||
scope: crate::file_access::ScopeHandle,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -544,21 +588,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
let doc = s.doc()?.doc.clone();
|
||||
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
|
||||
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
|
||||
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope })
|
||||
}
|
||||
|
||||
impl Package {
|
||||
/// Collect the linked files and fonts and write the package's files with `write` into
|
||||
/// `folder/name`, making its folders first, or into the zip without a folder → the reply of
|
||||
/// `file.package`.
|
||||
/// `file.package`, with the read roots in force where it was prepared, on any thread.
|
||||
pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
collect_and_write(self, write)
|
||||
self.scope.clone().run(|| collect_and_write(self, write))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Package::write`].
|
||||
fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package;
|
||||
let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package;
|
||||
let mut doc = (*original).clone();
|
||||
let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION);
|
||||
let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) };
|
||||
|
||||
@@ -274,8 +274,9 @@ impl DocState {
|
||||
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
|
||||
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
|
||||
/// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of
|
||||
/// each selected object's own stack is compared. One walk of the document, so callers that ask
|
||||
/// every frame cache it by revision.
|
||||
/// each selected object's own stack is compared. The selected objects are found through the id
|
||||
/// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk
|
||||
/// of the document, so callers that ask every frame cache it by revision.
|
||||
pub fn proxy_mixed(&self, item: Option<usize>) -> (bool, bool) {
|
||||
self.proxy_mixed_with(item, &[])
|
||||
}
|
||||
@@ -290,15 +291,17 @@ impl DocState {
|
||||
if self.selection.symbol_part.is_some() {
|
||||
return (false, false);
|
||||
}
|
||||
let ids: std::collections::HashSet<NodeId> = self.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
self.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
});
|
||||
// Looking the first object up builds the id cache when there is none.
|
||||
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
|
||||
// place it appears.
|
||||
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
|
||||
#[cfg(test)]
|
||||
tests::note_gathered();
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
@@ -1323,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.execute("object.setProps", &Value::Object(q))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,335 @@
|
||||
//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the
|
||||
//! id cache: it answers as a walk of the whole document does, and with a few objects selected it
|
||||
//! reads only those.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use crate::{DocState, Session};
|
||||
|
||||
thread_local! {
|
||||
/// [`gathered`] of this thread.
|
||||
static GATHERED: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones.
|
||||
pub(super) fn note_gathered() {
|
||||
GATHERED.set(GATHERED.get() + 1);
|
||||
}
|
||||
|
||||
/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones.
|
||||
fn gathered() -> u64 {
|
||||
GATHERED.get()
|
||||
}
|
||||
|
||||
/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document.
|
||||
fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -> (bool, bool) {
|
||||
if st.selection.is_empty() {
|
||||
return (false, false);
|
||||
}
|
||||
if st.selection.symbol_part.is_some() {
|
||||
return (false, false);
|
||||
}
|
||||
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
st.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
});
|
||||
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
|
||||
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
|
||||
c => c.into_iter().map(Paint::solid).collect(),
|
||||
});
|
||||
let Some(p0) = paints.next() else { return false };
|
||||
paints.any(|p| !same_in_proxy(&p0, &p))
|
||||
};
|
||||
(differ(false), differ(true))
|
||||
}
|
||||
|
||||
/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item
|
||||
/// and with and without `points`, with the id cache built and without it.
|
||||
fn agree(st: &DocState, points: &[(NodeId, Vec<usize>)], what: &str) {
|
||||
for cold in [true, false] {
|
||||
if cold {
|
||||
st.doc.drop_lookup_cache();
|
||||
}
|
||||
for item in [None, Some(0), Some(1), Some(2), Some(3)] {
|
||||
for points in [points, &[]] {
|
||||
assert_eq!(
|
||||
st.proxy_mixed_with(item, points),
|
||||
walked(st, item, points),
|
||||
"{what}: item {item:?}, {} picked points, cold cache {cold}",
|
||||
points.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn id_of(v: &serde_json::Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId {
|
||||
let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object,
|
||||
/// different fills or strokes, a group with different contents, a group with one of its objects,
|
||||
/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a
|
||||
/// gradient mesh with points picked beside another object, ids not in the document and an id that
|
||||
/// appears twice (a damaged file) with different paints.
|
||||
#[test]
|
||||
fn the_question_marks_match_a_walk_of_the_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let a = rect(&mut s, 10.0, "#ff0000", "#000000");
|
||||
let b = rect(&mut s, 40.0, "#0000ff", "#000000");
|
||||
let c = rect(&mut s, 70.0, "#ff0000", "#00ff00");
|
||||
// Two fills: [Fill, Stroke, Fill].
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap();
|
||||
let e = rect(&mut s, 100.0, "#ff0000", "#000000");
|
||||
let f = rect(&mut s, 130.0, "#00ff00", "#000000");
|
||||
let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap());
|
||||
let mesh = rect(&mut s, 160.0, "#ff0000", "#000000");
|
||||
s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap();
|
||||
let hidden = rect(&mut s, 190.0, "#0000ff", "#000000");
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let h = rect(&mut s, 220.0, "#ff0000", "#000000");
|
||||
let missing = NodeId(999_999);
|
||||
let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") };
|
||||
let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1));
|
||||
s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap();
|
||||
let points = vec![(mesh, vec![p00, p01])];
|
||||
let points_alike = vec![(mesh, vec![p01, p11])];
|
||||
|
||||
let selections = [
|
||||
vec![a],
|
||||
vec![a, b],
|
||||
vec![b, a],
|
||||
vec![a, h],
|
||||
vec![g],
|
||||
vec![g, e],
|
||||
vec![e, g],
|
||||
vec![f, e],
|
||||
vec![c],
|
||||
vec![c, a],
|
||||
vec![a, c],
|
||||
vec![mesh],
|
||||
vec![mesh, a],
|
||||
vec![a, mesh, h],
|
||||
vec![hidden],
|
||||
vec![hidden, b],
|
||||
vec![missing],
|
||||
vec![missing, a],
|
||||
vec![a, missing, b],
|
||||
vec![a, a],
|
||||
];
|
||||
let check = |s: &mut Session, what: &str| {
|
||||
for sel in &selections {
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
let st = s.active().unwrap();
|
||||
agree(st, &points, &format!("{what}: {sel:?}"));
|
||||
agree(st, &points_alike, &format!("{what}: {sel:?}, alike points"));
|
||||
}
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
agree(s.active().unwrap(), &points, &format!("{what}: Select All"));
|
||||
};
|
||||
check(&mut s, "unique ids");
|
||||
|
||||
// A second node with a's id and another fill, at the end of the tree.
|
||||
let st = s.active_mut().unwrap();
|
||||
let mut copy = st.doc.node(a).unwrap().clone();
|
||||
copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
let doc = Arc::make_mut(&mut st.doc);
|
||||
let last = doc.layers.len() - 1;
|
||||
Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy));
|
||||
doc.drop_lookup_cache();
|
||||
check(&mut s, "a repeated id");
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = vec![a];
|
||||
assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill");
|
||||
}
|
||||
|
||||
/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other
|
||||
/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order.
|
||||
fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec<NodeId>) {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
d.layers.clear();
|
||||
let mut rects = vec![];
|
||||
for l in 0..layers {
|
||||
let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0));
|
||||
for _ in 0..groups {
|
||||
let children = (0..per_group)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
let mut ap = Appearance::default_art();
|
||||
let red = rects.len() % 2 == 0;
|
||||
ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) }));
|
||||
rects.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap))
|
||||
})
|
||||
.collect();
|
||||
let group = Node::group(d.alloc_id(), children);
|
||||
layer.children_mut().unwrap().push(Arc::new(group));
|
||||
}
|
||||
d.layers.push(Arc::new(layer));
|
||||
}
|
||||
(d, rects)
|
||||
}
|
||||
|
||||
fn state(doc: Document) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap();
|
||||
s.active_mut().unwrap().doc = Arc::new(doc);
|
||||
s
|
||||
}
|
||||
|
||||
/// With one object selected, the "?" reads only that object, not every node of the document, and
|
||||
/// does not walk the tree once the id cache is built; with every object selected it walks the tree
|
||||
/// once.
|
||||
#[test]
|
||||
fn the_question_marks_read_only_the_selected_objects() {
|
||||
let (doc, rects) = big(2, 40, 25);
|
||||
let mut s = state(doc);
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = vec![rects[777]];
|
||||
assert_eq!(st.proxy_mixed(None), (false, false));
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (false, false));
|
||||
assert_eq!(gathered() - read, 1, "only the selected object is read");
|
||||
assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers");
|
||||
|
||||
st.selection.objects = vec![rects[3], rects[1500]];
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (true, false));
|
||||
assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0));
|
||||
|
||||
st.selection.objects = rects.clone();
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (true, false));
|
||||
assert_eq!(gathered() - read, rects.len() as u64);
|
||||
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
|
||||
}
|
||||
|
||||
/// Random selections of a document with nested groups answer as a walk does.
|
||||
#[test]
|
||||
fn random_selections_match_a_walk_of_the_document() {
|
||||
let (doc, rects) = big(3, 12, 6);
|
||||
let mut s = state(doc);
|
||||
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
|
||||
let layers: Vec<NodeId> = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect();
|
||||
let all: Vec<NodeId> = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect();
|
||||
let mut r = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let mut next = |n: usize| {
|
||||
r ^= r << 13;
|
||||
r ^= r >> 7;
|
||||
r ^= r << 17;
|
||||
(r % n as u64) as usize
|
||||
};
|
||||
for round in 0..200 {
|
||||
let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 });
|
||||
let sel: Vec<NodeId> = (0..count).map(|_| all[next(all.len())]).collect();
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<std::time::Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn time(f: impl FnOnce()) -> std::time::Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = std::time::Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on
|
||||
/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "timing; run by hand"]
|
||||
fn proxy_mixed_timing() {
|
||||
let (doc, rects) = big(5, 100, 100);
|
||||
let mut s = state(doc);
|
||||
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
|
||||
let cases: [(&str, Vec<NodeId>); 5] = [
|
||||
("1 object", vec![rects[25_000]]),
|
||||
("2 objects, different fills", vec![rects[10], rects[40_001]]),
|
||||
("a group of 100", vec![groups[250]]),
|
||||
("all 500 groups", groups.clone()),
|
||||
("all 50,000 objects", rects.clone()),
|
||||
];
|
||||
const CALLS: usize = 200;
|
||||
let median = |mut v: Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |");
|
||||
println!("|---|---|---|---|---|");
|
||||
for (name, sel) in &cases {
|
||||
for cold in [false, true] {
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}");
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
let calls = if cold { CALLS / 10 } else { CALLS };
|
||||
for _ in 0..7 {
|
||||
for (times, use_walk) in [(&mut old, true), (&mut new, false)] {
|
||||
let d = time(|| {
|
||||
for _ in 0..calls {
|
||||
if cold {
|
||||
st.doc.drop_lookup_cache();
|
||||
}
|
||||
std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) });
|
||||
}
|
||||
});
|
||||
times.push(d.as_secs_f64() * 1e6 / calls as f64);
|
||||
}
|
||||
}
|
||||
let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::<Vec<_>>().join(" ");
|
||||
println!(
|
||||
"| {name} | {} | {:.1} | {:.1} | {} / {} |",
|
||||
if cold { "dropped before each call" } else { "built" },
|
||||
median(old.clone()),
|
||||
median(new.clone()),
|
||||
runs(&old),
|
||||
runs(&new)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -161,6 +161,8 @@ pub struct FilterRun {
|
||||
parent: Option<NodeId>,
|
||||
/// The document it was made from, and that document's revision then.
|
||||
document: (u64, u64),
|
||||
/// The plug-in's limits with the Plug-in Instruction Budget in force when it was made.
|
||||
limits: vectorcraft_plugins::Limits,
|
||||
}
|
||||
|
||||
/// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run
|
||||
@@ -245,7 +247,11 @@ impl FilterRun {
|
||||
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
|
||||
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
|
||||
let document = (st.uid, st.revision);
|
||||
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document })
|
||||
let limits = match s.prefs.plugin_instruction_budget {
|
||||
crate::PluginBudget::Normal => plugin.limits().clone(),
|
||||
crate::PluginBudget::Large => plugin.large_limits(),
|
||||
};
|
||||
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
|
||||
}
|
||||
|
||||
/// The plug-in, for its name and budget.
|
||||
@@ -274,7 +280,13 @@ impl FilterRun {
|
||||
/// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between
|
||||
/// two slices of its budget.
|
||||
pub fn run(&self) -> Result<Vec<u8>> {
|
||||
self.plugin.run(&self.input, &self.params).map_err(err)
|
||||
self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err)
|
||||
}
|
||||
|
||||
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
|
||||
/// it was made.
|
||||
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
|
||||
&self.limits
|
||||
}
|
||||
|
||||
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
|
||||
@@ -289,7 +301,7 @@ impl FilterRun {
|
||||
let may = self.plugin.manifest().permissions();
|
||||
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
|
||||
let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args);
|
||||
self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err)
|
||||
self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err)
|
||||
}
|
||||
|
||||
/// Runs a plug-in that calls commands and applies its output: the calls and the output are one
|
||||
|
||||
@@ -324,6 +324,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text),
|
||||
// Plug-ins & Scratch Disks
|
||||
p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text),
|
||||
// The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input.
|
||||
p!(
|
||||
"pluginInstructionBudget",
|
||||
"Plug-ins & Scratch Disks",
|
||||
"Plug-ins",
|
||||
"Plug-in Instruction Budget",
|
||||
choice(&[("normal", "Normal"), ("large", "Large")])
|
||||
),
|
||||
p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text),
|
||||
p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text),
|
||||
// User Interface
|
||||
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -489,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value {
|
||||
|
||||
fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "graphicStyle.redefine";
|
||||
let (src, n) = source(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = if n.id == src { src } else { n.id };
|
||||
let i = match str_param(p, "name") {
|
||||
Some(name) => style_index(d, name)?,
|
||||
None => n
|
||||
.extras()
|
||||
.graphic_style
|
||||
.and_then(|id| d.graphic_style_by_id(id))
|
||||
.and_then(|g| d.graphic_style_index(&g.name))
|
||||
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
|
||||
// The style to replace, its new look, and the object that look comes from (none for another style's look).
|
||||
let (i, look, src) = match p.get("from") {
|
||||
Some(from) => {
|
||||
let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?;
|
||||
if p.get("id").is_some() {
|
||||
return Err(bad(cmd, "pass `id` or `from`, not both"));
|
||||
}
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (i, j) = (style_index(d, name)?, style_index(d, from)?);
|
||||
// A style dropped on itself, or on a style with the same look, stays as it is.
|
||||
let target = &d.graphic_styles[i];
|
||||
let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() };
|
||||
if i == j || look == *target {
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
(i, look, None)
|
||||
}
|
||||
None => {
|
||||
let (src, n) = source(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = if n.id == src { src } else { n.id };
|
||||
let i = match str_param(p, "name") {
|
||||
Some(name) => style_index(d, name)?,
|
||||
None => n
|
||||
.extras()
|
||||
.graphic_style
|
||||
.and_then(|id| d.graphic_style_by_id(id))
|
||||
.and_then(|g| d.graphic_style_index(&g.name))
|
||||
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
|
||||
};
|
||||
(i, GraphicStyle::of(String::new(), captured(n), n), Some(src))
|
||||
}
|
||||
};
|
||||
let look = GraphicStyle::of(String::new(), captured(n), n);
|
||||
let name = d.graphic_styles[i].name.clone();
|
||||
let name = s.doc()?.doc.graphic_styles[i].name.clone();
|
||||
let chars = s.prefs.override_char_color;
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
|
||||
@@ -513,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
|
||||
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
|
||||
// source or as a linked object: the graph draws it again from the design.
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
|
||||
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
@@ -521,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
follow_marks.retain(|nid| *nid != src && !edited.contains(nid));
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
@@ -530,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
|
||||
super::graph::capture_label_rows(d, &follow_marks);
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
if let Some(src) = src {
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
|
||||
@@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the
|
||||
/// thread as it was: every frame stays a frame of the thread with the text it holds, and the
|
||||
/// symbol's art holds a copy of the text the frame shows.
|
||||
#[test]
|
||||
fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() {
|
||||
for command in ["symbol.new", "symbol.update"] {
|
||||
let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0);
|
||||
let shown = frames.map(|id| text(&s, id));
|
||||
let name = if command == "symbol.update" {
|
||||
let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
|
||||
"Mark"
|
||||
} else {
|
||||
"Story"
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap();
|
||||
let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap();
|
||||
assert!(r["id"].is_null(), "{command}: {r}");
|
||||
assert_eq!(threads(&s), [frames], "{command}: the thread is as it was");
|
||||
assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text");
|
||||
assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows");
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the
|
||||
/// mask art too.
|
||||
#[test]
|
||||
|
||||
@@ -415,7 +415,7 @@ use history::history_budget_for;
|
||||
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
|
||||
pub(crate) use interaction::PreviewCopies;
|
||||
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
|
||||
pub use prefs::{DrawMode, Prefs};
|
||||
pub use prefs::{DrawMode, PluginBudget, Prefs};
|
||||
pub use sanity::TOO_DEEP;
|
||||
pub(crate) use sanity::{deselect_hidden, is_guide_path};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -10,6 +10,26 @@ pub enum DrawMode {
|
||||
Inside,
|
||||
}
|
||||
|
||||
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run
|
||||
/// may use ([`vectorcraft_plugins::Plugin::large_limits`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PluginBudget {
|
||||
/// The plug-in's own limits.
|
||||
#[default]
|
||||
Normal,
|
||||
/// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of
|
||||
/// input; the time budget is unchanged.
|
||||
Large,
|
||||
}
|
||||
|
||||
/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the
|
||||
/// other preferences are read as they are.
|
||||
fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<PluginBudget, D::Error> {
|
||||
let saved = <Value as serde::Deserialize>::deserialize(d)?;
|
||||
Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal })
|
||||
}
|
||||
|
||||
/// A saved Default Language as its tag: older preferences hold the language's name, and one the list
|
||||
/// no longer has reads as the default.
|
||||
fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<String, D::Error> {
|
||||
@@ -179,6 +199,11 @@ pub struct Prefs {
|
||||
pub fonts_folder: String,
|
||||
// Plug-ins & Scratch Disks
|
||||
pub plugins_folder: String,
|
||||
/// Plug-in Instruction Budget: the instructions each object filter run gets, from
|
||||
/// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers
|
||||
/// keep their own budgets.
|
||||
#[serde(deserialize_with = "plugin_budget")]
|
||||
pub plugin_instruction_budget: PluginBudget,
|
||||
pub scratch_primary: String,
|
||||
pub scratch_secondary: String,
|
||||
// User Interface
|
||||
@@ -496,6 +521,7 @@ impl Default for Prefs {
|
||||
hyphenation_exceptions: String::new(),
|
||||
fonts_folder: String::new(),
|
||||
plugins_folder: String::new(),
|
||||
plugin_instruction_budget: PluginBudget::Normal,
|
||||
scratch_primary: s("Startup"),
|
||||
scratch_secondary: s("None"),
|
||||
ui_brightness: s("mediumDark"),
|
||||
|
||||
@@ -2274,6 +2274,93 @@ fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch()
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of symbol instances in the document.
|
||||
fn instance_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. })));
|
||||
n
|
||||
}
|
||||
|
||||
/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current
|
||||
/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the
|
||||
/// result has no instance id and nothing places the symbol. One undo step takes the symbol away
|
||||
/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance.
|
||||
#[test]
|
||||
fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
|
||||
let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
|
||||
let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i));
|
||||
let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b));
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
select(&mut s, &[a, b]);
|
||||
let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap();
|
||||
assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}");
|
||||
assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected");
|
||||
assert_eq!(instance_count(&s), 0, "no instance");
|
||||
let list = s.execute("symbol.list", &json!({})).unwrap();
|
||||
assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0)));
|
||||
// The symbol's art is the pair: an instance placed from it is 120 × 50.
|
||||
let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap());
|
||||
let w = bounds(&s, placed);
|
||||
assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away");
|
||||
assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo");
|
||||
assert_eq!(instance_count(&s), 0, "redo places no instance");
|
||||
// false, like no keepArt, makes the art an instance.
|
||||
for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] {
|
||||
let r = s.execute("symbol.new", &p).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().expect("an instance id"));
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
|
||||
}
|
||||
|
||||
/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it
|
||||
/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the
|
||||
/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and
|
||||
/// no undo step.
|
||||
#[test]
|
||||
fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() {
|
||||
let mut s = session();
|
||||
let (inst, _, _) = make_symbol(&mut s);
|
||||
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
|
||||
let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
|
||||
let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0);
|
||||
{
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.node_mut(locked).unwrap().locked = true;
|
||||
doc.node_mut(hidden).unwrap().visible = false;
|
||||
}
|
||||
for bad in [json!("true"), json!(1), json!([true])] {
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err();
|
||||
assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step");
|
||||
}
|
||||
select(&mut s, &[]);
|
||||
let symbols = s.doc().unwrap().doc.symbols.len();
|
||||
let ids = [a.0, locked.0, hidden.0, inst.0];
|
||||
s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1);
|
||||
let selected = &s.doc().unwrap().selection.objects;
|
||||
assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}");
|
||||
for id in [a, locked, hidden] {
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art");
|
||||
}
|
||||
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance");
|
||||
assert_eq!(instance_count(&s), 1, "no new instance");
|
||||
}
|
||||
|
||||
/// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a
|
||||
/// group, in an opacity mask, or through the art of another symbol it holds an instance of, and
|
||||
/// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines
|
||||
|
||||
@@ -387,22 +387,79 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
|
||||
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
|
||||
}
|
||||
|
||||
/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115;
|
||||
/// the fill's shape is 9 pt larger on each side.
|
||||
fn image_with_shaped_fill(s: &mut Session) -> NodeId {
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let im = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
run(s, "select.set", json!({"ids": [im.0]}));
|
||||
run(s, "appearance.addFill", json!({}));
|
||||
run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
|
||||
run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
|
||||
im
|
||||
}
|
||||
|
||||
/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in
|
||||
/// outline with `outline`.
|
||||
fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec<NodeId> {
|
||||
let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0);
|
||||
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline)
|
||||
}
|
||||
|
||||
/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its
|
||||
/// art outside its box, as a click there selects it, except in outline.
|
||||
#[test]
|
||||
fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
|
||||
let mut s = session();
|
||||
let (id, row) = instance_with_row(&mut s, "Square", true);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), []);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill");
|
||||
assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill");
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is");
|
||||
|
||||
let mut s = session();
|
||||
let (id, row) = instance_with_row(&mut s, "Square", false);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke");
|
||||
assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill");
|
||||
|
||||
let mut s = session();
|
||||
let (id, row) = nested_instance_with_row(&mut s);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art");
|
||||
}
|
||||
|
||||
/// A marquee touches an image where the shape of its own fill lies outside its frame, and an
|
||||
/// instance of a symbol made of that image where the instance's fill effect grows that shape, as
|
||||
/// clicks there select them, except in outline.
|
||||
#[test]
|
||||
fn a_marquee_on_the_shape_of_an_image_fill_selects_it() {
|
||||
let mut s = session();
|
||||
let im = image_with_shaped_fill(&mut s);
|
||||
assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame");
|
||||
assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape");
|
||||
assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame");
|
||||
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(&s, id).appearance.items.len() - 1;
|
||||
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill");
|
||||
assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill");
|
||||
}
|
||||
|
||||
/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill
|
||||
/// effect grows what that fill paints, and a click there selects the instance.
|
||||
#[test]
|
||||
fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() {
|
||||
let mut s = session();
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
// The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side.
|
||||
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let im = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
run(&mut s, "select.set", json!({"ids": [im.0]}));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
|
||||
image_with_shaped_fill(&mut s);
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(&s, id).appearance.items.len() - 1;
|
||||
|
||||
@@ -465,6 +465,117 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_
|
||||
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
|
||||
}
|
||||
|
||||
/// A confined request packages no linked file whose native document it can't read to check against
|
||||
/// its read roots: a PDF that needs a password to open, and a native document that doesn't load,
|
||||
/// even inside the roots. The package is refused before anything is written, with an error that
|
||||
/// names no file or folder. A PDF without editing data is copied, and the person's package copies
|
||||
/// every file.
|
||||
#[test]
|
||||
fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() {
|
||||
let home = Folder::new("package-unreadable-home");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let out = home.file("out");
|
||||
let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p));
|
||||
let refused = |s: &mut Session, p: Value| {
|
||||
let e = package(s, p.clone()).expect_err("refused");
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}");
|
||||
assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}");
|
||||
assert!(!std::path::Path::new(&out).exists(), "{p}");
|
||||
};
|
||||
let mut part = session();
|
||||
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
|
||||
std::fs::create_dir_all(home.0.join("art")).unwrap();
|
||||
let native = home.file("art/part.vectorcraft");
|
||||
let pdf = home.file("art/part.pdf");
|
||||
save(&mut part, &native);
|
||||
let pdf_of =
|
||||
|part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let editable = pdf_of(&mut part, json!({"format": "pdf"}));
|
||||
let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}}));
|
||||
assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data");
|
||||
let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false}));
|
||||
let poster = |placed: &str| {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
|
||||
assert_eq!(r["linked"], true, "{r}");
|
||||
save(&mut s, &home.file("poster.vectorcraft"));
|
||||
s
|
||||
};
|
||||
write(&pdf, &editable);
|
||||
let mut s = poster(&pdf);
|
||||
write(&pdf, &locked);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
// A package prepared in the confined request and written on another thread.
|
||||
let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap();
|
||||
let e =
|
||||
std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused");
|
||||
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}");
|
||||
assert!(!std::path::Path::new(&out).exists());
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A PDF listing the editing file without its data (`EF` renamed, the same length).
|
||||
let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF");
|
||||
let mut detached = editable.clone();
|
||||
detached[at..at + 3].copy_from_slice(b"/XF");
|
||||
assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved");
|
||||
write(&pdf, &detached);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A PDF without editing data.
|
||||
write(&pdf, &plain);
|
||||
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
|
||||
std::fs::remove_dir_all(&out).unwrap();
|
||||
// A PDF whose attachments are too many to search to their end, with a readable editing file
|
||||
// listed before the ones left unsearched.
|
||||
let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data);
|
||||
assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read");
|
||||
write(&pdf, &cut);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A native document that doesn't load, rewritten or copied as it is.
|
||||
let mut s = poster(&native);
|
||||
write(&native, b"not a document");
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"folder": out, "relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
}
|
||||
|
||||
/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree
|
||||
/// whose second subtree has 70,000 nodes, more than are searched.
|
||||
fn attachments_cut_short(native: &[u8]) -> Vec<u8> {
|
||||
let name = vectorcraft_pdf::EDITING_FILE;
|
||||
let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes();
|
||||
stream.extend_from_slice(native);
|
||||
stream.extend_from_slice(b"\nendstream");
|
||||
let objects = [
|
||||
b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(),
|
||||
format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(),
|
||||
format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(),
|
||||
stream,
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, body) in objects.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
out.extend_from_slice(body);
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
|
||||
for at in &offsets {
|
||||
out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A missing link stored as a path relative to the document names a file inside a confined
|
||||
/// request's read root: the package report and Document Info give its stored path.
|
||||
#[test]
|
||||
|
||||
@@ -4446,6 +4446,59 @@ fn a_cancelled_filter_run_changes_nothing() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter
|
||||
/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as
|
||||
/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's
|
||||
/// larger budget stay as they are, and setting Normal again applies to the next run.
|
||||
#[test]
|
||||
fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let mut s = session();
|
||||
let id = "test.engine.largebudget";
|
||||
let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string();
|
||||
// More steps than a light budget pays for, fewer than 5 times it.
|
||||
install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output));
|
||||
let p = json!({"id": id, "ids": []});
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
|
||||
|
||||
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"}));
|
||||
let light = vectorcraft_plugins::Limits::default();
|
||||
let large = FilterRun::prepare(&s, &p).unwrap().limits().clone();
|
||||
assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() });
|
||||
assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms));
|
||||
// Cancel still stops it, and it changes nothing.
|
||||
let token = vectorcraft_doc::cancel::CancelToken::new();
|
||||
token.cancel();
|
||||
let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p));
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
|
||||
let made = run(&mut s, "plugin.run", p.clone())["ids"].clone();
|
||||
assert_eq!(made.as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
|
||||
// A heavy filter keeps its larger budget with either choice.
|
||||
let heavy_id = "test.engine.largebudget.heavy";
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true}));
|
||||
let hp = json!({"id": heavy_id, "ids": []});
|
||||
for budget in ["large", "normal"] {
|
||||
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget}));
|
||||
let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone();
|
||||
let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS);
|
||||
assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}");
|
||||
}
|
||||
|
||||
// Normal again: the next run runs out of instructions.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
run(&mut s, "plugin.remove", json!({"id": heavy_id}));
|
||||
}
|
||||
|
||||
/// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list).
|
||||
fn with_commands(id: &str, kind: &str, commands: &str) -> String {
|
||||
format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#)
|
||||
|
||||
@@ -464,6 +464,38 @@ fn gpu_preference_defaults_to_automatic_and_validates() {
|
||||
assert_eq!(s.prefs.gpu_preference, "automatic");
|
||||
}
|
||||
|
||||
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or
|
||||
/// label, kept through a save and load, and reset with its category. Setting another value is an
|
||||
/// error that changes nothing; a saved value that is missing, unknown or of another type reads as
|
||||
/// Normal and leaves the other saved preferences as they are.
|
||||
#[test]
|
||||
fn plugin_instruction_budget_defaults_to_normal_and_validates() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal"));
|
||||
set_pref(&mut s, "pluginInstructionBudget", json!("Large"));
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large"));
|
||||
for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] {
|
||||
assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}");
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}");
|
||||
}
|
||||
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
|
||||
assert_eq!(back.plugin_instruction_budget, PluginBudget::Large);
|
||||
let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")];
|
||||
let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v}));
|
||||
for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) {
|
||||
let read: Prefs = serde_json::from_value(saved.clone()).unwrap();
|
||||
assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}");
|
||||
}
|
||||
let l = s.execute("prefs.list", &json!({})).unwrap();
|
||||
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone();
|
||||
assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins")));
|
||||
assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large")));
|
||||
s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap();
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
|
||||
}
|
||||
|
||||
/// Performance › Low-Latency Drawing (#6013): off by default and for preference files written
|
||||
/// before it, a boolean only, kept through a save/load round trip, listed under Performance and
|
||||
/// reset with it.
|
||||
|
||||
@@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() {
|
||||
assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance));
|
||||
}
|
||||
|
||||
/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id,
|
||||
/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as
|
||||
/// they are, in one undo step. A style replaced by itself or by a style with the same look records
|
||||
/// nothing, and bad parameters are errors that change nothing.
|
||||
#[test]
|
||||
fn redefine_from_a_style_gives_the_style_that_look() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = linked_three(&mut s);
|
||||
let d = rect(&mut s, 300.0);
|
||||
set_fill(&mut s, d, "#0000ff");
|
||||
run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"}));
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Blue"}));
|
||||
set_fill(&mut s, c, "#00ff00");
|
||||
let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::<Vec<_>>();
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s));
|
||||
assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S");
|
||||
assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() });
|
||||
assert_eq!(names(&s), order);
|
||||
let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap());
|
||||
for id in [a, b] {
|
||||
let n = node(&s, id);
|
||||
assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply));
|
||||
}
|
||||
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
|
||||
// The edited object keeps its look and is unlinked; Blue and its object are as they were.
|
||||
assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap()));
|
||||
assert_eq!(node(&s, c).extras().graphic_style, None);
|
||||
assert_eq!(style(&s, "Blue"), blue);
|
||||
assert_eq!(linked(&mut s, "Blue"), vec![d.0]);
|
||||
let step = s.doc().unwrap().history.undo.last().unwrap().clone();
|
||||
assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(style(&s, "S"), old);
|
||||
assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE)));
|
||||
assert_eq!(node(&s, c).extras().graphic_style, Some(old.id));
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(style(&s, "S").appearance, blue.appearance);
|
||||
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
|
||||
// A style replaced by itself, or by a copy with the same look, records nothing.
|
||||
run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"}));
|
||||
let before = steps(&s);
|
||||
run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"}));
|
||||
run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"}));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert_eq!(style(&s, "S"), old);
|
||||
|
||||
// A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors.
|
||||
for p in [
|
||||
json!({"name": "S", "from": "nope"}),
|
||||
json!({"name": "nope", "from": "Blue"}),
|
||||
json!({"name": "S", "from": 3}),
|
||||
json!({"name": "S", "from": "Blue", "id": a.0}),
|
||||
json!({"from": "Blue"}),
|
||||
] {
|
||||
assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!((steps(&s), style(&s, "S")), (before, old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_style_unlinks_and_renaming_keeps_links() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -515,6 +515,69 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
|
||||
assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}");
|
||||
}
|
||||
|
||||
/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant
|
||||
/// opposite ways, and 120 and 300 slant as -60 does.
|
||||
#[test]
|
||||
fn shear_angles_slant_by_their_tangent() {
|
||||
let run = 100.0 * 60f64.to_radians().tan();
|
||||
for (angle, want) in [
|
||||
(60.0, Rect::new(-run, 0.0, 100.0, 100.0)),
|
||||
(-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)),
|
||||
] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap();
|
||||
assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a));
|
||||
}
|
||||
}
|
||||
|
||||
/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no
|
||||
/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded.
|
||||
#[test]
|
||||
fn shear_rejects_angles_with_no_shear_or_out_of_range() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
|
||||
let n = undo_len(&s);
|
||||
let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear");
|
||||
let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}");
|
||||
for (angle, msg) in [
|
||||
(90.0, none(90.0)),
|
||||
(-90.0, none(-90.0)),
|
||||
(270.0, none(270.0)),
|
||||
(-270.0, none(-270.0)),
|
||||
(90.0 + 1e-12, none(90.0 + 1e-12)),
|
||||
(360.0, range(360.0)),
|
||||
(-359.5, range(-359.5)),
|
||||
(1e300, range(1e300)),
|
||||
] {
|
||||
let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string());
|
||||
assert_eq!(e.to_string(), msg);
|
||||
}
|
||||
assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle");
|
||||
assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a));
|
||||
assert_eq!(undo_len(&s), n, "no undo step");
|
||||
}
|
||||
|
||||
/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact
|
||||
/// coordinates and no undo step is recorded.
|
||||
#[test]
|
||||
fn shear_by_0_and_180_changes_nothing() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
|
||||
let before = bounds(&s, a);
|
||||
let n = undo_len(&s);
|
||||
for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] {
|
||||
for axis in ["horizontal", "vertical"] {
|
||||
s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap();
|
||||
assert_eq!(bounds(&s, a), before, "{angle} {axis}");
|
||||
assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shear along an axis at an angle, counter-clockwise from horizontal on the page: each point
|
||||
/// slides along the axis by the tangent of the shear angle times its distance across the axis
|
||||
/// from the origin. -359° and 359° are taken, the shear is one undo step and Transform Again
|
||||
|
||||
@@ -95,6 +95,29 @@ fn apply_to_all_restyles_every_dimension_in_one_undo_step() {
|
||||
assert!(s.execute("dimension.applyToAll", &json!({"id":line})).is_err(), "not a dimension");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() {
|
||||
use vectorcraft_doc::Arrowhead;
|
||||
let mut s = session();
|
||||
for (style, head) in
|
||||
[("filled", Some(Arrowhead::Triangle)), ("open", Some(Arrowhead::TriangleOpen)), ("tick", Some(Arrowhead::Slash)), ("none", None)]
|
||||
{
|
||||
let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":style}}))["id"].as_u64().unwrap();
|
||||
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap();
|
||||
let heads: Vec<_> = n
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone())))
|
||||
.filter(|(a, b)| a.is_some() || b.is_some())
|
||||
.collect();
|
||||
match head {
|
||||
Some(head) => assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style}: {heads:?}"),
|
||||
None => assert!(heads.is_empty(), "{style}: {heads:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimension_angles_circles_arcs_and_curves() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -287,3 +287,107 @@ fn a_cancelled_export_stops_the_exporter() {
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}");
|
||||
}
|
||||
|
||||
/// Every string in `v`, at any depth.
|
||||
fn strings_in(v: &Value, out: &mut Vec<String>) {
|
||||
match v {
|
||||
Value::String(s) => out.push(s.clone()),
|
||||
Value::Array(items) => items.iter().for_each(|v| strings_in(v, out)),
|
||||
Value::Object(map) => map.values().for_each(|v| strings_in(v, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller: an exporter, given the native document's JSON, is not run for a document
|
||||
/// that links a JavaScript file, a data set's image or a placed file outside the read roots. Every
|
||||
/// command that writes its format refuses, before any file or folder is written, with an error
|
||||
/// that names no file or folder, and the document keeps its links. A data set's image inside the
|
||||
/// roots is given to it, the JSON it is given leaves out an Export for Screens folder outside them,
|
||||
/// and the person's export gives it every path as stored.
|
||||
#[test]
|
||||
fn a_confined_exporter_is_refused_stored_paths_outside_the_read_roots() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = tmp_dir("confined-away");
|
||||
let home = tmp_dir("confined-home");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("assets.add", &json!({"ids": [r["id"]]})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.confined", r#"["tsc"]"#, "{}"), Echo::Input));
|
||||
let format = "plugin.test.confined";
|
||||
let roots = AutomationRoots::new(&[home.as_path()], &[home.as_path()]).unwrap();
|
||||
let out = path_of(&home.join("out"));
|
||||
let outputs = [
|
||||
("document.serialize", json!({"format": format})),
|
||||
("document.export", json!({"format": format})),
|
||||
("document.export", json!({"format": format, "path": path_of(&home.join("export.tsc"))})),
|
||||
("document.exportSelection", json!({"format": format})),
|
||||
("document.exportForScreens", json!({"folder": out, "formats": [{"format": format}]})),
|
||||
("assets.export", json!({"folder": out, "formats": [{"format": format}]})),
|
||||
];
|
||||
let hidden = [path_of(&away), path_of(&home)];
|
||||
// `assets`: an asset's file is checked too (its document holds the asset's art and the
|
||||
// document's data sets, not other art).
|
||||
let refused = |s: &mut Session, why: &str, assets: bool| {
|
||||
for (cmd, p) in outputs.iter().filter(|(cmd, _)| assets || *cmd != "assets.export") {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, p)).expect_err(&format!("{cmd} {p}: {why}"));
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains(why), "{cmd} {p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
|
||||
}
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&home).unwrap().count(), 0, "nothing is written");
|
||||
};
|
||||
// The strings of the JSON the exporter is given.
|
||||
let given = |s: &mut Session, confined: bool| {
|
||||
let p = json!({"format": format});
|
||||
let r = if confined { confine(roots.as_ref(), || s.execute("document.export", &p)) } else { s.execute("document.export", &p) };
|
||||
let mut found = vec![];
|
||||
strings_in(&serde_json::from_slice(&exported(&r.unwrap())).unwrap(), &mut found);
|
||||
found
|
||||
};
|
||||
|
||||
let script = path_of(&away.join("menu.js"));
|
||||
s.execute("svgInteractivity.addFile", &json!({"file": script})).unwrap();
|
||||
refused(&mut s, "a linked JavaScript file is outside the read roots", true);
|
||||
assert!(given(&mut s, false).contains(&script), "the person's export");
|
||||
s.execute("svgInteractivity.removeFile", &json!({"file": script})).unwrap();
|
||||
|
||||
let set_image = |s: &mut Session, path: &str| {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect();
|
||||
doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }];
|
||||
};
|
||||
let photo = path_of(&away.join("photo.png"));
|
||||
set_image(&mut s, &photo);
|
||||
refused(&mut s, "a linked image file is outside the read roots", true);
|
||||
assert!(given(&mut s, false).contains(&photo), "the person's export");
|
||||
let inside = path_of(&home.join("photo.png"));
|
||||
set_image(&mut s, &inside);
|
||||
assert!(given(&mut s, true).contains(&inside), "an image inside the read roots");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.clear();
|
||||
|
||||
let folder = path_of(&away.join("screens"));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap();
|
||||
assert!(!given(&mut s, true).contains(&folder), "the export folder is left out");
|
||||
assert!(given(&mut s, false).contains(&folder), "the person's export");
|
||||
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder"), Some(&json!(folder)), "the document keeps it");
|
||||
|
||||
let mut part = Session::new();
|
||||
part.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let placed = path_of(&away.join("part.vectorcraft"));
|
||||
part.execute("file.saveAs", &json!({"path": placed})).unwrap();
|
||||
s.execute("file.place", &json!({"path": placed, "link": true})).unwrap();
|
||||
refused(&mut s, "a linked image file is outside the read roots", false);
|
||||
// The asset's file holds the rectangle alone, without the placed file.
|
||||
let r = confine(roots.as_ref(), || s.execute("assets.export", &outputs[5].1)).unwrap();
|
||||
let mut found = vec![];
|
||||
strings_in(&serde_json::from_slice(&std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap(), &mut found);
|
||||
assert!(!found.contains(&placed), "{found:?}");
|
||||
let _ = std::fs::remove_dir_all(&away);
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
@@ -3431,6 +3431,133 @@ fn many_gradient_definitions_take_distinct_names_in_order() {
|
||||
assert_eq!(text, program(&doc));
|
||||
}
|
||||
|
||||
/// The program written from `doc`, with the gradient and pattern definitions found by comparing
|
||||
/// each in turn (`scanned`) or through their indexes.
|
||||
fn program_scanned(doc: &Document, scanned: bool) -> Vec<u8> {
|
||||
writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned));
|
||||
let out = export_ai_editing(doc, &opts());
|
||||
writer::SCANNED_DEFINITIONS.with(|s| s.set(false));
|
||||
out.unwrap().program
|
||||
}
|
||||
|
||||
/// [`gradients_and_patterns`] with more rectangles, each filled with a gradient: `distinct` with
|
||||
/// gradients of their own; `reused` with one of `ramps` gradients in turn; one for each of
|
||||
/// `swatches` new gradient swatches, linked to it, with the swatch's gradient for every other one
|
||||
/// and another gradient for the rest; one with the gradient of an object whose style isn't written
|
||||
/// (an even-odd fill with a drop shadow), after that object; and two whose gradients
|
||||
/// differ only in the sign of a zero offset.
|
||||
fn many_gradients(distinct: u16, reused: u16, ramps: u16, swatches: u16) -> Document {
|
||||
let mut doc = gradients_and_patterns();
|
||||
let two = |a: Color, b: Color| ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]);
|
||||
let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1));
|
||||
let swatch_gradient = |i: u16| two(Color::gray(shade(i, swatches)), Color::rgb(1.0, 0.0, 0.0));
|
||||
let more = (0..swatches)
|
||||
.map(|i| Swatch { name: format!("Ramp {i}"), paint: gradient_paint(swatch_gradient(i), None, None), global: false, spot: false })
|
||||
.collect();
|
||||
swatches_plus(&mut doc, more);
|
||||
let mut paints = vec![];
|
||||
for i in 0..distinct {
|
||||
paints.push(gradient_paint(two(Color::rgb(shade(i, distinct), 0.5, 0.0), Color::rgb(0.0, 0.0, 1.0)), None, None));
|
||||
}
|
||||
for i in 0..reused {
|
||||
paints.push(gradient_paint(two(Color::rgb(0.0, shade(i % ramps.max(1), ramps), 0.5), Color::WHITE), None, None));
|
||||
}
|
||||
for i in 0..swatches {
|
||||
let g = if i % 2 == 0 { swatch_gradient(i) } else { two(Color::gray(shade(i, swatches)), Color::rgb(0.0, 1.0, 0.0)) };
|
||||
paints.push(gradient_paint(g, None, Some(&format!("Ramp {i}"))));
|
||||
}
|
||||
// The reader wouldn't read an even-odd fill with the style, so the style isn't written.
|
||||
let unstyled = two(Color::WHITE, Color::BLACK);
|
||||
let ap = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(unstyled.clone(), None, None)))],
|
||||
effects: vec![fx("stylize.dropShadow", serde_json::json!({}))],
|
||||
contents_index: None,
|
||||
};
|
||||
let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap);
|
||||
if let NodeKind::Path { rule, .. } = &mut n.kind {
|
||||
*rule = FillRule::EvenOdd;
|
||||
}
|
||||
put(&mut doc, n);
|
||||
paints.push(gradient_paint(unstyled, None, None));
|
||||
let zero = |o: f32| ramp(GradientKind::Linear, &[(o, Color::rgb(0.2, 0.3, 0.4), 1.0, 0.5), (1.0, Color::BLACK, 1.0, 0.5)]);
|
||||
paints.extend([gradient_paint(zero(0.0), None, None), gradient_paint(zero(-0.0), None, None)]);
|
||||
for (i, p) in (0u16..).zip(paints) {
|
||||
let (x, y) = (f64::from(i % 60) * 5.0, f64::from(i / 60 % 40) * 5.0);
|
||||
let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), vec![AppearanceItem::Fill(FillLayer::new(p))]);
|
||||
put(&mut doc, n);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
/// Gradient and pattern definitions found through their indexes are those found by comparing each
|
||||
/// in turn: the program is the same, byte for byte. A swatch's definition serves a paint linked to
|
||||
/// it only with the swatch's gradient; a gradient defined for a style that isn't written leaves its
|
||||
/// name free; gradients that differ only in the sign of a zero share a definition.
|
||||
#[test]
|
||||
fn indexed_definitions_write_the_same_program() {
|
||||
let doc = many_gradients(300, 300, 7, 6);
|
||||
let (indexed, scanned) = (program_scanned(&doc, false), program_scanned(&doc, true));
|
||||
let differ = indexed.iter().zip(&scanned).position(|(a, b)| a != b);
|
||||
assert!(indexed == scanned, "the programs differ from byte {differ:?} ({} and {} bytes)", indexed.len(), scanned.len());
|
||||
let text = String::from_utf8(indexed).unwrap();
|
||||
let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect();
|
||||
// `gradients_and_patterns`'s 5, then 300 + 7 + 6 swatches' + 3 others linked to swatches + 1
|
||||
// after the style + 1 for both signs of zero.
|
||||
assert_eq!(names.len(), 5 + 300 + 7 + 6 + 3 + 1 + 1, "{names:?}");
|
||||
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len(), "{names:?}");
|
||||
assert_eq!(text.matches("%AI3_BeginPattern: (Dots)").count(), 1);
|
||||
}
|
||||
|
||||
/// A gradient paint is matched with the definitions of the same gradient, not with each
|
||||
/// definition: 1,000 gradients of their own and 1,000 paints of 10 others take a few comparisons
|
||||
/// each, where comparing each definition in turn takes hundreds of thousands.
|
||||
#[test]
|
||||
fn gradient_definitions_are_found_without_comparing_each() {
|
||||
let doc = many_gradients(1000, 1000, 10, 0);
|
||||
let comparisons = |scanned: bool| {
|
||||
writer::GRADIENT_COMPARISONS.with(|c| c.set(0));
|
||||
program_scanned(&doc, scanned);
|
||||
writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get)
|
||||
};
|
||||
let (indexed, scanned) = (comparisons(false), comparisons(true));
|
||||
assert!(indexed <= 2 * 2010, "{indexed} comparisons through the index");
|
||||
assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index");
|
||||
}
|
||||
|
||||
/// The time to write 5,000 rectangles with gradients of their own, 5,000 with 50 others and 20
|
||||
/// gradient swatches, with the definitions found by comparing each in turn and through their
|
||||
/// indexes: the median of 7 runs of each, alternating, with the programs compared. Run with
|
||||
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture gradient_definitions_timing`.
|
||||
#[test]
|
||||
#[ignore = "timing"]
|
||||
fn gradient_definitions_timing() {
|
||||
let doc = many_gradients(5000, 5000, 50, 20);
|
||||
let mut times = [vec![], vec![]];
|
||||
let mut programs: [Option<Vec<u8>>; 2] = [None, None];
|
||||
let mut how = "";
|
||||
for _ in 0..7 {
|
||||
for (k, scanned) in [true, false].into_iter().enumerate() {
|
||||
let (start, h) = thread_time();
|
||||
let program = program_scanned(&doc, scanned);
|
||||
times[k].push(thread_time().0.saturating_sub(start));
|
||||
how = h;
|
||||
programs[k].get_or_insert(program);
|
||||
}
|
||||
}
|
||||
assert_eq!(programs[0], programs[1]);
|
||||
for t in &mut times {
|
||||
t.sort();
|
||||
}
|
||||
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
|
||||
println!("median of 7 runs ({how}):");
|
||||
println!("| definitions found | median (ms) | runs (ms) |");
|
||||
println!("|---|---:|---|");
|
||||
for (k, label) in ["by comparing each", "through the indexes"].into_iter().enumerate() {
|
||||
let runs: Vec<String> = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect();
|
||||
println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
/// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop,
|
||||
/// and reads back with each stop on its side.
|
||||
#[test]
|
||||
|
||||
@@ -45,7 +45,8 @@ pub(super) use images::PAYLOAD;
|
||||
pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT};
|
||||
#[cfg(test)]
|
||||
pub(super) use paints::{
|
||||
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
|
||||
GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS,
|
||||
SWATCH_PLACEMENT, free_gradient_name,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
|
||||
@@ -200,11 +201,11 @@ pub(super) struct Writer<'a> {
|
||||
/// pattern's definition, the pattern's space turned y up.
|
||||
canvas: Affine,
|
||||
/// The gradient definitions, in the order they are first used.
|
||||
gradients: Vec<paints::GradientDef>,
|
||||
gradients: paints::GradientDefs,
|
||||
/// The number the next new gradient definition's name tries first (1 is `Gradient`).
|
||||
next_gradient: u64,
|
||||
/// The pattern definitions written, each after those its art uses.
|
||||
patterns: Vec<paints::PatternOut>,
|
||||
patterns: paints::PatternDefs,
|
||||
/// The patterns whose definitions are being written.
|
||||
defining: Vec<String>,
|
||||
/// Writing the palette: the definitions it adds are for its swatches only.
|
||||
@@ -357,9 +358,9 @@ impl<'a> Writer<'a> {
|
||||
grad_space: to_art,
|
||||
tile_grad_space: Affine::translate((-origin.0, origin.1)),
|
||||
canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art,
|
||||
gradients: vec![],
|
||||
gradients: paints::GradientDefs::default(),
|
||||
next_gradient: 1,
|
||||
patterns: vec![],
|
||||
patterns: paints::PatternDefs::default(),
|
||||
defining: vec![],
|
||||
in_palette: false,
|
||||
canvas_origin: origin,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Gradients and patterns: their definitions in the setup, gradient instances on paths and the
|
||||
//! pattern operators (see [`crate::ai_editing`] for the form).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use vectorcraft_color::gradient::GradientGeom;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
@@ -46,6 +48,134 @@ pub(super) struct PatternOut {
|
||||
used: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Whether [`GradientDefs`] and [`PatternDefs`] find definitions on this thread by comparing
|
||||
/// the gradient or name with each definition in turn.
|
||||
pub(in crate::ai_editing) static SCANNED_DEFINITIONS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// How many times [`GradientDefs::find`] has compared two gradients on this thread.
|
||||
pub(in crate::ai_editing) static GRADIENT_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Are gradients `a` and `b` the same?
|
||||
fn same_gradient(a: &Gradient, b: &Gradient) -> bool {
|
||||
#[cfg(test)]
|
||||
GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1));
|
||||
a == b
|
||||
}
|
||||
|
||||
/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its
|
||||
/// bits, with -0 as 0); different gradients may share one.
|
||||
fn gradient_key(g: &Gradient) -> u64 {
|
||||
let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() };
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
std::mem::discriminant(&g.kind).hash(&mut h);
|
||||
std::mem::discriminant(&g.method).hash(&mut h);
|
||||
(g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h);
|
||||
for s in &g.stops {
|
||||
let (model, c) = match s.color {
|
||||
Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]),
|
||||
Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]),
|
||||
Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]),
|
||||
Color::Lab { l, a, b } => (3, [l, a, b, 0.0]),
|
||||
};
|
||||
(model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h);
|
||||
(&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// The gradient definitions, in the order they are first used, found by name and by gradient
|
||||
/// without comparing each one.
|
||||
#[derive(Default)]
|
||||
pub(super) struct GradientDefs {
|
||||
list: Vec<GradientDef>,
|
||||
/// Each definition's place in `list`, by its name (no two definitions share one).
|
||||
names: HashMap<String, usize>,
|
||||
/// The places in `list` of the definitions no swatch names, in order, by their gradient's key
|
||||
/// ([`gradient_key`]).
|
||||
ramps: HashMap<u64, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl GradientDefs {
|
||||
/// Is `name` a definition's name?
|
||||
fn has_name(&self, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return self.list.iter().any(|d| d.name == name);
|
||||
}
|
||||
self.names.contains_key(name)
|
||||
}
|
||||
|
||||
/// The place of the definition of `g`: the swatch `swatch` names when it is a gradient swatch
|
||||
/// of the same gradient, else the first definition of the same gradient that no swatch names.
|
||||
fn find(&self, g: &Gradient, swatch: Option<&str>) -> Option<usize> {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return swatch
|
||||
.and_then(|s| self.list.iter().position(|d| d.swatch && d.name == s && same_gradient(&d.gradient, g)))
|
||||
.or_else(|| self.list.iter().position(|d| !d.swatch && same_gradient(&d.gradient, g)));
|
||||
}
|
||||
let held = |i: &usize, swatch: bool| self.list.get(*i).is_some_and(|d| d.swatch == swatch && same_gradient(&d.gradient, g));
|
||||
swatch
|
||||
.and_then(|s| self.names.get(s).copied().filter(|i| held(i, true)))
|
||||
.or_else(|| self.ramps.get(&gradient_key(g))?.iter().copied().find(|i| held(i, false)))
|
||||
}
|
||||
|
||||
/// Add `d`, whose name no definition has.
|
||||
fn push(&mut self, d: GradientDef) {
|
||||
let i = self.list.len();
|
||||
if !d.swatch {
|
||||
self.ramps.entry(gradient_key(&d.gradient)).or_default().push(i);
|
||||
}
|
||||
self.names.insert(d.name.clone(), i);
|
||||
self.list.push(d);
|
||||
}
|
||||
|
||||
/// Keep the first `len` definitions; the names of those removed are free again.
|
||||
fn truncate(&mut self, len: usize) {
|
||||
while self.list.len() > len {
|
||||
let Some(d) = self.list.pop() else { break };
|
||||
self.names.remove(&d.name);
|
||||
if !d.swatch {
|
||||
// Places are added in order, so the removed definition's is the last of its key's.
|
||||
let key = gradient_key(&d.gradient);
|
||||
if let Some(places) = self.ramps.get_mut(&key) {
|
||||
places.pop();
|
||||
if places.is_empty() {
|
||||
self.ramps.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern definitions written, each after those its art uses, found by name.
|
||||
#[derive(Default)]
|
||||
pub(super) struct PatternDefs {
|
||||
list: Vec<PatternOut>,
|
||||
/// Each definition's place in `list`, by its name (no two definitions share one).
|
||||
names: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl PatternDefs {
|
||||
/// The place of pattern `name`'s definition.
|
||||
fn find(&self, name: &str) -> Option<usize> {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return self.list.iter().position(|p| p.name == name);
|
||||
}
|
||||
self.names.get(name).copied()
|
||||
}
|
||||
|
||||
/// Add `p`, whose name no definition has.
|
||||
fn push(&mut self, p: PatternOut) {
|
||||
self.names.insert(p.name.clone(), self.list.len());
|
||||
self.list.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::ai_editing) const DIAMOND: &str =
|
||||
"diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps";
|
||||
@@ -118,7 +248,7 @@ impl Writer<'_> {
|
||||
&& let stops = curve_as_stops(&g.gradient)
|
||||
&& let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS)
|
||||
&& writable_gradient(&gradient)
|
||||
&& !self.gradients.iter().any(|d| d.name == sw.name)
|
||||
&& !self.gradients.has_name(&sw.name)
|
||||
{
|
||||
self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false });
|
||||
}
|
||||
@@ -131,17 +261,14 @@ impl Writer<'_> {
|
||||
/// swatch or a pattern).
|
||||
fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String {
|
||||
let used = !self.in_palette;
|
||||
let found = swatch
|
||||
.and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g))
|
||||
.or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g));
|
||||
if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) {
|
||||
let found = self.gradients.find(g, swatch);
|
||||
if let Some(d) = found.and_then(|i| self.gradients.list.get_mut(i)) {
|
||||
d.used |= used;
|
||||
return d.name.clone();
|
||||
}
|
||||
let (doc, gradients) = (self.doc, &self.gradients);
|
||||
let name = free_gradient_name(&mut self.next_gradient, |name| {
|
||||
gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()
|
||||
});
|
||||
let name =
|
||||
free_gradient_name(&mut self.next_gradient, |name| gradients.has_name(name) || doc.swatch(name).is_some() || doc.pattern(name).is_some());
|
||||
self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used });
|
||||
name
|
||||
}
|
||||
@@ -149,14 +276,14 @@ impl Writer<'_> {
|
||||
/// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the
|
||||
/// art uses, and the next name's number.
|
||||
pub(super) fn gradient_mark(&self) -> (usize, Vec<bool>, u64) {
|
||||
(self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient)
|
||||
(self.gradients.list.len(), self.gradients.list.iter().map(|d| d.used).collect(), self.next_gradient)
|
||||
}
|
||||
|
||||
/// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]).
|
||||
pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec<bool>, u64)) {
|
||||
let (len, used, next) = mark;
|
||||
self.gradients.truncate(len);
|
||||
for (d, u) in self.gradients.iter_mut().zip(used) {
|
||||
for (d, u) in self.gradients.list.iter_mut().zip(used) {
|
||||
d.used = u;
|
||||
}
|
||||
self.next_gradient = next;
|
||||
@@ -476,7 +603,7 @@ impl Writer<'_> {
|
||||
if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol {
|
||||
return false;
|
||||
}
|
||||
if self.patterns.iter().any(|p| p.name == name) {
|
||||
if self.patterns.find(name).is_some() {
|
||||
return true;
|
||||
}
|
||||
self.doc.pattern(name).is_some_and(tile_holds_art)
|
||||
@@ -492,7 +619,7 @@ impl Writer<'_> {
|
||||
return false;
|
||||
}
|
||||
let used = !self.in_palette;
|
||||
if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) {
|
||||
if let Some(p) = self.patterns.find(name).and_then(|i| self.patterns.list.get_mut(i)) {
|
||||
p.used |= used;
|
||||
return true;
|
||||
}
|
||||
@@ -582,7 +709,7 @@ impl Writer<'_> {
|
||||
/// uses).
|
||||
pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) {
|
||||
let defs = std::mem::take(&mut self.gradients);
|
||||
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used);
|
||||
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.list.iter().partition(|d| d.used);
|
||||
let _ = writeln!(s, "{} Bn", used.len());
|
||||
for d in &used {
|
||||
self.gradient_def(s, d);
|
||||
@@ -595,12 +722,12 @@ impl Writer<'_> {
|
||||
s.push_str("%AI5_End_NonPrinting--\n");
|
||||
}
|
||||
self.gradients = defs;
|
||||
for p in self.patterns.iter().filter(|p| p.used) {
|
||||
for p in self.patterns.list.iter().filter(|p| p.used) {
|
||||
s.push_str(&p.text);
|
||||
}
|
||||
if self.patterns.iter().any(|p| !p.used) {
|
||||
if self.patterns.list.iter().any(|p| !p.used) {
|
||||
s.push_str("%AI5_Begin_NonPrinting\nNp\n");
|
||||
for p in self.patterns.iter().filter(|p| !p.used) {
|
||||
for p in self.patterns.list.iter().filter(|p| !p.used) {
|
||||
s.push_str(&p.text);
|
||||
}
|
||||
s.push_str("%AI5_End_NonPrinting--\n");
|
||||
@@ -729,3 +856,94 @@ fn tile_holds_art(def: &PatternDef) -> bool {
|
||||
b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn two(a: f32, b: Color) -> Gradient {
|
||||
Gradient::new(GradientKind::Linear, vec![GradientStop::new(a, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, b)])
|
||||
}
|
||||
|
||||
fn def(name: &str, gradient: Gradient, swatch: bool) -> GradientDef {
|
||||
GradientDef { name: name.into(), gradient, swatch, used: true }
|
||||
}
|
||||
|
||||
/// The same gradients have the same key, a zero of either sign included.
|
||||
#[test]
|
||||
fn a_zero_of_either_sign_gives_the_same_key() {
|
||||
assert_eq!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(-0.0, Color::BLACK)));
|
||||
assert_eq!(two(0.0, Color::BLACK), two(-0.0, Color::BLACK));
|
||||
assert_ne!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(0.0, Color::WHITE)));
|
||||
}
|
||||
|
||||
/// Definitions whose gradients share a key are told apart by their gradients, the first of the
|
||||
/// same gradient found; a gradient that isn't equal to itself is found in none.
|
||||
#[test]
|
||||
fn definitions_that_share_a_key_are_told_apart() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Gradient", white.clone(), false));
|
||||
defs.push(def("Gradient 2", black.clone(), false));
|
||||
defs.push(def("Gradient 3", black.clone(), false));
|
||||
// Every definition under the black gradient's key, as if the keys of both were the same.
|
||||
defs.ramps = HashMap::from([(gradient_key(&black), vec![0, 1, 2])]);
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, None), None);
|
||||
defs.ramps.insert(gradient_key(&white), vec![0, 1, 2]);
|
||||
assert_eq!(defs.find(&white, None), Some(0));
|
||||
let nan = two(f32::NAN, Color::BLACK);
|
||||
defs.push(def("Gradient 4", nan.clone(), false));
|
||||
assert_eq!(defs.find(&nan, None), None);
|
||||
}
|
||||
|
||||
/// A swatch's definition is found by the swatch's name and gradient; a definition that no
|
||||
/// swatch names, for the same gradient without the name or with another.
|
||||
#[test]
|
||||
fn a_swatch_definition_is_found_by_its_name_and_gradient() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Ramp", black.clone(), true));
|
||||
assert_eq!(defs.find(&black, Some("Ramp")), Some(0));
|
||||
assert_eq!(defs.find(&black, None), None);
|
||||
assert_eq!(defs.find(&white, Some("Ramp")), None);
|
||||
defs.push(def("Gradient", black.clone(), false));
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
assert_eq!(defs.find(&black, Some("Ramp")), Some(0));
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, Some("Ramp")), Some(2));
|
||||
assert_eq!(defs.find(&black, Some("Other")), Some(1));
|
||||
}
|
||||
|
||||
/// Definitions removed leave their names free and are no longer found; those kept still are.
|
||||
#[test]
|
||||
fn removed_definitions_free_their_names() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Ramp", white.clone(), true));
|
||||
defs.push(def("Gradient", black.clone(), false));
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
defs.push(def("Gradient 3", black.clone(), false));
|
||||
defs.truncate(2);
|
||||
assert!(defs.has_name("Ramp") && defs.has_name("Gradient"));
|
||||
assert!(!defs.has_name("Gradient 2") && !defs.has_name("Gradient 3"));
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, None), None);
|
||||
assert_eq!(defs.ramps.values().map(Vec::len).sum::<usize>(), 1);
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
assert_eq!(defs.find(&white, None), Some(2));
|
||||
defs.truncate(0);
|
||||
assert!(defs.list.is_empty() && defs.names.is_empty() && defs.ramps.is_empty());
|
||||
}
|
||||
|
||||
/// A pattern's definition is found by its name.
|
||||
#[test]
|
||||
fn pattern_definitions_are_found_by_name() {
|
||||
let mut defs = PatternDefs::default();
|
||||
assert_eq!(defs.find("Dots"), None);
|
||||
for name in ["Dots", "Checks"] {
|
||||
defs.push(PatternOut { name: name.into(), text: String::new(), used: false });
|
||||
}
|
||||
assert_eq!((defs.find("Dots"), defs.find("Checks"), defs.find("Stripes")), (Some(0), Some(1), None));
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,8 @@ mod tests_native;
|
||||
#[cfg(test)]
|
||||
mod tests_reads;
|
||||
#[cfg(test)]
|
||||
mod tests_strings;
|
||||
#[cfg(test)]
|
||||
mod tests_type1;
|
||||
#[cfg(test)]
|
||||
mod tests_type42;
|
||||
|
||||
@@ -146,13 +146,21 @@ impl Interp<'_> {
|
||||
fn token(&mut self) -> Res {
|
||||
match self.pop()? {
|
||||
Obj::Str(s) => {
|
||||
let bytes = s.to_vec();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
let Some(o) = lex.next()? else { return self.push(Obj::Bool(false)) };
|
||||
let o = self.scanned(o, lex.immediate)?;
|
||||
// The whitespace after the token is read with it.
|
||||
let used = bytes.len() - lex.data().len();
|
||||
self.push_interval(Obj::Str(s), used, bytes.len() - used)?;
|
||||
// The scanner reads the string in place. The borrow ends before `scanned`, which
|
||||
// can fail or charge the budget, and before the results are pushed.
|
||||
let read = {
|
||||
let bytes = s.borrow();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
// The whitespace after the token is read with it.
|
||||
lex.next()?.map(|o| {
|
||||
let immediate = lex.immediate;
|
||||
let rest = lex.data().len();
|
||||
(o, immediate, bytes.len() - rest, rest)
|
||||
})
|
||||
};
|
||||
let Some((o, immediate, used, rest)) = read else { return self.push(Obj::Bool(false)) };
|
||||
let o = self.scanned(o, immediate)?;
|
||||
self.push_interval(Obj::Str(s), used, rest)?;
|
||||
self.push(o)?;
|
||||
}
|
||||
Obj::File { stream: f, .. } => {
|
||||
|
||||
@@ -753,21 +753,25 @@ impl<'a> Interp<'a> {
|
||||
}
|
||||
|
||||
fn search_string(&mut self, op: Op) -> Res {
|
||||
let seek = self.pop_str()?.to_vec();
|
||||
let seek = self.pop_str()?;
|
||||
let s = self.pop_str()?;
|
||||
let text = s.to_vec();
|
||||
self.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
// Both strings are read in place, and the borrows end before the results are pushed.
|
||||
let (len, n, at) = {
|
||||
let (text, seek) = (s.borrow(), seek.borrow());
|
||||
self.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
(text.len(), seek.len(), at)
|
||||
};
|
||||
match at {
|
||||
Some(i) => {
|
||||
let o = Obj::Str(s);
|
||||
if op == Op::Search {
|
||||
self.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?;
|
||||
self.push_interval(o.clone(), i, seek.len())?;
|
||||
self.push_interval(o.clone(), i + n, len - i - n)?;
|
||||
self.push_interval(o.clone(), i, n)?;
|
||||
self.push_interval(o, 0, i)?;
|
||||
} else {
|
||||
self.push_interval(o.clone(), seek.len(), text.len() - seek.len())?;
|
||||
self.push_interval(o, 0, seek.len())?;
|
||||
self.push_interval(o.clone(), n, len - n)?;
|
||||
self.push_interval(o, 0, n)?;
|
||||
}
|
||||
self.push(Obj::Bool(true))?;
|
||||
}
|
||||
|
||||
@@ -49,6 +49,8 @@ thread_local! {
|
||||
/// Tests: the arrays of the list last released on this thread that were still alive after it
|
||||
/// (the ones the interpreter itself still held).
|
||||
pub(crate) static ARRAYS_LEFT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many values [`Shared::to_vec`] has copied on this thread.
|
||||
pub(crate) static VALUES_COPIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -340,7 +342,10 @@ impl<T: Clone + Held> Shared<T> {
|
||||
}
|
||||
|
||||
pub fn to_vec(&self) -> Vec<T> {
|
||||
self.borrow().to_vec()
|
||||
let v = self.borrow().to_vec();
|
||||
#[cfg(test)]
|
||||
VALUES_COPIED.with(|n| n.set(n.get() + v.len()));
|
||||
v
|
||||
}
|
||||
|
||||
/// `n` values from `at`, sharing the storage (`getinterval`); `None` past the end.
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
//! `token` on a string, `search` and `anchorsearch` (PLRM 3rd ed., pp. 702-703, 655 and 529) read
|
||||
//! their strings in place. The tests run them next to reference readers that copy the strings
|
||||
//! first, on the same operands in the same interpreter state: the operand stack, the error and the
|
||||
//! operations spent must agree.
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::graphics::{GState, Out};
|
||||
use super::interp::Interp;
|
||||
use super::lex::Lexer;
|
||||
use super::obj::{Obj, Op, PsError, Res, Shared, VALUES_COPIED};
|
||||
|
||||
/// An interpreter that has run `src`, with the operands it left.
|
||||
fn after(src: &[u8]) -> Interp<'_> {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.layers.clear();
|
||||
let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]);
|
||||
let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0)));
|
||||
assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src));
|
||||
it
|
||||
}
|
||||
|
||||
/// The reference `token`: the string copied before it is scanned.
|
||||
fn token_by_copy(it: &mut Interp) -> Res {
|
||||
match it.pop()? {
|
||||
Obj::Str(s) => {
|
||||
let bytes = s.to_vec();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
let Some(o) = lex.next()? else { return it.push(Obj::Bool(false)) };
|
||||
let o = it.scanned(o, lex.immediate)?;
|
||||
let used = bytes.len() - lex.data().len();
|
||||
it.push_interval(Obj::Str(s), used, bytes.len() - used)?;
|
||||
it.push(o)?;
|
||||
}
|
||||
Obj::File { stream: f, .. } => {
|
||||
let (o, immediate) = it.next_in(&f)?;
|
||||
let Some(o) = o else { return it.push(Obj::Bool(false)) };
|
||||
let o = it.scanned(o, immediate)?;
|
||||
it.push(o)?;
|
||||
}
|
||||
_ => return Err(PsError::Ps("typecheck", "token".into())),
|
||||
}
|
||||
it.push(Obj::Bool(true))
|
||||
}
|
||||
|
||||
/// The reference `search` and `anchorsearch`: both strings copied before they are compared.
|
||||
fn search_by_copy(it: &mut Interp, op: Op) -> Res {
|
||||
let seek = it.pop_str()?.to_vec();
|
||||
let s = it.pop_str()?;
|
||||
let text = s.to_vec();
|
||||
it.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
match at {
|
||||
Some(i) => {
|
||||
let o = Obj::Str(s);
|
||||
if op == Op::Search {
|
||||
it.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?;
|
||||
it.push_interval(o.clone(), i, seek.len())?;
|
||||
it.push_interval(o, 0, i)?;
|
||||
} else {
|
||||
it.push_interval(o.clone(), seek.len(), text.len() - seek.len())?;
|
||||
it.push_interval(o, 0, seek.len())?;
|
||||
}
|
||||
it.push(Obj::Bool(true))?;
|
||||
}
|
||||
None => {
|
||||
it.push(Obj::Str(s))?;
|
||||
it.push(Obj::Bool(false))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn by_copy(it: &mut Interp, op: Op) -> Res {
|
||||
if op == Op::Token { token_by_copy(it) } else { search_by_copy(it, op) }
|
||||
}
|
||||
|
||||
/// The error's name, or the limit reached.
|
||||
fn outcome(r: Res) -> Result<(), String> {
|
||||
r.map_err(|e| match e {
|
||||
PsError::Ps(name, _) => name.to_string(),
|
||||
e => format!("{e:?}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Everything the operator left: the operand stack with each string's storage, offset and length,
|
||||
/// and the operations spent.
|
||||
fn state(it: &Interp) -> (String, u64) {
|
||||
(format!("{:?}", it.stack), it.ops_left())
|
||||
}
|
||||
|
||||
/// Run `op` on the operands `src` leaves, in place and by copy, `steps` times (a walk that feeds
|
||||
/// each call the string the last one left), and check that the two agree after every call.
|
||||
fn agree(src: &str, op: Op, steps: usize) {
|
||||
let (mut new, mut old) = (after(src.as_bytes()), after(src.as_bytes()));
|
||||
// `search` and `anchorsearch` look for the same string on each call.
|
||||
let seeks = [new.stack.last().cloned(), old.stack.last().cloned()];
|
||||
for step in 0..steps {
|
||||
let (a, b) = (outcome(new.op(op)), outcome(by_copy(&mut old, op)));
|
||||
assert_eq!(a, b, "{src} {op:?}, call {step}");
|
||||
assert_eq!(state(&new), state(&old), "{src} {op:?}, call {step}");
|
||||
// Keep walking while the operator answered true, with the string it left.
|
||||
let more = matches!(new.stack.last(), Some(Obj::Bool(true)));
|
||||
if a.is_err() || !more {
|
||||
break;
|
||||
}
|
||||
for (it, seek) in [&mut new, &mut old].into_iter().zip(&seeks) {
|
||||
it.stack.pop();
|
||||
// `token` leaves the rest under the object; `search` leaves it under match and pre
|
||||
// (and `anchorsearch` under the match).
|
||||
let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 };
|
||||
it.stack.truncate(keep);
|
||||
// The string to look for again, or the file `token` reads on from.
|
||||
if op != Op::Token || matches!(seek, Some(Obj::File { .. })) {
|
||||
it.stack.extend(seek.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
new.release();
|
||||
old.release();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_and_search_agree_with_copying_readers() {
|
||||
let tokens = [
|
||||
"()",
|
||||
"( )",
|
||||
"(\r\n\t )",
|
||||
"(12)",
|
||||
"(12 34)",
|
||||
"(12 34)",
|
||||
"(12\r\n34)",
|
||||
"(/x {a b} (s) <41> 1.5 x)",
|
||||
"(1 {)",
|
||||
"( [ 1 ] )",
|
||||
"/x 7 def (//x {//x} y)",
|
||||
"(xx12 34 56) 2 7 getinterval",
|
||||
"(%comment only)",
|
||||
"5",
|
||||
"(12 /x {a}) /ReusableStreamDecode filter",
|
||||
"currentfile",
|
||||
];
|
||||
for src in tokens {
|
||||
agree(src, Op::Token, 16);
|
||||
}
|
||||
let searches = [
|
||||
"(abcabc) (bc)",
|
||||
"(abc) (x)",
|
||||
"(abc) ()",
|
||||
"() ()",
|
||||
"() (a)",
|
||||
"(ab) (abc)",
|
||||
"(a\nb\nc\n) (\n)",
|
||||
"/s (aa) def s s",
|
||||
"(xxab cd ef) 2 8 getinterval ( )",
|
||||
"(abc) 5",
|
||||
"5 (abc)",
|
||||
];
|
||||
for src in searches {
|
||||
agree(src, Op::Search, 8);
|
||||
agree(src, Op::AnchorSearch, 8);
|
||||
}
|
||||
// Over the operation budget: the same error, with the same operands popped.
|
||||
let big = "/h 65536 string def h (\\001)";
|
||||
let (mut new, mut old) = (after(big.as_bytes()), after(big.as_bytes()));
|
||||
for it in [&mut new, &mut old] {
|
||||
let left = it.ops_left();
|
||||
assert_eq!(it.spend(left.saturating_sub(10)), Ok(()));
|
||||
}
|
||||
let (a, b) = (outcome(new.op(Op::Search)), outcome(by_copy(&mut old, Op::Search)));
|
||||
assert!(a.as_ref().is_err_and(|e| e.contains("too long")), "{a:?}");
|
||||
assert_eq!((a, state(&new)), (b, state(&old)));
|
||||
new.release();
|
||||
old.release();
|
||||
}
|
||||
|
||||
/// The results share the string's storage: a write to the string after `token` or `search` shows
|
||||
/// in what they left.
|
||||
#[test]
|
||||
fn token_and_search_results_see_later_writes() {
|
||||
let check = super::tests::check;
|
||||
check("/s (12 34) def s token pop pop /post exch def s 3 57 put post token pop exch pop 94 eq");
|
||||
check("/s (ab cd) def s ( ) search pop /pre exch def pop /post exch def s 0 120 put s 4 121 put pre (xb) eq post (cy) eq and");
|
||||
check("/s (ab cd) def s (ab) anchorsearch pop pop /post exch def s 4 122 put post ( cz) eq");
|
||||
check("/s (xx12 34) def s 2 5 getinterval token pop pop /post exch def s 5 57 put post token pop exch pop 94 eq");
|
||||
}
|
||||
|
||||
/// `token` on a string, `search` and `anchorsearch` copy neither string.
|
||||
#[test]
|
||||
fn token_and_search_copy_no_string() {
|
||||
for (src, op) in [
|
||||
("(12 34 56 78)", Op::Token),
|
||||
("(abc def ghi) ( )", Op::Search),
|
||||
("(abc def ghi) (xyz)", Op::Search),
|
||||
("(abc def ghi) (abc)", Op::AnchorSearch),
|
||||
("(abc def ghi) (def)", Op::AnchorSearch),
|
||||
] {
|
||||
let mut it = after(src.as_bytes());
|
||||
VALUES_COPIED.with(|n| n.set(0));
|
||||
assert_eq!(it.op(op), Ok(()), "{src} {op:?}");
|
||||
assert_eq!(VALUES_COPIED.with(std::cell::Cell::get), 0, "{src} {op:?}");
|
||||
it.release();
|
||||
}
|
||||
}
|
||||
|
||||
/// The median of `runs`.
|
||||
fn median(runs: &[Duration]) -> Duration {
|
||||
let mut sorted = runs.to_vec();
|
||||
sorted.sort();
|
||||
sorted.get(sorted.len() / 2).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a walk records of each result: a string's length and first bytes, any other object whole.
|
||||
fn mark(o: &Obj, h: &mut impl Hasher) {
|
||||
match o {
|
||||
Obj::Str(s) => {
|
||||
s.len().hash(h);
|
||||
s.borrow().iter().take(16).for_each(|b| b.hash(h));
|
||||
}
|
||||
o => format!("{o:?}").hash(h),
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk `data` with `op` and `seek` (none for `token`) until the operator answers false, by copy
|
||||
/// or in place: how long it took, the calls made, and a hash of every result and of the operations
|
||||
/// spent. The interpreter is made before the clock starts.
|
||||
fn walk(data: &[u8], op: Op, seek: Option<&[u8]>, copy: bool) -> (Duration, usize, u64) {
|
||||
let mut it = after(b"");
|
||||
it.stack.push(Obj::Str(Shared::new(data.to_vec())));
|
||||
let mut calls = 0;
|
||||
let mut h = DefaultHasher::new();
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if let Some(seek) = seek {
|
||||
it.stack.push(Obj::Str(Shared::new(seek.to_vec())));
|
||||
}
|
||||
let r = if copy { by_copy(&mut it, op) } else { it.op(op) };
|
||||
assert_eq!(r, Ok(()));
|
||||
calls += 1;
|
||||
if !matches!(it.stack.pop(), Some(Obj::Bool(true))) {
|
||||
break;
|
||||
}
|
||||
let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 };
|
||||
it.stack.iter().for_each(|o| mark(o, &mut h));
|
||||
it.stack.truncate(keep);
|
||||
}
|
||||
let took = start.elapsed();
|
||||
it.stack.iter().for_each(|o| mark(o, &mut h));
|
||||
it.ops_left().hash(&mut h);
|
||||
it.release();
|
||||
(took, calls, h.finish())
|
||||
}
|
||||
|
||||
/// Time both readers on `data` in 7 runs, alternating which goes first, check that they leave the
|
||||
/// same, and print every run and the medians.
|
||||
fn compare(what: &str, data: &[u8], op: Op, seek: Option<&[u8]>) {
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
let mut calls = 0;
|
||||
for run in 0..7 {
|
||||
let order: [bool; 2] = if run % 2 == 0 { [true, false] } else { [false, true] };
|
||||
let mut got = vec![];
|
||||
for copy in order {
|
||||
let (took, n, last) = walk(data, op, seek, copy);
|
||||
if copy {
|
||||
old.push(took)
|
||||
} else {
|
||||
new.push(took)
|
||||
}
|
||||
calls = n;
|
||||
got.push((n, last));
|
||||
}
|
||||
assert!(got.first() == got.get(1), "{what}: the readers differ");
|
||||
}
|
||||
let ms = |d: &Duration| format!("{:.2}", d.as_secs_f64() * 1000.0);
|
||||
println!("{what}: {} bytes, {calls} calls", data.len());
|
||||
println!(" by copy, ms: {}", old.iter().map(ms).collect::<Vec<_>>().join(" "));
|
||||
println!(" in place, ms: {}", new.iter().map(ms).collect::<Vec<_>>().join(" "));
|
||||
let (o, w) = (median(&old), median(&new));
|
||||
println!(" median: by copy {} ms, in place {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9));
|
||||
}
|
||||
|
||||
/// Times `token` and `search` walking a string by what each call leaves, against the copying
|
||||
/// reference readers, in one process: strings of 4 KiB, 64 KiB and 512 KiB, of numbers and names
|
||||
/// for `token` and of 128-byte lines for `search`. Run it in release:
|
||||
/// `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn string_walks_timed() {
|
||||
for kib in [4, 64, 512] {
|
||||
let size = kib * 1024;
|
||||
let mut words = Vec::with_capacity(size + 16);
|
||||
let mut i = 0u32;
|
||||
while words.len() < size {
|
||||
let w = if i.is_multiple_of(2) { format!("{} ", i.wrapping_mul(2_654_435_761) % 100_000) } else { format!("/n{i} ") };
|
||||
words.extend_from_slice(w.as_bytes());
|
||||
i += 1;
|
||||
}
|
||||
compare(&format!("token, {kib} KiB"), &words, Op::Token, None);
|
||||
let lines: Vec<u8> = (0..size / 128).flat_map(|i| format!("{:<127}\n", format!("line {i}")).into_bytes()).collect();
|
||||
compare(&format!("search, {kib} KiB"), &lines, Op::Search, Some(b"\n"));
|
||||
}
|
||||
}
|
||||
@@ -1636,6 +1636,33 @@ fn doc_json(s: &mut Server) -> Value {
|
||||
serde_json::from_str(&text_of(&r)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_refused_by_a_later_operation_changes_nothing() {
|
||||
let mut s = server();
|
||||
let count = |s: &mut Server| -> u64 {
|
||||
let r = call(s, 90, "inspect_document", json!({}));
|
||||
serde_json::from_str::<Value>(&text_of(&r)).unwrap()["objects"].as_u64().unwrap()
|
||||
};
|
||||
let base = count(&mut s);
|
||||
let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50})));
|
||||
let before = doc_json(&mut s);
|
||||
for (id, args, says) in [
|
||||
(2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"),
|
||||
(3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"),
|
||||
(4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"),
|
||||
(5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"),
|
||||
(6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"),
|
||||
] {
|
||||
let t = call(&mut s, id, "transform", args.clone());
|
||||
assert_eq!(t["isError"], true, "{args}: {t}");
|
||||
assert!(text_of(&t).contains(says), "{args}: {t}");
|
||||
assert_eq!(doc_json(&mut s), before, "{args}");
|
||||
}
|
||||
// No undo step was recorded: one undo removes the rectangle.
|
||||
assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false);
|
||||
assert_eq!(count(&mut s), base, "one undo removes the rectangle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_text_rejects_invalid_path_effects_before_editing() {
|
||||
let mut s = server();
|
||||
|
||||
@@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"transform",
|
||||
"Transform",
|
||||
"Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.",
|
||||
"Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.",
|
||||
obj(
|
||||
json!({
|
||||
"ids": {"type": "array", "items": {"type": "integer"}},
|
||||
|
||||
@@ -302,6 +302,24 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
}
|
||||
|
||||
pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
// Each operation is its own command: check the params the later ones refuse before the first
|
||||
// runs, so a refused request changes nothing.
|
||||
fn bad(cmd: &'static str) -> impl Fn(String) -> String {
|
||||
move |e| format!("invalid parameters for `{cmd}`: {e}")
|
||||
}
|
||||
let s = a.get("scale").and_then(Value::as_f64);
|
||||
let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s));
|
||||
if sx.is_some() || sy.is_some() {
|
||||
vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?;
|
||||
}
|
||||
let reflect = a.get("reflect").and_then(Value::as_str);
|
||||
if let Some(axis) = reflect {
|
||||
vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?;
|
||||
}
|
||||
let shear = a.get("shear").and_then(Value::as_f64);
|
||||
if let Some(sh) = shear {
|
||||
vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?;
|
||||
}
|
||||
select_ids(b, a)?;
|
||||
// With `copy`, the first operation duplicates and the rest transform the copy (the new selection).
|
||||
let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false));
|
||||
@@ -322,17 +340,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String>
|
||||
exec(b, "object.rotate", with(json!({"angle": r})))?;
|
||||
done.push("rotate");
|
||||
}
|
||||
let s = a.get("scale").and_then(Value::as_f64);
|
||||
let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s));
|
||||
if sx.is_some() || sy.is_some() {
|
||||
exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?;
|
||||
done.push("scale");
|
||||
}
|
||||
if let Some(axis) = a.get("reflect").and_then(Value::as_str) {
|
||||
if let Some(axis) = reflect {
|
||||
exec(b, "object.reflect", with(json!({"axis": axis})))?;
|
||||
done.push("reflect");
|
||||
}
|
||||
if let Some(sh) = a.get("shear").and_then(Value::as_f64) {
|
||||
if let Some(sh) = shear {
|
||||
exec(b, "object.shear", with(json!({"angle": sh})))?;
|
||||
done.push("shear");
|
||||
}
|
||||
|
||||
@@ -1026,7 +1026,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.symbolOptions",
|
||||
"Symbol Options…",
|
||||
"F8",
|
||||
"{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}",
|
||||
"{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error",
|
||||
),
|
||||
(
|
||||
"tool.options",
|
||||
|
||||
+104
-27
@@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash ";
|
||||
/// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it
|
||||
/// keeps every offset.
|
||||
const PLACEHOLDER: &str = "0000000000000000";
|
||||
/// Deepest name tree searched for the editing file.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// The most name tree nodes searched for the editing file.
|
||||
const MAX_NODES: usize = 1 << 16;
|
||||
|
||||
/// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -77,12 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option<Editing> {
|
||||
editing_in(&crate::pages::open(bytes, password).ok()?)
|
||||
}
|
||||
|
||||
/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]).
|
||||
struct Search<'a> {
|
||||
/// The editing file's file specification, if one was found.
|
||||
spec: Option<Dict<'a>>,
|
||||
/// A name tree key searched names the editing file (set also when its file specification
|
||||
/// can't be read).
|
||||
keyed: bool,
|
||||
/// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched.
|
||||
cut: bool,
|
||||
}
|
||||
|
||||
/// The search of a parsed PDF's attachments for the editing file.
|
||||
fn editing_file_spec(pdf: &Pdf) -> Search<'_> {
|
||||
let xref = pdf.xref();
|
||||
let Some(tree) = xref
|
||||
.get::<Dict<'_>>(xref.root_id())
|
||||
.and_then(|catalog| catalog.get::<Dict<'_>>(b"Names"))
|
||||
.and_then(|names| names.get::<Dict<'_>>(b"EmbeddedFiles"))
|
||||
else {
|
||||
return Search { spec: None, keyed: false, cut: false };
|
||||
};
|
||||
let (mut keyed, mut cut) = (false, false);
|
||||
let spec = editing_spec(tree, &mut keyed, &mut cut, xref);
|
||||
Search { spec, keyed, cut }
|
||||
}
|
||||
|
||||
/// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't
|
||||
/// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be
|
||||
/// resolved)? Also true when the name tree is too large to search to its end.
|
||||
pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool {
|
||||
let search = editing_file_spec(pdf);
|
||||
search.spec.is_some() || search.keyed || search.cut
|
||||
}
|
||||
|
||||
/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`]
|
||||
/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it
|
||||
/// reads.
|
||||
pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool {
|
||||
editing_file_spec(pdf).cut
|
||||
}
|
||||
|
||||
/// [`editing`] of a parsed PDF.
|
||||
pub(crate) fn editing_in(pdf: &Pdf) -> Option<Editing> {
|
||||
let xref = pdf.xref();
|
||||
let catalog = xref.get::<Dict<'_>>(xref.root_id())?;
|
||||
let tree = catalog.get::<Dict<'_>>(b"Names")?.get::<Dict<'_>>(b"EmbeddedFiles")?;
|
||||
let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?;
|
||||
let spec = editing_file_spec(pdf).spec?;
|
||||
let files = spec.get::<Dict<'_>>(b"EF")?;
|
||||
let stream = files.get::<Stream<'_>>(b"F").or_else(|| files.get::<Stream<'_>>(b"UF"))?;
|
||||
let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default();
|
||||
@@ -96,10 +134,59 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option<Editing> {
|
||||
Some(Editing { data, intact })
|
||||
}
|
||||
|
||||
/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect
|
||||
/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path.
|
||||
fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet<ObjectIdentifier>, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
/// The first file specification of the editing file in the name tree `tree`, searched in order at
|
||||
/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the
|
||||
/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is
|
||||
/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is
|
||||
/// set when a key searched names the editing file, and `cut` when nodes are left unsearched.
|
||||
fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
let mut seen = HashSet::<ObjectIdentifier>::new();
|
||||
let mut nodes = vec![tree];
|
||||
let mut found = None;
|
||||
// Nodes still to be searched, counting the ones waiting in `nodes`.
|
||||
let mut left = MAX_NODES - 1;
|
||||
while let Some(node) = nodes.pop() {
|
||||
// Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut.
|
||||
if found.is_none() {
|
||||
found = node_spec(&node, keyed, xref);
|
||||
}
|
||||
let Some(kids) = node.get::<Array<'a>>(b"Kids") else { continue };
|
||||
// Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The
|
||||
// reference is checked before the kid is read, so a shared kid is read once.
|
||||
let mut kids: Vec<Dict<'a>> = items(&kids)
|
||||
.filter_map(|raw| match raw {
|
||||
MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::<Dict<'a>>(r.into()),
|
||||
MaybeRef::NotRef(Object::Dict(kid)) => Some(kid),
|
||||
_ => None,
|
||||
})
|
||||
.take(left.saturating_add(1))
|
||||
.collect();
|
||||
if kids.len() > left {
|
||||
*cut = true;
|
||||
kids.truncate(left);
|
||||
}
|
||||
left -= kids.len();
|
||||
nodes.extend(kids.into_iter().rev());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The file specification of the editing file among the name tree node `node`'s own `Names`.
|
||||
/// `keyed` is set when a key names the editing file.
|
||||
fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
if let Some(names) = node.get::<Array<'a>>(b"Names") {
|
||||
// The keys read as written, so a value that can't be resolved doesn't shift the pairs.
|
||||
let mut raw = items(&names);
|
||||
while let (Some(key), Some(_)) = (raw.next(), raw.next()) {
|
||||
let key = match key {
|
||||
MaybeRef::NotRef(Object::String(key)) => Some(key),
|
||||
MaybeRef::Ref(r) => xref.get::<PdfString<'a>>(r.into()),
|
||||
MaybeRef::NotRef(_) => None,
|
||||
};
|
||||
if key.is_some_and(|key| is_editing_name(&key)) {
|
||||
*keyed = true;
|
||||
}
|
||||
}
|
||||
let mut items = names.iter::<Object<'a>>();
|
||||
while let (Some(_), Some(spec)) = (items.next(), items.next()) {
|
||||
if let Object::Dict(spec) = spec
|
||||
@@ -109,29 +196,19 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet<ObjectIden
|
||||
}
|
||||
}
|
||||
}
|
||||
if depth >= MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let kids = node.get::<Array<'a>>(b"Kids")?;
|
||||
// Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The
|
||||
// reference is checked before the kid is read, so a shared kid is read once.
|
||||
items(&kids).find_map(|raw| {
|
||||
let kid = match raw {
|
||||
MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::<Dict<'a>>(r.into())?,
|
||||
MaybeRef::NotRef(Object::Dict(kid)) => kid,
|
||||
_ => return None,
|
||||
};
|
||||
editing_spec(&kid, depth + 1, seen, xref)
|
||||
})
|
||||
None
|
||||
}
|
||||
|
||||
/// A file specification naming the editing file (current or legacy name), in any text string
|
||||
/// encoding.
|
||||
fn is_editing_file(spec: &Dict<'_>) -> bool {
|
||||
[&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::<PdfString<'_>>(k)).any(|name| {
|
||||
let name = text_string(name.as_bytes());
|
||||
name == EDITING_FILE || name == LEGACY_EDITING_FILE
|
||||
})
|
||||
[&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::<PdfString<'_>>(k)).any(|name| is_editing_name(&name))
|
||||
}
|
||||
|
||||
/// A text string that is the editing file's name (current or legacy), in any encoding.
|
||||
fn is_editing_name(name: &PdfString<'_>) -> bool {
|
||||
let name = text_string(name.as_bytes());
|
||||
name == EDITING_FILE || name == LEGACY_EDITING_FILE
|
||||
}
|
||||
|
||||
/// The most decoded page content [`page_hash`] reads in all (bytes).
|
||||
|
||||
@@ -64,8 +64,8 @@ pub(crate) struct Sheet<'a> {
|
||||
|
||||
impl Writer {
|
||||
/// A PDF with `set`'s version, standard, compression and colour output, and `doc`'s metadata
|
||||
/// under `title`, created at `created` (Unix seconds). With `cmyk`, transparency blends in
|
||||
/// CMYK (unless the colours are converted to RGB).
|
||||
/// and language under `title`, created at `created` (Unix seconds). With `cmyk`, transparency
|
||||
/// blends in CMYK (unless the colours are converted to RGB).
|
||||
pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option<i64>, cmyk: bool) -> Result<Self, PdfError> {
|
||||
let out = ColorOut::new(doc, set)?;
|
||||
let mut warnings = out.profile_notes.clone();
|
||||
@@ -111,7 +111,11 @@ impl Writer {
|
||||
created: created.map(date_time),
|
||||
modified: None,
|
||||
};
|
||||
let pdf = write::Writer::new(settings, metadata);
|
||||
// The document language (Document Setup) as the catalog's `Lang` and the XMP packet's
|
||||
// `dc:language` (ISO 32000-1, 14.9.2): its BCP 47 tag. A language without a tag writes
|
||||
// none rather than a guess.
|
||||
let language = vectorcraft_doc::setup::language_tag(&doc.setup.language).map(str::to_string);
|
||||
let pdf = write::Writer::new_with_language(settings, metadata, language);
|
||||
Ok(Self {
|
||||
pdf,
|
||||
cmyk: out.blends_cmyk(cmyk),
|
||||
|
||||
@@ -261,6 +261,18 @@ impl Opened {
|
||||
crate::editing::editing_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// Does the PDF list the editing file among its attachments, also when
|
||||
/// [`editing`](Self::editing) can't read it?
|
||||
pub fn has_editing_file(&self) -> bool {
|
||||
crate::editing::has_editing_file_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// Is the PDF's attachment name tree too large to search to its end? It may then list an
|
||||
/// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads.
|
||||
pub fn editing_search_cut(&self) -> bool {
|
||||
crate::editing::editing_search_cut_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it.
|
||||
pub fn illustrator_data(&self) -> Option<Vec<u8>> {
|
||||
private_data(&self.pdf)
|
||||
|
||||
@@ -1449,6 +1449,41 @@ fn empty_and_populated_file_info_preserve_key_presence() {
|
||||
assert!(s.contains("/ViewerPreferences<</DisplayDocTitle true>>"), "viewers should show the document title (#3646)");
|
||||
}
|
||||
|
||||
/// The text of the `/Lang` entry of the catalog of `pdf` (a literal string), if any.
|
||||
fn catalog_lang(pdf: &[u8]) -> Option<String> {
|
||||
let xref = crate::patch::Xref::read(pdf).expect("a cross-reference table");
|
||||
let root = xref.trailer_ref(pdf, b"/Root").expect("a catalog");
|
||||
let (start, end) = xref.dict(pdf, root).expect("the catalog's dictionary");
|
||||
let catalog = String::from_utf8_lossy(&pdf[start..end]).into_owned();
|
||||
let at = catalog.find("/Lang")? + "/Lang".len();
|
||||
let rest = catalog[at..].trim_start().strip_prefix('(').expect("a literal string");
|
||||
Some(rest[..rest.find(')').expect("a closed string")].to_string())
|
||||
}
|
||||
|
||||
/// The catalog gives the document language chosen in Document Setup as its BCP 47 tag, in
|
||||
/// exported and printed PDFs, and the XMP packet says it too (#3644).
|
||||
#[test]
|
||||
fn the_catalog_gives_the_document_language() {
|
||||
let mut d = doc(100.0, 100.0);
|
||||
for (language, tag) in [(None, "en-US"), (Some("French"), "fr"), (Some("German: Swiss"), "de-CH")] {
|
||||
if let Some(language) = language {
|
||||
d.setup.language = language.into();
|
||||
}
|
||||
for opts in [PdfOptions::uncompressed(), PdfOptions::default()] {
|
||||
let bytes = export(&d, &opts).unwrap();
|
||||
assert_eq!(catalog_lang(&bytes).as_deref(), Some(tag), "{language:?}");
|
||||
}
|
||||
// Print to PDF writes its file with the same writer.
|
||||
let printed = print(&d, &PrintOptions { created: Some(1_700_000_000), ..Default::default() }).unwrap();
|
||||
assert_eq!(catalog_lang(&printed.bytes).as_deref(), Some(tag), "{language:?}: printed");
|
||||
let s = uncompressed(&d);
|
||||
assert!(s.contains(&format!("<dc:language><rdf:Bag><rdf:li>{tag}</rdf:li></rdf:Bag></dc:language>")), "{language:?}: {s}");
|
||||
}
|
||||
// A language without a tag (from a file) writes none rather than a guess.
|
||||
d.setup.language = "Klingon".into();
|
||||
assert_eq!(catalog_lang(&export(&d, &PdfOptions::uncompressed()).unwrap()), None);
|
||||
}
|
||||
|
||||
/// A function or colour space built on itself is refused before the interpreter builds it (by
|
||||
/// recursion, with no cap: a stack overflow), and those of real files are read.
|
||||
#[test]
|
||||
|
||||
@@ -237,3 +237,104 @@ fn a_file_name_written_as_utf16_is_found() {
|
||||
assert_eq!(e.data, b"hello", "/{key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() {
|
||||
// No `EF` dictionary, an `EF` without `F` or `UF`, and an `F` naming no object.
|
||||
for ef in ["", "/EF << >>", "/EF << /F 9 0 R >>"] {
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [5 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Names [(a) 4 0 R] >>".to_string(),
|
||||
format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
];
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing(), None, "{ef:?}");
|
||||
assert!(opened.has_editing_file(), "{ef:?}");
|
||||
}
|
||||
// A name tree key naming it, with a file specification that names no object or isn't one.
|
||||
for spec in ["9 0 R", "(not a file specification)"] {
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(),
|
||||
format!("<< /Names [(a) 9 0 R ({EDITING_FILE}) {spec}] >>"),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
];
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing(), None, "{spec}");
|
||||
assert!(opened.has_editing_file(), "{spec}");
|
||||
}
|
||||
// The key written as an indirect string.
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Names [5 0 R 9 0 R] >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
format!("({EDITING_FILE})"),
|
||||
];
|
||||
assert!(open_pdf(&raw_pdf(&objects), None).unwrap().has_editing_file());
|
||||
// A PDF without the editing file, and one with it.
|
||||
assert!(!open_pdf(&export(&doc(), &PdfOptions::default()).unwrap(), None).unwrap().has_editing_file());
|
||||
let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap();
|
||||
assert!(opened.editing().is_some() && opened.has_editing_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_editing_file_deep_in_the_name_tree_is_found() {
|
||||
// Objects 4..=203 are a chain of 200 name tree nodes, each listing the next one; the editing
|
||||
// file sits in the leaf (object 204), with its data or naming data that can't be resolved.
|
||||
for ef in ["/EF << /F 206 0 R >>", "/EF << /F 999 0 R >>"] {
|
||||
let mut objects = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [207 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Kids [4 0 R] >>".to_string(),
|
||||
];
|
||||
for node in 4..=203 {
|
||||
objects.push(format!("<< /Kids [{} 0 R] >>", node + 1));
|
||||
}
|
||||
objects.push("<< /Names [(a) 205 0 R] >>".to_string());
|
||||
objects.push(format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"));
|
||||
objects.push("<< /Length 5 >>\nstream\nhello\nendstream".to_string());
|
||||
objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string());
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert!(opened.has_editing_file(), "{ef}");
|
||||
let data = opened.editing().map(|e| e.data);
|
||||
assert_eq!(data.as_deref(), ef.contains("206").then_some(&b"hello"[..]), "{ef}");
|
||||
}
|
||||
// A name tree with more nodes than are searched may list it.
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(),
|
||||
format!("<< /Kids [{}] >>", "<< /Names [] >> ".repeat(70_000)),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
];
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing(), None);
|
||||
assert!(opened.has_editing_file() && opened.editing_search_cut());
|
||||
// One that lists a readable editing file before the nodes left unsearched and another after
|
||||
// them: the first is read, and the search reads as cut short.
|
||||
let leaf = |stream: u32| format!("<< /Names [({EDITING_FILE}) << /Type /Filespec /UF ({EDITING_FILE}) /EF << /F {stream} 0 R >> >>] >>");
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [8 0 R] /Count 1 >>".to_string(),
|
||||
format!("<< /Kids [4 0 R {}5 0 R] >>", "<< /Names [] >> ".repeat(70_000)),
|
||||
leaf(6),
|
||||
leaf(7),
|
||||
"<< /Length 5 >>\nstream\nfirst\nendstream".to_string(),
|
||||
"<< /Length 6 >>\nstream\nsecond\nendstream".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
];
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..]));
|
||||
assert!(opened.has_editing_file() && opened.editing_search_cut());
|
||||
// The same, with the nodes past the limit in a subtree after the one holding the first.
|
||||
let mut objects = objects;
|
||||
objects[2] = format!("<< /Kids [4 0 R << /Kids [{}5 0 R] >>] >>", "<< /Names [] >> ".repeat(70_000));
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..]));
|
||||
assert!(opened.has_editing_file() && opened.editing_search_cut());
|
||||
// A tree searched to its end.
|
||||
let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap();
|
||||
assert!(opened.editing().is_some() && !opened.editing_search_cut());
|
||||
}
|
||||
@@ -53,7 +53,7 @@ pub mod wat;
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms};
|
||||
#[doc(hidden)]
|
||||
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
|
||||
|
||||
|
||||
@@ -35,6 +35,11 @@ pub const HEAVY_FUEL: u64 = 1_000_000_000;
|
||||
/// Wall-clock budget of a heavy filter's run, in milliseconds.
|
||||
pub const HEAVY_WALL_TIME_MS: u64 = 300_000;
|
||||
|
||||
/// Instructions a filter's run may use besides [`Limits::fuel_per_byte`] for each byte of input
|
||||
/// when Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget is Large
|
||||
/// ([`Plugin::large_limits`]): 5 times the default.
|
||||
pub const LARGE_FUEL: u64 = 250_000_000;
|
||||
|
||||
/// The limit a run reports when its input and parameters together are past half its memory.
|
||||
pub(crate) const SELECTION_TOO_LARGE: &str = "memory budget (the selection is too large to hand over)";
|
||||
|
||||
@@ -215,6 +220,12 @@ impl Plugin {
|
||||
pub fn limits(&self) -> &Limits {
|
||||
&self.limits
|
||||
}
|
||||
/// Its limits with the Large instruction budget: at least [`LARGE_FUEL`] instructions besides
|
||||
/// those for each byte of input, and every other limit, the time budget included, as it is. A
|
||||
/// heavy filter keeps its larger budget.
|
||||
pub fn large_limits(&self) -> Limits {
|
||||
Limits { fuel_base: self.limits.fuel_base.max(LARGE_FUEL), ..self.limits.clone() }
|
||||
}
|
||||
/// Module size in bytes.
|
||||
pub fn size(&self) -> usize {
|
||||
self.size
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_plugins::storage::{Meter, Storage, StorageError};
|
||||
use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, Limits, Plugin, Report, heavy_terms, registry, wat as tpl};
|
||||
use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl};
|
||||
|
||||
/// The example Desaturate plug-in, built from `crates/plugins/example`.
|
||||
const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm");
|
||||
@@ -259,6 +259,23 @@ fn a_heavy_filter_finishes_what_a_light_one_cannot() {
|
||||
assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes());
|
||||
}
|
||||
|
||||
/// The Large instruction budget gives a light filter 5 times the instructions besides those for
|
||||
/// each byte of input, so it finishes 20 million steps of a loop that its own budget can't, in the
|
||||
/// same time budget. A heavy filter keeps its larger budget, and every other limit stays.
|
||||
#[test]
|
||||
fn the_large_budget_finishes_what_a_light_one_cannot_and_keeps_a_heavy_one() {
|
||||
let light = Plugin::load(&build(&tpl::spinning(MANIFEST, 20_000_000, INPUT)), Limits::default()).unwrap();
|
||||
assert_eq!(light.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into())));
|
||||
let large = light.large_limits();
|
||||
assert_eq!(large, Limits { fuel_base: LARGE_FUEL, ..Limits::default() });
|
||||
assert_eq!(LARGE_FUEL, 5 * Limits::default().fuel_base);
|
||||
assert_eq!(light.run_limited(INPUT.as_bytes(), b"{}", &large).unwrap(), INPUT.as_bytes());
|
||||
let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#;
|
||||
let heavy = Plugin::load(&build(&tpl::spinning(heavy, 1, INPUT)), Limits::default()).unwrap();
|
||||
assert_eq!(heavy.large_limits(), *heavy.limits());
|
||||
assert_eq!((heavy.large_limits().fuel_base, heavy.large_limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exporter_returns_its_file_with_an_export_s_budget() {
|
||||
use vectorcraft_plugins::export::{self, Target};
|
||||
|
||||
@@ -82,6 +82,7 @@ impl VectorcraftApp {
|
||||
slices: None,
|
||||
print_tiling: None,
|
||||
live_paint_gaps: None,
|
||||
find_font: None,
|
||||
hidden_chars: Default::default(),
|
||||
spelling: Default::default(),
|
||||
selection_marks: Default::default(),
|
||||
|
||||
@@ -42,6 +42,10 @@ pub struct CanvasCache {
|
||||
pub print_tiling: Option<PrintTilingCache>,
|
||||
/// The gap lines View → Show Live Paint Gaps draws for (document uid, revision).
|
||||
pub live_paint_gaps: Option<LivePaintGapsCache>,
|
||||
/// Type → Find Font's list of the document's fonts and whether the document misses one, for a
|
||||
/// version of the document's content and of the available fonts: the dialog reads them every
|
||||
/// frame.
|
||||
pub find_font: Option<FindFontCache>,
|
||||
/// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame
|
||||
/// that does not draw them drops them ([`canvas::show`]).
|
||||
pub hidden_chars: canvas::HiddenChars,
|
||||
@@ -117,6 +121,32 @@ pub type SliceCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_doc::SliceArea
|
||||
/// uid, revision).
|
||||
pub type LivePaintGapsCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_tools::Overlay>>);
|
||||
|
||||
/// [`CanvasCache::find_font`]: the document's fonts as `text.fonts` lists them, and whether
|
||||
/// [`vectorcraft_engine::cmd::fontfiles::missing_fonts`] finds any (`None` until it is asked).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FindFontCache {
|
||||
/// The document and the content and fonts the answers were worked out from.
|
||||
pub key: FontsKey,
|
||||
pub fonts: std::sync::Arc<Vec<serde_json::Value>>,
|
||||
pub missing: Option<bool>,
|
||||
}
|
||||
|
||||
/// A document's uid, a version of its content (compared by identity) and the font database's
|
||||
/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's
|
||||
/// allocation, so a later version is never placed at the same address while the key is kept.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FontsKey {
|
||||
pub uid: u64,
|
||||
pub doc: std::sync::Weak<vectorcraft_doc::Document>,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
impl PartialEq for FontsKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.uid == other.uid && self.generation == other.generation && std::sync::Weak::ptr_eq(&self.doc, &other.doc)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they
|
||||
/// agree and `None` when they differ, with whether every one can be aligned.
|
||||
pub type PixelAligned = (Option<bool>, bool);
|
||||
|
||||
@@ -846,6 +846,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
let focus_first = focus_first && !clicked;
|
||||
let spec = spec(&d.kind);
|
||||
// Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to.
|
||||
if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) {
|
||||
modal::over_parent(ctx);
|
||||
}
|
||||
if let Some(window) = spec.window {
|
||||
return window(app, ctx);
|
||||
}
|
||||
@@ -888,14 +892,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if focus_first {
|
||||
ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true));
|
||||
}
|
||||
// When the dialog is taller than the window, its body scrolls, and the heading and the
|
||||
// buttons stay in view.
|
||||
if let Some(body) = spec.body_with_actions {
|
||||
match body(app, ui, &mut d) {
|
||||
match modal::body_rows(ui, |ui| body(app, ui, &mut d)) {
|
||||
DialogAction::None => {}
|
||||
DialogAction::Confirm => ok = true,
|
||||
DialogAction::Cancel => cancel = true,
|
||||
}
|
||||
} else {
|
||||
cancel = (spec.body)(app, ui, &mut d);
|
||||
cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d));
|
||||
}
|
||||
// Taken (the flag is gone): done. Still there (the window's measuring frame): next frame.
|
||||
if focus_first && ui.data_mut(|m| m.remove_temp::<bool>(widgets::dialog_focus_flag())).is_none() {
|
||||
@@ -1076,6 +1082,9 @@ mod tests_perspective;
|
||||
#[cfg(test)]
|
||||
mod tests_modal;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_scroll;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_rectangular_grid;
|
||||
|
||||
|
||||
@@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id {
|
||||
/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether
|
||||
/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`).
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
super::modal::fits_itself(ui);
|
||||
let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height());
|
||||
let content = ui.ctx().data(|m| m.get_temp::<f32>(content_id(ui))).unwrap_or(0.0);
|
||||
let rest = (window - content).max(0.0);
|
||||
|
||||
@@ -384,6 +384,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction {
|
||||
let p = picked(d);
|
||||
let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color);
|
||||
let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color);
|
||||
super::modal::fits_itself(ui);
|
||||
let (side, values_w, button_w, stacked) = layout_size(ui);
|
||||
let field_w = side + SLIDER_GAP + SLIDER_W;
|
||||
let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w };
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::DialogSpec;
|
||||
use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets};
|
||||
use egui::{RichText, Ui};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::dimension::DimensionOptions;
|
||||
use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions};
|
||||
|
||||
pub const KIND: &str = "dimensionOptions";
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
@@ -32,6 +32,10 @@ const UNITS: Choices = &[
|
||||
];
|
||||
const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")];
|
||||
const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")];
|
||||
/// The style of each `ARROWS` entry, in the same order.
|
||||
const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None];
|
||||
/// The size of an Arrow Style preview: a line with the head at its right end.
|
||||
const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0);
|
||||
const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")];
|
||||
const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")];
|
||||
|
||||
@@ -69,6 +73,29 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, key: &str, l
|
||||
});
|
||||
changed
|
||||
}
|
||||
/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in
|
||||
/// the open list and in the closed field.
|
||||
fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, id: &str) -> bool {
|
||||
const KEY: &str = "arrowStyle";
|
||||
let mut changed = false;
|
||||
widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| {
|
||||
let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default();
|
||||
let shown = ARROWS.iter().position(|(v, _)| *v == current);
|
||||
let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect();
|
||||
let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| {
|
||||
if let Some(style) = ARROW_STYLES.get(i) {
|
||||
crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink);
|
||||
}
|
||||
};
|
||||
if let Some((value, _)) =
|
||||
widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i))
|
||||
{
|
||||
fields.insert(KEY.into(), json!(value));
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
fn number(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, key: &str, label: &str, range: (f64, f64), suffix: &str) -> bool {
|
||||
let mut changed = false;
|
||||
widgets::label_row(ui, tl!(label), 96.0, |ui| {
|
||||
@@ -160,7 +187,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
color(ui, f, "lineColor");
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
choose(ui, f, "arrowStyle", "Arrow Style:", ARROWS);
|
||||
arrow_style(ui, f, "arrowStyle");
|
||||
number(ui, f, "arrowScale", "Arrow Scale:", (1.0, 1000.0), "%");
|
||||
});
|
||||
});
|
||||
@@ -310,7 +337,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
changed |= number(ui, &mut f, "lineWeight", "Line Weight:", (0.1, 100.0), "pt");
|
||||
changed |= color(ui, &mut f, "lineColor");
|
||||
});
|
||||
ui.horizontal(|ui| changed |= choose(ui, &mut f, "arrowStyle", "Arrow Style:", ARROWS));
|
||||
ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle"));
|
||||
ui.horizontal(|ui| {
|
||||
changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt");
|
||||
changed |= color(ui, &mut f, "textColor");
|
||||
@@ -377,4 +404,56 @@ mod tests {
|
||||
assert!(text.contains(label), "{label}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a frame drew a picture (a textured mesh) just before the text `name` on its line.
|
||||
fn picture_before(out: &egui::FullOutput, name: &str) -> bool {
|
||||
fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, pictures: &mut Vec<egui::Rect>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.visual_bounding_rect())),
|
||||
egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => pictures.push(m.calc_bounds()),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, pictures)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (mut texts, mut pictures) = (vec![], vec![]);
|
||||
for c in &out.shapes {
|
||||
collect(&c.shape, &mut texts, &mut pictures);
|
||||
}
|
||||
texts
|
||||
.iter()
|
||||
.filter(|(t, _)| t == name)
|
||||
.any(|(_, r)| pictures.iter().any(|p| p.max.x <= r.min.x + 1.0 && r.min.x - p.max.x < 16.0 && p.min.y < r.max.y && p.max.y > r.min.y))
|
||||
}
|
||||
|
||||
/// The frame `f` draws, once its previews are loaded.
|
||||
fn frame(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &mut Ui)) -> egui::FullOutput {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear();
|
||||
ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui))
|
||||
}
|
||||
|
||||
/// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead,
|
||||
/// drawn, before its name (#8049).
|
||||
#[test]
|
||||
fn arrow_style_shows_a_drawn_arrowhead() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("tool.options", json!({"tool":"dimension"})).unwrap();
|
||||
let out = frame(&mut app, |app, ui| super::super::show(app, ui.ctx()));
|
||||
assert!(picture_before(&out, "Filled"), "Tool Options");
|
||||
app.ui.dialog = None;
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowStyle":"tick"}})).unwrap();
|
||||
let out = frame(&mut app, properties_section);
|
||||
assert!(picture_before(&out, "Tick"), "Properties");
|
||||
}
|
||||
|
||||
/// Each Arrow Style entry previews the style its value names.
|
||||
#[test]
|
||||
fn arrow_previews_follow_the_listed_styles() {
|
||||
assert_eq!(ARROWS.len(), ARROW_STYLES.len());
|
||||
for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) {
|
||||
assert_eq!(serde_json::to_value(style).unwrap(), json!(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,9 @@
|
||||
//! window with no title bar that opens centred and moves by dragging its heading (the band from its
|
||||
//! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where
|
||||
//! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows
|
||||
//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons
|
||||
//! stay in view.
|
||||
//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its
|
||||
//! heading and buttons stay in view. A window without such rows that is still too tall or too wide
|
||||
//! for the screen scrolls as a whole on that axis.
|
||||
|
||||
use egui::{Id, Rect, Vec2};
|
||||
|
||||
@@ -35,11 +36,97 @@ pub(crate) fn show_at<R>(ctx: &egui::Context, title: &str, id: Id, initial: Vec2
|
||||
.title_bar(false)
|
||||
.anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial))
|
||||
.frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin)))
|
||||
.show(ctx, add)?;
|
||||
keep_rest(ctx, id, shown.response.rect.height());
|
||||
.show(ctx, |ui| {
|
||||
// Just opened: what scrolls in the window starts at its top, wherever it was left when
|
||||
// the window last closed.
|
||||
if opened(ctx, id) {
|
||||
ctx.data_mut(|m| {
|
||||
m.insert_temp(id.with(TOP_ROWS_KEY), true);
|
||||
m.insert_temp(id.with(TOP_WHOLE_KEY), true);
|
||||
});
|
||||
}
|
||||
// A window whose contents are wider than the screen has room for, or taller without
|
||||
// rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis,
|
||||
// so none of it is out of reach. The contents keep their ids whether the window scrolls
|
||||
// or not, so a field being edited keeps its text when that changes.
|
||||
let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default();
|
||||
let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents"));
|
||||
let (r, contents) = if wide || tall {
|
||||
let room = whole_room(ctx, margin);
|
||||
let mut area = egui::ScrollArea::new([wide, tall]);
|
||||
if ctx.data_mut(|m| m.remove_temp::<bool>(id.with(TOP_WHOLE_KEY))).is_some() {
|
||||
area = area.scroll_offset(Vec2::ZERO);
|
||||
}
|
||||
let out = area
|
||||
.id_salt("modal-whole")
|
||||
.max_width(room.x)
|
||||
.max_height(room.y)
|
||||
.min_scrolled_width(room.x)
|
||||
.min_scrolled_height(room.y)
|
||||
.show(ui, |ui| ui.scope_builder(scope, add).inner);
|
||||
(out.inner, out.content_size)
|
||||
} else {
|
||||
let r = ui.scope_builder(scope, add).inner;
|
||||
(r, ui.min_rect().size())
|
||||
};
|
||||
ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents));
|
||||
r
|
||||
})?;
|
||||
keep_rest(ctx, id, shown.response.rect.height(), margin);
|
||||
shown.inner
|
||||
}
|
||||
|
||||
/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before,
|
||||
/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard
|
||||
/// Shortcuts). The window under it keeps where it was scrolled to.
|
||||
pub(crate) fn over_parent(ctx: &egui::Context) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass));
|
||||
}
|
||||
|
||||
/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before,
|
||||
/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]).
|
||||
fn opened(ctx: &egui::Context, id: Id) -> bool {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|m| {
|
||||
// The windows drawn in this pass so far and in the pass before.
|
||||
let (at, now, prev) = m.get_temp::<(u64, Vec<Id>, Vec<Id>)>(Id::unique(LAST_KEY)).unwrap_or_default();
|
||||
let (mut now, prev) = if at == pass {
|
||||
(now, prev)
|
||||
} else if at.saturating_add(1) == pass {
|
||||
(vec![], now)
|
||||
} else {
|
||||
(vec![], vec![])
|
||||
};
|
||||
let before: Vec<Id> = prev.iter().copied().filter(|&other| other != id).collect();
|
||||
now.push(id);
|
||||
m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev));
|
||||
let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass);
|
||||
if last != u64::MAX && last.saturating_add(1) >= pass {
|
||||
return false;
|
||||
}
|
||||
// Shown again as the window opened over it closed.
|
||||
if before.iter().any(|over| m.get_temp::<Id>(over.with(HOLDS_KEY)) == Some(id)) {
|
||||
return false;
|
||||
}
|
||||
// Opened over the window drawn last in the pass before, it holds that one; otherwise none.
|
||||
match before.last().copied().filter(|_| m.get_temp::<u64>(Id::unique(OVER_KEY)) == Some(pass)) {
|
||||
Some(under) => {
|
||||
m.insert_temp(id.with(HOLDS_KEY), under);
|
||||
}
|
||||
None => {
|
||||
m.remove::<Id>(id.with(HOLDS_KEY));
|
||||
}
|
||||
}
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// The room for the contents of a modal window with `margin` inside its frame.
|
||||
fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 {
|
||||
(ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO)
|
||||
}
|
||||
|
||||
/// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of
|
||||
/// the app would get.
|
||||
pub(crate) fn backdrop() -> egui::LayerId {
|
||||
@@ -86,34 +173,158 @@ pub(super) fn handle(id: Id) -> Id {
|
||||
id.with("modal-drag")
|
||||
}
|
||||
|
||||
/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall
|
||||
/// the rest of it was when last drawn.
|
||||
/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this
|
||||
/// frame, and how tall the rest of it was when last drawn.
|
||||
const ROWS_KEY: &str = "modal-rows";
|
||||
const REST_KEY: &str = "modal-rest";
|
||||
/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to
|
||||
/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`).
|
||||
const OWN_ROWS_KEY: &str = "modal-own-rows";
|
||||
const OWN_BEFORE_KEY: &str = "modal-own-before";
|
||||
/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame.
|
||||
const BODY_KEY: &str = "modal-body";
|
||||
/// Under a modal window's id: how large its contents would be without scrolling as a whole, this
|
||||
/// frame.
|
||||
const CONTENTS_KEY: &str = "modal-contents";
|
||||
/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on
|
||||
/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`).
|
||||
const TALL_KEY: &str = "modal-tall";
|
||||
const WHOLE_KEY: &str = "modal-whole";
|
||||
/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened,
|
||||
/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so
|
||||
/// they start at the top when they first do.
|
||||
const SHOWN_KEY: &str = "modal-shown";
|
||||
const TOP_ROWS_KEY: &str = "modal-top-rows";
|
||||
const TOP_WHOLE_KEY: &str = "modal-top-whole";
|
||||
/// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass
|
||||
/// and of those drawn in the pass before it (`LAST_KEY`), and the pass
|
||||
/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`).
|
||||
/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`).
|
||||
const LAST_KEY: &str = "modal-last";
|
||||
const OVER_KEY: &str = "modal-over";
|
||||
const HOLDS_KEY: &str = "modal-holds";
|
||||
|
||||
/// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window
|
||||
/// would be taller than the screen. Their height is the screen's less the rest of the window as
|
||||
/// last drawn (a frame late, as only the drawn window knows its height).
|
||||
/// Rows that fit are as tall as they are.
|
||||
pub(crate) fn scrolled_rows<R>(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let id = ui.layer_id().id;
|
||||
let rest = ui.ctx().data(|m| m.get_temp::<f32>(id.with(REST_KEY))).unwrap_or(0.0);
|
||||
let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0);
|
||||
// As tall as the room at once: by itself a scroll area grows a frame at a time with the window.
|
||||
let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner);
|
||||
ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height()));
|
||||
rows.inner
|
||||
fits_itself(ui);
|
||||
let (r, drawn, _) = rows(ui, salt, true, add);
|
||||
ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn));
|
||||
r
|
||||
}
|
||||
|
||||
/// After modal window `id` is drawn `height` tall: keep the height of all of it but its
|
||||
/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just
|
||||
/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit
|
||||
/// without waiting for input.
|
||||
fn keep_rest(ctx: &egui::Context, id: Id, height: f32) {
|
||||
let Some(rows) = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(ROWS_KEY))) else { return };
|
||||
let rest = (height - rows).max(0.0);
|
||||
let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest));
|
||||
if (used - rest).abs() > 0.5 {
|
||||
/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing
|
||||
/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window
|
||||
/// scroll them again.
|
||||
pub(crate) fn fits_itself(ui: &egui::Ui) {
|
||||
ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true));
|
||||
}
|
||||
|
||||
/// The body of a shared dialog window. While the window would be taller than the screen has room
|
||||
/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view;
|
||||
/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is.
|
||||
pub(crate) fn body_rows<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let id = ui.layer_id().id;
|
||||
let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add);
|
||||
if !ui.ctx().data(|m| m.get_temp::<bool>(id.with(OWN_ROWS_KEY))).unwrap_or(false) {
|
||||
ui.ctx().data_mut(|m| {
|
||||
m.insert_temp(id.with(ROWS_KEY), drawn);
|
||||
m.insert_temp(id.with(BODY_KEY), body);
|
||||
});
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Whether the [`body_rows`] of modal window `id` scroll in this frame.
|
||||
fn body_scrolls(ctx: &egui::Context, id: Id) -> bool {
|
||||
let own = ctx.data(|m| m.get_temp::<bool>(id.with(OWN_BEFORE_KEY))).unwrap_or(false);
|
||||
!own && ctx.data(|m| m.get_temp::<bool>(id.with(TALL_KEY))).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn.
|
||||
pub(crate) fn body_view(ui: &egui::Ui) -> Option<f32> {
|
||||
let id = ui.layer_id().id;
|
||||
body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id))
|
||||
}
|
||||
|
||||
/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on
|
||||
/// which axes ([wide, tall]) the window scrolls as a whole.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option<f32>, [bool; 2]) {
|
||||
let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id));
|
||||
(body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`]
|
||||
/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so
|
||||
/// the list and its bar can be scrolled into view whole.
|
||||
pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 {
|
||||
body_view(ui).map_or(height, |view| view.min(height))
|
||||
}
|
||||
|
||||
/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the
|
||||
/// window as last drawn.
|
||||
fn rows_room(ctx: &egui::Context, id: Id) -> f32 {
|
||||
let rest = ctx.data(|m| m.get_temp::<f32>(id.with(REST_KEY))).unwrap_or(0.0);
|
||||
(ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0)
|
||||
}
|
||||
|
||||
/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their
|
||||
/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling.
|
||||
/// Rows that do not `scroll` are as tall as they are, with no
|
||||
/// scroll area (which would take the scroll requests of their fields from the window's). The rows
|
||||
/// keep their ids either way, so a field being edited keeps its text when they start or stop
|
||||
/// scrolling.
|
||||
fn rows<R>(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) {
|
||||
let id = ui.layer_id().id;
|
||||
let room = rows_room(ui.ctx(), id);
|
||||
let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows"));
|
||||
if !scroll {
|
||||
let rows = ui.scope_builder(scope, add);
|
||||
let height = rows.response.rect.height();
|
||||
return (rows.inner, height, height);
|
||||
}
|
||||
// As tall as the room at once: by itself a scroll area grows a frame at a time with the window.
|
||||
let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room);
|
||||
if ui.ctx().data_mut(|m| m.remove_temp::<bool>(id.with(TOP_ROWS_KEY))).is_some() {
|
||||
area = area.scroll_offset(Vec2::ZERO);
|
||||
}
|
||||
let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner));
|
||||
(rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y)
|
||||
}
|
||||
|
||||
/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height
|
||||
/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different
|
||||
/// one (the window just opened, or what is around them changed), the next frame is drawn at once,
|
||||
/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll
|
||||
/// while the window would be taller than the screen has room for without them scrolling; a window
|
||||
/// without rows that scroll scrolls as a whole while its contents would be taller than the room,
|
||||
/// and any window scrolls sideways while its contents would be wider.
|
||||
fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) {
|
||||
let rows = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(ROWS_KEY)));
|
||||
let body = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(BODY_KEY)));
|
||||
let contents = ctx.data_mut(|m| m.remove_temp::<Vec2>(id.with(CONTENTS_KEY))).unwrap_or_default();
|
||||
let own = ctx.data_mut(|m| m.remove_temp::<bool>(id.with(OWN_ROWS_KEY))).unwrap_or(false);
|
||||
ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own));
|
||||
let room = whole_room(ctx, margin);
|
||||
let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP;
|
||||
let tall = match (rows, body) {
|
||||
(Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5,
|
||||
_ => false,
|
||||
};
|
||||
// A window that fits itself to the screen's height can still be too wide for it.
|
||||
let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5];
|
||||
let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall));
|
||||
let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole));
|
||||
let mut repaint = tall != was_tall || whole != was_whole;
|
||||
if let Some(rows) = rows {
|
||||
let rest = (height - rows).max(0.0);
|
||||
let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest));
|
||||
repaint |= (used - rest).abs() > 0.5;
|
||||
}
|
||||
if repaint {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
@@ -159,4 +370,159 @@ mod tests {
|
||||
// Larger than the screen: its top left stays in view.
|
||||
assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0));
|
||||
}
|
||||
|
||||
/// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal
|
||||
/// windows named in `open` open, in that order: the first a heading and 60 rows, in
|
||||
/// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is
|
||||
/// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in
|
||||
/// the last frame (inside the screen and its clip).
|
||||
fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec<egui::Event>, time: &mut f64, frames: usize) -> bool {
|
||||
let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0));
|
||||
let add = |ui: &mut egui::Ui| {
|
||||
for i in 0..60 {
|
||||
ui.label(format!("Row {i}"));
|
||||
}
|
||||
};
|
||||
let mut events = Some(events);
|
||||
let mut seen = false;
|
||||
for _ in 0..frames {
|
||||
*time += 1.0 / 60.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
for (i, &name) in open.iter().enumerate() {
|
||||
if name.starts_with("over ") {
|
||||
over_parent(ui.ctx());
|
||||
}
|
||||
show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| {
|
||||
heading(ui, "Top");
|
||||
if i > 0 {
|
||||
ui.label("Alert");
|
||||
} else if in_rows {
|
||||
scrolled_rows(ui, "rows", add);
|
||||
} else {
|
||||
add(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
seen = out.shapes.iter().any(|c| match &c.shape {
|
||||
egui::Shape::Text(t) => {
|
||||
let r = t.visual_bounding_rect();
|
||||
t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// A wheel turn far down, at the middle of the 400×300 screen.
|
||||
fn wheel_down() -> Vec<egui::Event> {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(0.0, -3000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_scrolled_opens_again_at_its_top() {
|
||||
for in_rows in [false, true] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let mut time = 0.0;
|
||||
assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top");
|
||||
assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away");
|
||||
first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2);
|
||||
assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() {
|
||||
// As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it
|
||||
// did not close. A window that another replaced did close. Either may have shown an alert
|
||||
// of its own, drawn after it in the same passes.
|
||||
let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)];
|
||||
let mut wrong = vec![];
|
||||
for in_rows in [false, true] {
|
||||
for (other, kept) in others {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let mut time = 0.0;
|
||||
first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4);
|
||||
if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) {
|
||||
wrong.push(format!("rows {in_rows}: the wheel does not scroll A"));
|
||||
}
|
||||
if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) {
|
||||
wrong.push(format!("rows {in_rows}: {other:?} does not open at its top"));
|
||||
}
|
||||
if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept {
|
||||
wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" }));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() {
|
||||
// A field's edit state and the keyboard focus are kept under its id, so typing goes on into
|
||||
// the same field when the screen's height changes whether the body or the window scrolls.
|
||||
let mut wrong = vec![];
|
||||
for in_body in [false, true] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let window = Id::unique("modal-field-id-test");
|
||||
let mut text = String::from("12");
|
||||
let mut time = 0.0;
|
||||
let mut field = None;
|
||||
let mut focus_given = false;
|
||||
let mut seen = vec![];
|
||||
for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] {
|
||||
let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height));
|
||||
for i in 0..4 {
|
||||
time += 1.0 / 60.0;
|
||||
// Typed once the window has settled at this height.
|
||||
let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] };
|
||||
let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
show(ui.ctx(), "Test", window, 0.0, 8, |ui| {
|
||||
heading(ui, "Top");
|
||||
let mut add = |ui: &mut egui::Ui| {
|
||||
let r = ui.text_edit_singleline(&mut text);
|
||||
for i in 0..30 {
|
||||
ui.label(format!("Row {i}"));
|
||||
}
|
||||
r.id
|
||||
};
|
||||
field = Some(if in_body { body_rows(ui, add) } else { add(ui) });
|
||||
});
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
// The field is given the focus once, after the first frame; a resize that took it
|
||||
// away would leave the keys typed after it untaken.
|
||||
if let Some(id) = field.filter(|_| !focus_given) {
|
||||
ctx.memory_mut(|m| m.request_focus(id));
|
||||
focus_given = true;
|
||||
}
|
||||
}
|
||||
let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) };
|
||||
let scrolls = ctx.data(|m| m.get_temp::<bool>(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1]));
|
||||
seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some()));
|
||||
}
|
||||
let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)];
|
||||
let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect();
|
||||
if seen != want {
|
||||
wrong.push((in_body, seen));
|
||||
}
|
||||
}
|
||||
// Only the short screen scrolls, and the field keeps its focus and takes each key.
|
||||
assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong");
|
||||
}
|
||||
}
|
||||
@@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id {
|
||||
/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether
|
||||
/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`).
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
super::modal::fits_itself(ui);
|
||||
let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height());
|
||||
let content = ui.ctx().data(|m| m.get_temp::<f32>(content_id(ui))).unwrap_or(0.0);
|
||||
let rest = (window - content).max(0.0);
|
||||
|
||||
@@ -251,7 +251,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(500.0);
|
||||
ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong));
|
||||
egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
let list_h = super::modal::list_height(ui, 360.0);
|
||||
egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
"Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d),
|
||||
"Output" => output(ui, d, &preview),
|
||||
"Graphics" => graphics(ui, d),
|
||||
|
||||
@@ -55,6 +55,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
|
||||
/// The preview area (panes and their captions) and the settings column.
|
||||
const PREVIEW_W: f32 = 620.0;
|
||||
/// The narrowest the panes get in a narrow window.
|
||||
const MIN_PREVIEW_W: f32 = 240.0;
|
||||
const PREVIEW_H: f32 = 470.0;
|
||||
const SIDE_W: f32 = 296.0;
|
||||
const GAP: f32 = 16.0;
|
||||
@@ -535,10 +537,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
let settings = settings_of(app, d);
|
||||
let mut browser = false;
|
||||
ui.horizontal_top(|ui| {
|
||||
// In a window too narrow for both, the panes are narrower, so the settings beside them and the
|
||||
// buttons below stay in view. The room is the screen's (the window's own width follows what it
|
||||
// drew last), less a column for the bar of the body while it scrolls; the settings column is as
|
||||
// wide as it was drawn last.
|
||||
let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 };
|
||||
let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar;
|
||||
let rest_id = egui::Id::unique("save-for-web-beside-panes");
|
||||
let rest = ui.ctx().data(|m| m.get_temp::<f32>(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W);
|
||||
let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W);
|
||||
let row = ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(PREVIEW_W);
|
||||
browser = preview_area(app, ui, d, &settings);
|
||||
ui.set_width(preview_w);
|
||||
browser = preview_area(app, ui, d, &settings, preview_w);
|
||||
});
|
||||
ui.add_space(GAP);
|
||||
ui.vertical(|ui| {
|
||||
@@ -546,6 +557,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
side(app, ui, d, settings.as_ref().ok());
|
||||
});
|
||||
});
|
||||
let drawn = row.response.rect.width() - preview_w;
|
||||
if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
optimize_on_enter(ui.ctx(), d);
|
||||
if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) {
|
||||
app.status(e);
|
||||
@@ -553,16 +568,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was
|
||||
/// clicked.
|
||||
fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result<WebSettings, String>) -> bool {
|
||||
/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in
|
||||
/// Browser was clicked.
|
||||
fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result<WebSettings, String>, width: f32) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2);
|
||||
if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) {
|
||||
d.fields.insert("__view".into(), json!(VIEWS[i]));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag());
|
||||
let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag());
|
||||
let pan_id = egui::Id::unique("save-for-web-pan");
|
||||
let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default();
|
||||
if resp.dragged() {
|
||||
@@ -607,6 +622,17 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
let mut browser = false;
|
||||
// Preview in Browser goes on a row of its own when the panes are too narrow for it beside the
|
||||
// two lists (its width as `widgets::secondary_button` draws it).
|
||||
let label = tl!("Preview in Browser");
|
||||
let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0);
|
||||
let mut beside = false;
|
||||
let mut button = |ui: &mut egui::Ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, label));
|
||||
browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked();
|
||||
});
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
let z = ZOOMS.iter().position(|z| *z == d.str("__zoom")).unwrap_or(2);
|
||||
let zoom = ui.name_inputs(tl!("Zoom"), |ui| widgets::dropdown(ui, "sfw-zoom", ZOOM_LABELS[z], &ZOOM_LABELS, 110.0));
|
||||
@@ -623,11 +649,15 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set
|
||||
{
|
||||
d.fields.insert("__kbps".into(), json!(s));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Preview in Browser")));
|
||||
browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked();
|
||||
});
|
||||
beside = ui.available_width() >= button_w;
|
||||
if beside {
|
||||
button(ui);
|
||||
}
|
||||
});
|
||||
if !beside {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(button);
|
||||
}
|
||||
browser
|
||||
}
|
||||
|
||||
@@ -732,7 +762,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&
|
||||
presets_row(app, ui, d, s);
|
||||
optimize_rows(ui, d, s, &art_key(app));
|
||||
widgets::divider(ui);
|
||||
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0);
|
||||
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| {
|
||||
let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| {
|
||||
form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options);
|
||||
};
|
||||
|
||||
@@ -429,7 +429,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(500.0);
|
||||
ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong));
|
||||
egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
let list_h = super::modal::list_height(ui, 360.0);
|
||||
egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
"Compression" => compression(ui, d),
|
||||
"Marks and Bleeds" => marks_and_bleeds(app, ui, d),
|
||||
"Output" => output(ui, d),
|
||||
|
||||
@@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open);
|
||||
let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0);
|
||||
crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| {
|
||||
crate::dialogs::modal::fits_itself(ui);
|
||||
ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0);
|
||||
crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set"));
|
||||
ui.add_space(10.0);
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` |
|
||||
//! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid;
|
||||
//! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an
|
||||
//! existing symbol). Help:
|
||||
//! existing symbol), `__keepArt` (true when a new symbol leaves the selection as ordinary art).
|
||||
//! Help:
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html>.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -69,15 +70,23 @@ const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic"
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM };
|
||||
|
||||
/// Open Symbol Options to name a new symbol made from the selection.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
/// Open Symbol Options to name a new symbol made from the selection. With `keep_art`, OK leaves
|
||||
/// the selection as ordinary art instead of replacing it with an instance.
|
||||
pub fn open(app: &mut VectorcraftApp, keep_art: bool) -> Result<Value, String> {
|
||||
let st = app.session.active().ok_or("no document open")?;
|
||||
if st.selection.is_empty() {
|
||||
return Err("nothing selected".into());
|
||||
}
|
||||
let name = st.doc.unique_symbol_name("New Symbol");
|
||||
let mut fields =
|
||||
json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false });
|
||||
let mut fields = json!({
|
||||
"name": name,
|
||||
"exportType": "movieClip",
|
||||
"type": "dynamic",
|
||||
"registration": 4,
|
||||
"alignToPixelGrid": false,
|
||||
"__edit": false,
|
||||
"__keepArt": keep_art,
|
||||
});
|
||||
if let Some(o) = fields.as_object_mut() {
|
||||
o.extend(slice_fields(None));
|
||||
}
|
||||
@@ -193,6 +202,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
} else {
|
||||
let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel });
|
||||
merge(&mut params, slice_params(d));
|
||||
if d.bool("__keepArt") {
|
||||
params["keepArt"] = json!(true);
|
||||
}
|
||||
app.run("symbol.new", params)
|
||||
};
|
||||
if r.is_ok() {
|
||||
|
||||
@@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId
|
||||
egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None })
|
||||
}
|
||||
|
||||
/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out.
|
||||
/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out.
|
||||
fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) {
|
||||
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
|
||||
screen.run(app, vec![]);
|
||||
let out = screen.run(app, vec![]);
|
||||
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
|
||||
let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)));
|
||||
// W is left of H on their row (the tree lists its nodes in no particular order).
|
||||
let w = nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)))
|
||||
.min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0)));
|
||||
screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]);
|
||||
screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]);
|
||||
screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]);
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
//! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of
|
||||
//! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests
|
||||
//! can find it.
|
||||
|
||||
use egui::{Pos2, Rect, Shape, vec2};
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
type Open = fn(&mut VectorcraftApp);
|
||||
|
||||
/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls
|
||||
/// ([`modal::scrolling`]).
|
||||
struct Shown {
|
||||
shapes: Vec<egui::epaint::ClippedShape>,
|
||||
window: Rect,
|
||||
body: Option<f32>,
|
||||
whole: [bool; 2],
|
||||
}
|
||||
|
||||
/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away
|
||||
/// from the dialog), and draw it until it settles. With `scroll`, then scroll far down and right
|
||||
/// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists
|
||||
/// inside it) and draw it until it settles again.
|
||||
fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
ctx.global_style_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid());
|
||||
open(&mut app);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, size);
|
||||
let window = |ctx: &egui::Context| {
|
||||
ctx.memory(|m| {
|
||||
m.areas()
|
||||
.visible_layer_ids()
|
||||
.into_iter()
|
||||
.filter(|l| l.order == egui::Order::Foreground)
|
||||
.filter_map(|l| Some((l.id, m.area_rect(l.id)?)))
|
||||
.max_by(|a, b| a.1.area().total_cmp(&b.1.area()))
|
||||
})
|
||||
.unwrap_or((egui::Id::NULL, Rect::NOTHING))
|
||||
};
|
||||
let mut time = 0.0;
|
||||
let mut frames = |app: &mut VectorcraftApp, first: Vec<egui::Event>| {
|
||||
let mut first = Some(first);
|
||||
let mut shapes = vec![];
|
||||
for _ in 0..12 {
|
||||
time += 1.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: first.take().unwrap_or_default(), time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
shapes = std::mem::take(&mut out.shapes);
|
||||
}
|
||||
shapes
|
||||
};
|
||||
let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]);
|
||||
if scroll {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(-5000.0, -5000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
let (id, w) = window(&ctx);
|
||||
let (body, whole) = modal::scrolling(&ctx, id);
|
||||
let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole };
|
||||
// On the window's upright bar, else on its body's bar, else on its sideways bar, else at
|
||||
// its right edge.
|
||||
let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width());
|
||||
let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center());
|
||||
shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]);
|
||||
}
|
||||
let (id, window) = window(&ctx);
|
||||
let (body, whole) = modal::scrolling(&ctx, id);
|
||||
Shown { shapes, window, body, whole }
|
||||
}
|
||||
|
||||
/// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or
|
||||
/// (`sideways`) flat, inside the dialog window; with `seen`, only those inside their clip.
|
||||
fn bars(shown: &Shown, sideways: bool, seen: bool) -> Vec<Rect> {
|
||||
fn walk(s: &Shape, clip: Rect, sideways: bool, seen: bool, out: &mut Vec<Rect>) {
|
||||
match s {
|
||||
Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => {
|
||||
let (across, along) = if sideways { (r.rect.height(), r.rect.width()) } else { (r.rect.width(), r.rect.height()) };
|
||||
if (4.0..=10.0).contains(&across) && along > 12.0 && (!seen || clip.contains_rect(r.rect)) {
|
||||
out.push(r.rect);
|
||||
}
|
||||
}
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, sideways, seen, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, sideways, seen, &mut out));
|
||||
out.retain(|r| shown.window.expand(0.5).contains_rect(*r));
|
||||
out
|
||||
}
|
||||
|
||||
/// The bar of a shared dialog's scrolling body: the rightmost upright bar as tall as the body is
|
||||
/// drawn (a list inside the body draws its bar further left).
|
||||
fn body_bar(shown: &Shown) -> Option<Rect> {
|
||||
let view = shown.body?;
|
||||
bars(shown, false, true).into_iter().filter(|r| (r.height() - view).abs() <= 1.0).max_by(|a, b| a.right().total_cmp(&b.right()))
|
||||
}
|
||||
|
||||
/// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that
|
||||
/// runs most of the window's height (lists inside it are shorter).
|
||||
fn whole_bar(shown: &Shown) -> Option<Rect> {
|
||||
let w = shown.window;
|
||||
bars(shown, false, true)
|
||||
.into_iter()
|
||||
.filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height())
|
||||
.max_by(|a, b| a.height().total_cmp(&b.height()))
|
||||
}
|
||||
|
||||
/// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and
|
||||
/// its clip).
|
||||
fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> {
|
||||
texts(shown)
|
||||
.into_iter()
|
||||
.filter(|(s, ..)| labels.contains(&s.as_str()))
|
||||
.map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() {
|
||||
let opens: [(&str, Open, &[&str]); 7] = [
|
||||
("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]),
|
||||
("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]),
|
||||
("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]),
|
||||
(
|
||||
"Save PDF",
|
||||
|app| {
|
||||
save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap();
|
||||
},
|
||||
&["Cancel"],
|
||||
),
|
||||
(
|
||||
"Save for Web",
|
||||
|app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
},
|
||||
&["Cancel", "Done"],
|
||||
),
|
||||
("Export for Screens", export_for_screens::open, &["Cancel"]),
|
||||
(
|
||||
"Print",
|
||||
|app| {
|
||||
print::open(app).unwrap();
|
||||
},
|
||||
&["Cancel", "Done"],
|
||||
),
|
||||
];
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0));
|
||||
for (name, open, labels) in opens {
|
||||
let tall = show_in(open, vec2(1280.0, 900.0), false);
|
||||
assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window);
|
||||
assert_eq!((tall.body, tall.whole), (None, [false; 2]), "{name}: in a tall window nothing scrolls");
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window);
|
||||
let found = buttons(&shown, screen, labels);
|
||||
assert_eq!(found.len(), labels.len(), "{name}: {found:?}");
|
||||
assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}");
|
||||
assert_eq!(shown.whole, [false; 2], "{name}: the window does not scroll as a whole");
|
||||
let bar = body_bar(&shown);
|
||||
assert!(bar.is_some(), "{name}: the body scrolls ({:?}) and its bar is drawn: {:?}", shown.body, bars(&shown, false, true));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_in_a_scrolling_body_is_no_taller_than_the_body() {
|
||||
// The settings of Save for Web and the sections of Print and Save PDF scroll in lists of their
|
||||
// own; in a short window those lists are no taller than the body shows, so each list and its
|
||||
// bar can be scrolled into view whole.
|
||||
let opens: [(&str, Open); 3] = [
|
||||
("Save for Web", |app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
}),
|
||||
("Print", |app| {
|
||||
print::open(app).unwrap();
|
||||
if let Some(d) = app.ui.dialog.as_mut() {
|
||||
d.fields.insert("__section".into(), json!("Marks and Bleed"));
|
||||
}
|
||||
}),
|
||||
("Save PDF", |app| {
|
||||
save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap();
|
||||
if let Some(d) = app.ui.dialog.as_mut() {
|
||||
d.fields.insert("__section".into(), json!("Marks and Bleeds"));
|
||||
}
|
||||
}),
|
||||
];
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 400.0));
|
||||
let mut wrong = vec![];
|
||||
for (name, open) in opens {
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
let Some(body) = body_bar(&shown) else {
|
||||
wrong.push(format!("{name}: the body does not scroll ({:?}): {:?}", shown.body, bars(&shown, false, false)));
|
||||
continue;
|
||||
};
|
||||
// The tracks of the lists' bars, seen or not: left of the body's bar and inside the window
|
||||
// (a list taller than the body runs past the window's bottom).
|
||||
let lists: Vec<Rect> = bars(&shown, false, false).into_iter().filter(|r| r.right() < body.left()).collect();
|
||||
let tallest = lists.iter().map(|r| r.height()).fold(0.0, f32::max);
|
||||
if tallest == 0.0 || tallest > body.height() + 0.5 {
|
||||
wrong.push(format!("{name}: no list bar no taller than the body ({}): {:?}", body.height(), bars(&shown, false, false)));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() {
|
||||
let open: Open = |app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
};
|
||||
// The app window's smallest size, 800 by 500 pixels, at a UI scale of 100%, 110% and 125%.
|
||||
let mut wrong = vec![];
|
||||
for size in [vec2(800.0, 500.0), vec2(727.0, 454.0), vec2(640.0, 400.0)] {
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, size);
|
||||
let shown = show_in(open, size, false);
|
||||
let labels = ["Format:", "Optimize to File Size…", "Cancel", "Done"];
|
||||
let found = buttons(&shown, screen, &labels);
|
||||
if !screen.contains_rect(shown.window) || found.len() != labels.len() || !found.iter().all(|(_, seen)| *seen) {
|
||||
wrong.push(format!("{size:?}: the dialog ({:?}) leaves its settings and buttons in view: {found:?}", shown.window));
|
||||
}
|
||||
if body_bar(&shown).is_none() || shown.whole != [false; 2] {
|
||||
wrong.push(format!("{size:?}: only the body scrolls ({:?}, {:?})", shown.body, shown.whole));
|
||||
}
|
||||
// The controls under the narrower panes stay in their column, left of the settings.
|
||||
let controls = text_rects(&shown, "Preview in Browser").first().map(|r| r.right());
|
||||
let settings = text_rects(&shown, "Format:").first().map(|r| r.left());
|
||||
if !matches!((controls, settings), (Some(c), Some(s)) if c < s) {
|
||||
wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})"));
|
||||
}
|
||||
// Preview in Browser is right of the download speed list or on a row below it, not over it.
|
||||
let button = text_rects(&shown, "Preview in Browser").first().copied();
|
||||
let speed = text_rects(&shown, "56.6 Kbps").first().copied();
|
||||
if !matches!((button, speed), (Some(b), Some(s)) if b.left() > s.right() + 16.0 || b.top() > s.bottom() + 8.0) {
|
||||
wrong.push(format!("{size:?}: Preview in Browser ({button:?}) clears the download speed list ({speed:?})"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// The rectangles of the texts `label` the dialog drew.
|
||||
fn text_rects(shown: &Shown, label: &str) -> Vec<Rect> {
|
||||
fn walk(s: &Shape, label: &str, out: &mut Vec<Rect>) {
|
||||
match s {
|
||||
Shape::Text(t) if t.galley.text() == label => out.push(t.visual_bounding_rect()),
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, label, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, label, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_too_large_for_the_screen_scrolls_as_a_whole() {
|
||||
let opens: [(&str, Open, &[&str]); 4] = [
|
||||
("Preferences", |app| crate::prefs_dialog::open(app, None), &["OK", "Cancel"]),
|
||||
("Keyboard Shortcuts", crate::shortcut_editor::open, &["OK", "Cancel"]),
|
||||
("New Document", new_document::open, &["Create", "Close"]),
|
||||
("Find Font", crate::find_font::open, &["Done"]),
|
||||
];
|
||||
// The app window's smallest size.
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
|
||||
for (name, open, labels) in opens {
|
||||
let tall = show_in(open, vec2(1280.0, 900.0), false);
|
||||
assert!(
|
||||
tall.window.height() > screen.height() || tall.window.width() > screen.width(),
|
||||
"{name}: the dialog is larger than the small window ({:?})",
|
||||
tall.window
|
||||
);
|
||||
assert_eq!(tall.whole, [false; 2], "{name}: in a large window the dialog does not scroll as a whole");
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window);
|
||||
assert!(shown.whole[1], "{name}: the dialog scrolls as a whole");
|
||||
assert!(whole_bar(&shown).is_some(), "{name}: the window's bar is drawn: {:?}", bars(&shown, false, true));
|
||||
// The buttons can sit outside the part in view; each is in view at the top or scrolled to
|
||||
// the end.
|
||||
let scrolled = show_in(open, screen.size(), true);
|
||||
let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels));
|
||||
for label in labels {
|
||||
let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen);
|
||||
assert!(seen(&top) || seen(&end), "{name}: {label} can be scrolled into view: {top:?} {end:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() {
|
||||
// Scrolled down in the smallest window, Keyboard Shortcuts is where it was left when Import
|
||||
// Shortcut Set, opened over it, is canceled; closed and opened again, it starts at its top.
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
|
||||
let mut time = 0.0;
|
||||
// Draws 12 frames, the first with `events`; returns whether the heading can be seen.
|
||||
let mut heading_seen = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut events = Some(events);
|
||||
let mut seen = false;
|
||||
for _ in 0..12 {
|
||||
time += 1.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] };
|
||||
seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen);
|
||||
}
|
||||
seen
|
||||
};
|
||||
let wheel = |at: Pos2| {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -5000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
vec![egui::Event::PointerMoved(at), wheel]
|
||||
};
|
||||
crate::shortcut_editor::open(&mut app);
|
||||
assert!(heading_seen(&mut app, vec![]), "Keyboard Shortcuts opens at its top");
|
||||
// On the window's bar, inside its 20 pt margin.
|
||||
let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-shortcuts"))).unwrap_or(screen);
|
||||
assert!(!heading_seen(&mut app, wheel(egui::pos2(window.right() - 23.0, window.center().y))), "the wheel scrolls the heading away");
|
||||
let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n}\n";
|
||||
crate::io::open_bytes(&mut app, "Keys.kys", kys.as_bytes(), None).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(shortcut_import::KIND));
|
||||
heading_seen(&mut app, vec![]);
|
||||
cancel(&mut app);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "Cancel shows Keyboard Shortcuts again");
|
||||
assert!(!heading_seen(&mut app, vec![]), "shown again, Keyboard Shortcuts is where it was scrolled to");
|
||||
cancel(&mut app);
|
||||
heading_seen(&mut app, vec![]);
|
||||
crate::shortcut_editor::open(&mut app);
|
||||
assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top");
|
||||
}
|
||||
|
||||
/// Open Import Shortcut Set on a set of two shortcuts.
|
||||
fn open_shortcut_import(app: &mut VectorcraftApp) {
|
||||
let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n";
|
||||
crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() {
|
||||
// Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An
|
||||
// 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt.
|
||||
let wide = show_in(open_shortcut_import, vec2(1280.0, 900.0), false);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0));
|
||||
assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window);
|
||||
assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll");
|
||||
let shown = show_in(open_shortcut_import, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window);
|
||||
assert_eq!(shown.whole, [true, false], "it scrolls sideways only");
|
||||
let sideways: Vec<Rect> = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect();
|
||||
assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() {
|
||||
// In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right
|
||||
// edge, the text drawn furthest right in a large window can be seen.
|
||||
let opens: [(&str, Open); 3] = [
|
||||
("Import Shortcut Set", open_shortcut_import),
|
||||
("Keyboard Shortcuts", crate::shortcut_editor::open),
|
||||
("Preferences", |app| crate::prefs_dialog::open(app, None)),
|
||||
];
|
||||
let mut wrong = vec![];
|
||||
for (name, open) in opens {
|
||||
let wide = show_in(open, vec2(1600.0, 1000.0), false);
|
||||
let Some((right, _)) = texts(&wide)
|
||||
.into_iter()
|
||||
.filter(|(_, r, _)| wide.window.contains_rect(*r))
|
||||
.map(|(s, r, _)| (s, r.right()))
|
||||
.max_by(|a, b| a.1.total_cmp(&b.1))
|
||||
else {
|
||||
wrong.push(format!("{name}: no text in the large window"));
|
||||
continue;
|
||||
};
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2((0.7 * wide.window.width()).round(), 1000.0));
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
let scrolled = show_in(open, screen.size(), true);
|
||||
// Within 1 pt: a text's drawn box can reach a fraction of a point past the content's edge.
|
||||
let seen =
|
||||
|shown: &Shown| texts(shown).iter().any(|(s, r, clip)| *s == right && screen.contains_rect(*r) && clip.expand(1.0).contains_rect(*r));
|
||||
let sideways = bars(&shown, true, true).into_iter().any(|r| r.width() >= 0.5 * shown.window.width());
|
||||
if !screen.contains_rect(shown.window) || !shown.whole[0] || !sideways || seen(&shown) || !seen(&scrolled) {
|
||||
let at = |shown: &Shown| texts(shown).into_iter().filter(|(s, ..)| *s == right).collect::<Vec<_>>();
|
||||
wrong.push(format!(
|
||||
"{name} in {:?}: window {:?}, scrolls {:?}, sideways bar {sideways}, {right:?} seen at first {} {:?}, scrolled {} {:?}, bars {:?}",
|
||||
screen.size(),
|
||||
shown.window,
|
||||
shown.whole,
|
||||
seen(&shown),
|
||||
at(&shown),
|
||||
seen(&scrolled),
|
||||
at(&scrolled),
|
||||
bars(&shown, true, true)
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// Every text the dialog drew, with its rectangle and its clip.
|
||||
fn texts(shown: &Shown) -> Vec<(String, Rect, Rect)> {
|
||||
fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) {
|
||||
match s {
|
||||
Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)),
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_with_buttons_in_its_body_scrolls_them_with_the_body() {
|
||||
// Check Spelling draws its buttons inside its body: in a window too short for it, the heading
|
||||
// stays in view and the buttons scroll with the body.
|
||||
let open: Open = |app| {
|
||||
check_spelling::open(app).unwrap();
|
||||
};
|
||||
let tall = show_in(open, vec2(1280.0, 900.0), false);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, (0.6 * tall.window.height()).round()));
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
let scrolled = show_in(open, screen.size(), true);
|
||||
let seen = |shown: &Shown, label: &str| buttons(shown, screen, &[label]).iter().any(|(_, seen)| *seen);
|
||||
assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window);
|
||||
assert!(body_bar(&shown).is_some() && shown.whole == [false; 2], "only the body scrolls ({:?}, {:?})", shown.body, shown.whole);
|
||||
assert!(seen(&shown, "Check Spelling") && seen(&scrolled, "Check Spelling"), "the heading stays in view");
|
||||
assert!(!seen(&shown, "Cancel") && seen(&scrolled, "Cancel"), "Cancel is out of view until the body is scrolled down");
|
||||
}
|
||||
@@ -4,10 +4,13 @@
|
||||
//! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). Find In limits Find
|
||||
//! to the active artboard or the selected layers.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::caches::{FindFontCache, FontsKey};
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets;
|
||||
@@ -20,7 +23,7 @@ pub fn open(app: &mut VectorcraftApp) {
|
||||
/// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find
|
||||
/// Fonts).
|
||||
pub fn open_on_missing(app: &mut VectorcraftApp) {
|
||||
let first = fonts(app).iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute")));
|
||||
let first = document_fonts(app, false).0.iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute")));
|
||||
open_at(app, first.unwrap_or(0));
|
||||
}
|
||||
|
||||
@@ -28,7 +31,7 @@ pub fn open_on_missing(app: &mut VectorcraftApp) {
|
||||
/// System's font ([`system_family`]) to change to, and the last Find In choice (Document at first).
|
||||
fn open_at(app: &mut VectorcraftApp, selected: usize) {
|
||||
let find_in = FIND_IN.iter().find(|f| **f == app.ui.find_font_in).copied().unwrap_or("document");
|
||||
let used = fonts(app);
|
||||
let (used, _) = document_fonts(app, false);
|
||||
let source = "system";
|
||||
let rows = replacement_rows(app, source, &used);
|
||||
let family = system_family();
|
||||
@@ -252,6 +255,30 @@ fn fonts(app: &mut VectorcraftApp) -> Vec<Value> {
|
||||
app.session.execute("text.fonts", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The active document's fonts ([`fonts`]) and, when `missing` is asked for, whether it misses a
|
||||
/// font ([`vectorcraft_engine::cmd::fontfiles::missing_fonts`]; `false` when it is not asked
|
||||
/// for). Both are kept in [`crate::CanvasCache::find_font`] and worked out again only for another
|
||||
/// document, another version of its content or another font generation. No document: no fonts.
|
||||
fn document_fonts(app: &mut VectorcraftApp, missing: bool) -> (Arc<Vec<Value>>, bool) {
|
||||
let Some(st) = app.session.active() else { return (Arc::default(), false) };
|
||||
// The generation is read first: fonts loaded while the answers are worked out leave the entry
|
||||
// under the older generation, so the next frame works them out again.
|
||||
let key = FontsKey { uid: st.uid, doc: Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() };
|
||||
if app.canvas.find_font.as_ref().is_none_or(|c| c.key != key) {
|
||||
let fonts = Arc::new(fonts(app));
|
||||
app.canvas.find_font = Some(FindFontCache { key, fonts, missing: None });
|
||||
}
|
||||
if missing
|
||||
&& let Some(c) = app.canvas.find_font.as_mut()
|
||||
&& c.missing.is_none()
|
||||
&& let Some(st) = app.session.active()
|
||||
{
|
||||
c.missing = Some(!vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
|
||||
}
|
||||
let c = app.canvas.find_font.as_ref();
|
||||
(c.map(|c| c.fonts.clone()).unwrap_or_default(), missing && c.and_then(|c| c.missing).unwrap_or(false))
|
||||
}
|
||||
|
||||
pub fn confirm(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
if let Some(ctx) = app.ui_ctx.clone() {
|
||||
clear_search(&ctx);
|
||||
@@ -279,10 +306,9 @@ fn change(app: &mut VectorcraftApp, d: &Dialog, from: &Value, all: bool) -> Resu
|
||||
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(mut d) = app.ui.dialog.clone() else { return };
|
||||
let t = Tokens::get(ctx);
|
||||
let list = fonts(app);
|
||||
// Find in Folder… shows when the document misses fonts, fonts used only in its symbols included.
|
||||
let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder)
|
||||
&& app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
|
||||
let can_pick = crate::picks::can(app, &crate::picks::PickRequest::Folder);
|
||||
let (list, offer_folder) = document_fonts(app, can_pick);
|
||||
let mut close = false;
|
||||
let mut find_in_folder = false;
|
||||
let mut act: Option<&str> = None;
|
||||
@@ -416,7 +442,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
match run_button(app, &d, a, from) {
|
||||
// The rows are a snapshot: the document's fonts and the recent fonts have moved on.
|
||||
Ok(_) if a != "find" => {
|
||||
let used = fonts(app);
|
||||
let (used, _) = document_fonts(app, false);
|
||||
d.fields.insert("rows".into(), rows_json(&replacement_rows(app, &d.str("replaceFrom"), &used)));
|
||||
}
|
||||
Ok(_) => {}
|
||||
@@ -1421,4 +1447,231 @@ mod tests {
|
||||
let (note, color) = font_note(&row("exact", 2));
|
||||
assert!(note.contains("2 characters") && color.is_some());
|
||||
}
|
||||
|
||||
/// The font list the dialog keeps for the active document.
|
||||
fn kept_list(app: &VectorcraftApp) -> Arc<Vec<Value>> {
|
||||
app.canvas.find_font.as_ref().expect("the dialog kept the document's fonts").fonts.clone()
|
||||
}
|
||||
|
||||
/// The kept list and Find in Folder… are what `text.fonts` and `missing_fonts` give now.
|
||||
fn assert_current(app: &mut VectorcraftApp, shown: &str, why: &str) {
|
||||
let listed = fonts(app);
|
||||
assert_eq!(*kept_list(app), listed, "{why}: the list");
|
||||
let missing = app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
|
||||
let picks = crate::picks::can(app, &crate::picks::PickRequest::Folder);
|
||||
assert_eq!(shown.contains("Find in Folder…"), picks && missing, "{why}: Find in Folder… {shown}");
|
||||
}
|
||||
|
||||
/// A document set in a missing family and in Inter, with a folder picker.
|
||||
fn missing_font_document() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
for (y, font) in [(20, "Missing Family"), (40, "Inter")] {
|
||||
app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap();
|
||||
}
|
||||
app.services.pick_folder = Some(Box::new(|| None));
|
||||
app
|
||||
}
|
||||
|
||||
/// Frames that change nothing in the document, a new selection included, keep the font list
|
||||
/// and the missing-font answer worked out on the first; the answer is worked out only once a
|
||||
/// folder picker is there.
|
||||
#[test]
|
||||
fn the_font_list_is_worked_out_once_per_document_version() {
|
||||
let mut app = missing_font_document();
|
||||
let picker = app.services.pick_folder.take();
|
||||
open(&mut app);
|
||||
assert!(kept_over_frames(&mut app, "no folder picker"), "frames of one document version keep its list");
|
||||
assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), None, "no picker: the document is not searched for missing fonts");
|
||||
app.services.pick_folder = picker;
|
||||
assert!(kept_over_frames(&mut app, "a folder picker"), "a picker alone keeps the list");
|
||||
assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), Some(true));
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
assert!(kept_over_frames(&mut app, "a new selection"), "a new selection keeps the list");
|
||||
}
|
||||
|
||||
/// Draws frames of the dialog and tells whether they kept the list kept before them. Another
|
||||
/// test thread that changes the available fonts meanwhile makes the dialog work the list out
|
||||
/// again, so the frames are drawn again until the fonts stay as they are.
|
||||
fn kept_over_frames(app: &mut VectorcraftApp, why: &str) -> bool {
|
||||
for _ in 0..20 {
|
||||
// The generation the kept list was worked out under: the database's generation only
|
||||
// counts up, so the same one after the frames means no fonts changed in between.
|
||||
let before = kept_list(app);
|
||||
let generation = app.canvas.find_font.as_ref().map(|c| c.key.generation);
|
||||
let shown = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(app, &shown, why);
|
||||
if Some(vectorcraft_text::FontDb::global().generation()) == generation {
|
||||
return Arc::ptr_eq(&before, &kept_list(app));
|
||||
}
|
||||
}
|
||||
panic!("{why}: the available fonts kept changing")
|
||||
}
|
||||
|
||||
/// An edit, its undo and a Change All each give the list of the document as it is then.
|
||||
#[test]
|
||||
fn an_edit_works_the_font_list_out_again() {
|
||||
let mut app = missing_font_document();
|
||||
open(&mut app);
|
||||
crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
let first = kept_list(&app);
|
||||
app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Inter"}})).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "after the replacement");
|
||||
assert!(!shown.contains("Find in Folder…"), "nothing is missing: {shown}");
|
||||
assert_eq!(kept_list(&app).len(), 1, "{:?}", kept_list(&app));
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "after the undo");
|
||||
assert_eq!(*kept_list(&app), *first, "the undo brings back the first list");
|
||||
let mut d = app.ui.dialog.clone().unwrap();
|
||||
d.fields.insert("family".into(), json!("Source Serif 4"));
|
||||
d.fields.insert("style".into(), json!(""));
|
||||
let from = first.iter().find(|f| f["family"] == "Inter").unwrap().clone();
|
||||
change(&mut app, &d, &from, true).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "after Change All");
|
||||
assert!(kept_list(&app).iter().any(|f| f["family"] == "Source Serif 4"), "{:?}", kept_list(&app));
|
||||
}
|
||||
|
||||
/// Fonts that become available, a composite font defined among them, give the list and the
|
||||
/// missing-font answer as they are with those fonts.
|
||||
#[test]
|
||||
fn other_available_fonts_work_the_font_list_out_again() {
|
||||
const FAMILY: &str = "Find Font Kept List CF";
|
||||
let mut app = missing_font_document();
|
||||
app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Ab12", "font": FAMILY})).unwrap();
|
||||
open(&mut app);
|
||||
crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
// The same document under another generation of the font database: what is kept for it no
|
||||
// longer counts.
|
||||
let entry = app.canvas.find_font.as_mut().unwrap();
|
||||
entry.key.generation = u64::MAX;
|
||||
entry.fonts = Arc::default();
|
||||
entry.missing = Some(false);
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "another font generation");
|
||||
let row = |app: &VectorcraftApp| kept_list(app).iter().find(|f| f["family"] == FAMILY).cloned().unwrap();
|
||||
assert_eq!(row(&app)["status"], "missing");
|
||||
let generation = vectorcraft_text::FontDb::global().generation();
|
||||
let parts = json!({"name": FAMILY, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono"}, "numerals": {"font": "Inter"}}});
|
||||
app.run("type.compositeFonts.set", json!({"fonts": [parts]})).unwrap();
|
||||
assert_ne!(vectorcraft_text::FontDb::global().generation(), generation, "defining a composite font is a new generation");
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "the composite font defined");
|
||||
assert_eq!(row(&app)["status"], "exact");
|
||||
app.run("type.compositeFonts.set", json!({"fonts": []})).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "the composite font taken out");
|
||||
assert_eq!(row(&app)["status"], "missing");
|
||||
}
|
||||
|
||||
/// Another document in front, and pattern editing entered and canceled, each give the list of
|
||||
/// the document in front as it is then.
|
||||
#[test]
|
||||
fn the_font_list_follows_the_document_in_front() {
|
||||
let mut app = missing_font_document();
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Serif 4"})).unwrap()["id"].clone();
|
||||
app.services.pick_folder = Some(Box::new(|| None));
|
||||
open(&mut app);
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "the second document");
|
||||
app.session.set_active(0);
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "the first document");
|
||||
assert!(shown.contains("Find in Folder…"), "{shown}");
|
||||
app.session.set_active(1);
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.run("object.pattern.make", json!({"name": "Kept List"})).unwrap();
|
||||
assert!(app.session.active().unwrap().doc.pattern_edit.is_some(), "pattern editing");
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "pattern editing");
|
||||
app.run("object.pattern.cancel", json!({})).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "pattern editing canceled");
|
||||
}
|
||||
|
||||
/// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`.
|
||||
fn thread_cpu_ns() -> Option<u128> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Time the font list and the missing-font answer a Find Font frame reads, for a document of
|
||||
/// 2,000 point-type objects of 50 characters each and one of 20, set in five installed faces
|
||||
/// and a missing family, with a folder picker: worked out on every frame as `text.fonts` and
|
||||
/// `missing_fonts` (each frame before they were kept), on the first frame of a document version
|
||||
/// ([`document_fonts`] with nothing kept) and on later frames. Per run, the large document
|
||||
/// draws 120 frames and the small one 12,000 (so the thread's CPU clock, which advances in
|
||||
/// steps of a few milliseconds, sees them), and later frames number 1,000,000; the sides
|
||||
/// alternate, and the median time per frame of 7 runs is printed.
|
||||
/// Run with `cargo test --release -p vectorcraft-ui-egui --lib find_font_list_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; performance depends on machine load"]
|
||||
fn find_font_list_timing() {
|
||||
const KEPT: u32 = 1_000_000;
|
||||
const FACES: [(&str, &str); 6] = [
|
||||
("Inter", "Regular"),
|
||||
("Inter", "Medium"),
|
||||
("Source Sans 3", "Bold"),
|
||||
("Source Serif 4", "Regular"),
|
||||
("JetBrains Mono", "Regular"),
|
||||
("Missing Family", "Regular"),
|
||||
];
|
||||
for (objects, frames) in [(2_000, 120), (20, 12_000)] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap();
|
||||
for i in 0..objects {
|
||||
let (family, style) = FACES[i % FACES.len()];
|
||||
let text: String = (0..50).map(|c| char::from(b'a' + ((i + c) % 26) as u8)).collect();
|
||||
let (x, y) = ((i % 20 * 90) as f64, (i / 20 * 18) as f64 + 20.0);
|
||||
app.session.execute("text.create", &json!({"x": x, "y": y, "text": text, "font": family, "style": style})).unwrap();
|
||||
}
|
||||
app.services.pick_folder = Some(Box::new(|| None));
|
||||
let every_frame = |app: &mut VectorcraftApp| {
|
||||
let list = fonts(app);
|
||||
let offer = crate::picks::can(app, &crate::picks::PickRequest::Folder)
|
||||
&& app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
|
||||
(list, offer)
|
||||
};
|
||||
let expected = every_frame(&mut app);
|
||||
assert!(expected.1 && expected.0.len() == FACES.len(), "{expected:?}");
|
||||
let kept = document_fonts(&mut app, true);
|
||||
assert_eq!((kept.0.to_vec(), kept.1), expected, "the kept answers are the ones worked out every frame");
|
||||
// Each side's answers for one frame: the number of fonts listed and Find in Folder….
|
||||
let time = |app: &mut VectorcraftApp, frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> (usize, bool)| {
|
||||
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..frames {
|
||||
assert_eq!(f(app), (FACES.len(), true));
|
||||
}
|
||||
let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a);
|
||||
ns as f64 / f64::from(frames) / 1000.0
|
||||
};
|
||||
let (mut full, mut first, mut later) = (vec![], vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
full.push(time(&mut app, frames, &mut |app| {
|
||||
let (list, offer) = every_frame(app);
|
||||
(list.len(), offer)
|
||||
}));
|
||||
first.push(time(&mut app, frames, &mut |app| {
|
||||
app.canvas.find_font = None;
|
||||
let (list, offer) = document_fonts(app, true);
|
||||
(list.len(), offer)
|
||||
}));
|
||||
later.push(time(&mut app, KEPT, &mut |app| {
|
||||
let (list, offer) = document_fonts(app, true);
|
||||
(list.len(), offer)
|
||||
}));
|
||||
}
|
||||
let median = |v: &mut Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" };
|
||||
eprintln!("{objects} text objects of 50 characters; {clock} per frame, median of 7 runs");
|
||||
eprintln!("worked out every frame ({frames} frames a run): {:>12.3} us {full:.3?}", median(&mut full));
|
||||
eprintln!("first frame of a version ({frames} a run): {:>12.3} us {first:.3?}", median(&mut first));
|
||||
eprintln!("later frames of the version ({KEPT} a run): {:>12.4} us {later:.4?}", median(&mut later));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -518,10 +518,10 @@ impl Filters {
|
||||
|
||||
/// The families the type in `doc` is set in, lowercase and by the name the menu lists them under
|
||||
/// ([`vectorcraft_text::FontDb::canonical`]): the runs of every text object in the layers, symbols,
|
||||
/// patterns and graph designs, hidden, locked and masked ones included, with a composite font named
|
||||
/// as such. A pattern being edited is read from its editing layer only. Each run's family is looked
|
||||
/// up with its style, so a family and style split from a PostScript name (`Honoka`, `Mincho`) find
|
||||
/// the installed font of that name. Styles no type uses are left out.
|
||||
/// patterns, graph designs and stored scatter brushes, hidden, locked and masked ones included, with
|
||||
/// a composite font named as such. A pattern being edited is read from its editing layer only. Each
|
||||
/// run's family is looked up with its style, so a family and style split from a PostScript name
|
||||
/// (`Honoka`, `Mincho`) find the installed font of that name. Styles no type uses are left out.
|
||||
fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Document) -> HashSet<String> {
|
||||
// Each family and style once, so a document with many runs in a few fonts looks each one up
|
||||
// once.
|
||||
@@ -549,6 +549,14 @@ fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Docum
|
||||
for n in doc.layers.iter().map(|l| &**l).chain(doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(designs) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut add);
|
||||
}
|
||||
// A scatter brush draws copies of its art's type along a stroke; art and pattern brushes drop
|
||||
// type when they bend their art. Malformed library entries are skipped.
|
||||
let brushes = doc.unknown.get(vectorcraft_brush::DOC_KEY).map(vectorcraft_brush::parse_library).unwrap_or_default();
|
||||
for b in &brushes {
|
||||
if let vectorcraft_brush::BrushKind::Scatter(s) = &b.kind {
|
||||
vectorcraft_doc::swatches::walk_with_masks(&s.art, &mut add);
|
||||
}
|
||||
}
|
||||
named.iter().flat_map(|(f, styles)| styles.iter().map(move |s| db.canonical(f, s).0.to_lowercase())).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -1221,6 +1221,58 @@ fn the_document_filter_counts_type_in_graph_designs() {
|
||||
assert_eq!(names, ["inter", "jetbrains mono"]);
|
||||
}
|
||||
|
||||
/// Type in the art of a stored scatter brush counts as the document's type, as a scatter stroke
|
||||
/// draws it, after a malformed library entry too. Type in an art or pattern brush's art does not,
|
||||
/// as those brushes leave type out when they bend their art.
|
||||
#[test]
|
||||
fn the_document_filter_counts_type_in_scatter_brushes() {
|
||||
let mut app = app_with_type(&["Inter"]);
|
||||
let mut art = |font: &str| {
|
||||
let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": font})).unwrap()["id"].as_u64().unwrap();
|
||||
let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type");
|
||||
app.run("edit.undo", serde_json::json!({})).unwrap();
|
||||
node
|
||||
};
|
||||
let (scatter, bent, tiled) = (art("JetBrains Mono"), art("Source Serif 4"), art("Source Sans 3"));
|
||||
let brush = |name: &str, kind| serde_json::to_value(vectorcraft_brush::Brush { name: name.into(), kind }).unwrap();
|
||||
let library = serde_json::json!([
|
||||
{"name": "Broken", "type": "scatter", "art": 7},
|
||||
brush("Art", vectorcraft_brush::BrushKind::Art(vectorcraft_brush::ArtBrush { art: bent, ..Default::default() })),
|
||||
brush("Pattern", vectorcraft_brush::BrushKind::Pattern(vectorcraft_brush::PatternBrush { side: tiled, ..Default::default() })),
|
||||
brush("Dots", vectorcraft_brush::BrushKind::Scatter(vectorcraft_brush::Scatter { art: scatter, ..Default::default() })),
|
||||
]);
|
||||
let mut doc = (*app.session.active().unwrap().doc).clone();
|
||||
doc.unknown.insert(vectorcraft_brush::DOC_KEY.into(), library);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let mut names: Vec<_> = super::document_families(db, &doc).into_iter().collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["inter", "jetbrains mono"]);
|
||||
}
|
||||
|
||||
/// A scatter brush made of type keeps its family in the Document filter after the type is deleted;
|
||||
/// deleting the brush takes the family out, and undoing the deletion brings it back.
|
||||
#[test]
|
||||
fn the_document_filter_follows_a_scatter_brushs_edits_and_undo() {
|
||||
let mut app = app_with_type(&["Inter"]);
|
||||
let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": "JetBrains Mono"})).unwrap()["id"].clone();
|
||||
let name = app.run("brush.new", serde_json::json!({"type": "scatter", "name": "Type Dots"})).unwrap()["name"].clone();
|
||||
app.run("edit.clear", serde_json::json!({"ids": [id]})).unwrap();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// One menu state throughout, so each edit has to get past the families it keeps.
|
||||
let mut st = super::MenuState { document_only: true, ..Default::default() };
|
||||
let mut families = |app: &crate::VectorcraftApp| {
|
||||
let used = super::used_families(db, &mut st, super::MenuLook::of(app)).expect("a document is open");
|
||||
let mut names: Vec<_> = used.iter().cloned().collect();
|
||||
names.sort();
|
||||
names
|
||||
};
|
||||
assert_eq!(families(&app), ["inter", "jetbrains mono"], "the brush's type");
|
||||
app.run("brush.delete", serde_json::json!({"name": name})).unwrap();
|
||||
assert_eq!(families(&app), ["inter"], "the brush deleted");
|
||||
app.run("edit.undo", serde_json::json!({})).unwrap();
|
||||
assert_eq!(families(&app), ["inter", "jetbrains mono"], "the deletion undone");
|
||||
}
|
||||
|
||||
/// A run whose family and style were split from a PostScript name (as an importer without the font
|
||||
/// splits one) counts under the family of the installed font of that name, found with its style.
|
||||
#[test]
|
||||
|
||||
@@ -127,6 +127,7 @@
|
||||
Add to Swatches Добавяне към образци
|
||||
Add Used Colors Добавяне на използваните цветове
|
||||
Additional Plug-ins Folder Допълнителна папка за плъгини
|
||||
Plug-in Instruction Budget Бюджет на инструкции за плъгини
|
||||
Additional Fonts Folder Допълнителна папка за шрифтове
|
||||
Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина
|
||||
Incoming Входяща
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3944,6 +3944,7 @@ theme Appearance Izgled
|
||||
90° & 45° Angles Uglovi od 90° i 45°
|
||||
90° Angles Uglovi od 90°
|
||||
Additional Plug-ins Folder Dodatni folder dodataka
|
||||
Plug-in Instruction Budget Budžet instrukcija za dodatke
|
||||
Additional Fonts Folder Dodatni folder fontova
|
||||
Alignment Guides Vodilice za poravnanje
|
||||
Anchor Points, Handle, and Bounding Box Display Prikaz sidrenih tačaka, ručki i graničnog okvira
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -223,6 +223,7 @@
|
||||
Add Used Colors Afegeix els colors utilitzats
|
||||
Additional Fonts Folder Carpeta addicional de tipus de lletra
|
||||
Additional Plug-ins Folder Carpeta addicional de complements
|
||||
Plug-in Instruction Budget Pressupost d’instruccions dels complements
|
||||
Adjust Adjoining Width Points Ajusta els punts d’amplada contigus
|
||||
Incoming Entrant
|
||||
Outgoing Sortint
|
||||
@@ -5810,6 +5811,7 @@ digits Malayalam Malaiàlam
|
||||
@msg a linked JavaScript file is outside the read roots un fitxer JavaScript enllaçat és fora de les arrels de lectura
|
||||
@msg a linked image file is outside the read roots un fitxer d’imatge enllaçat és fora de les arrels de lectura
|
||||
@msg a linked file's export folder is outside the read roots la carpeta d’exportació d’un fitxer enllaçat és fora de les arrels de lectura
|
||||
@msg a linked file's editing data can't be read to check it against the read roots no es poden llegir les dades d’edició d’un fitxer enllaçat per comprovar-les amb les arrels de lectura
|
||||
@msg the library's file is outside the read roots el fitxer de la biblioteca és fora de les arrels de lectura
|
||||
@msg {file} names more than one linked JavaScript file {file} correspon a més d’un fitxer JavaScript enllaçat
|
||||
@msg automation path rejected: outside the write root {root}: {path} camí d’automatització rebutjat: fora de l’arrel d’escriptura {root}: {path}
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4048,6 +4048,7 @@ theme Appearance Motiv
|
||||
90° & 45° Angles Úhly 90° a 45°
|
||||
90° Angles Úhly 90°
|
||||
Additional Plug-ins Folder Další složka zásuvných modulů
|
||||
Plug-in Instruction Budget Rozpočet instrukcí zásuvných modulů
|
||||
Additional Fonts Folder Další složka písem
|
||||
Alignment Guides Vodítka zarovnání
|
||||
Anchor Points, Handle, and Bounding Box Display Zobrazení kotevních bodů, úchytů a ohraničovacího rámečku
|
||||
@@ -6022,6 +6023,7 @@ variable-list-end {0}, {1} {0} a {1}
|
||||
@msg a linked JavaScript file is outside the read roots propojený soubor JavaScript je mimo kořeny pro čtení
|
||||
@msg a linked image file is outside the read roots propojený soubor obrázku je mimo kořeny pro čtení
|
||||
@msg a linked file's export folder is outside the read roots exportní složka propojeného souboru je mimo kořeny pro čtení
|
||||
@msg a linked file's editing data can't be read to check it against the read roots editační data propojeného souboru nelze přečíst a ověřit vůči kořenům pro čtení
|
||||
@msg automation path rejected: outside the write root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro zápis {root}: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro zápis {roots}: {path}
|
||||
@msg automation path rejected: path is empty cesta automatizace odmítnuta: cesta je prázdná
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1439,6 +1439,7 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg a linked JavaScript file is outside the read roots en linket JavaScript-fil ligger uden for læserødderne
|
||||
@msg a linked image file is outside the read roots en linket billedfil ligger uden for læserødderne
|
||||
@msg a linked file's export folder is outside the read roots eksportmappen for en linket fil ligger uden for læserødderne
|
||||
@msg a linked file's editing data can't be read to check it against the read roots redigeringsdataene for en linket fil kan ikke læses for at kontrollere dem mod læserødderne
|
||||
@msg a name names one asset: give multiple: false, or one object et navn angiver ét aktiv: angiv multiple: false eller ét objekt
|
||||
@msg a namespace declaration uses a reserved prefix or URI en navnerumserklæring bruger et reserveret præfiks eller en reserveret URI
|
||||
@msg a namespace qualifier is undefined en navnerumskvalifikator er udefineret
|
||||
@@ -6496,6 +6497,7 @@ theme Appearance Udseende
|
||||
90° & 45° Angles 90° & 45°-vinkler
|
||||
90° Angles 90°-vinkler
|
||||
Additional Plug-ins Folder Yderligere mappe med plug-ins
|
||||
Plug-in Instruction Budget Instruktionsbudget for plug-ins
|
||||
Additional Fonts Folder Yderligere mappe med skrifttyper
|
||||
Alignment Guides Justeringshjælpelinjer
|
||||
Anchor Points, Handle, and Bounding Box Display Visning af ankerpunkter, håndtag og afgrænsningsboks
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -116,6 +116,7 @@
|
||||
Add to Swatches Zu Farbfeldern hinzufügen
|
||||
Add Used Colors Verwendete Farben hinzufügen
|
||||
Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner
|
||||
Plug-in Instruction Budget Anweisungsbudget für Plug-ins
|
||||
Additional Fonts Folder Zusätzlicher Schriftenordner
|
||||
Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen
|
||||
Incoming Eingehend
|
||||
@@ -9589,6 +9590,7 @@ breakText Glyphs Glyphen
|
||||
@msg a linked JavaScript file is outside the read roots eine verknüpfte JavaScript-Datei liegt außerhalb der Lesestammordner
|
||||
@msg a linked image file is outside the read roots eine verknüpfte Bilddatei liegt außerhalb der Lesestammordner
|
||||
@msg a linked file's export folder is outside the read roots der Exportordner einer verknüpften Datei liegt außerhalb der Lesestammordner
|
||||
@msg a linked file's editing data can't be read to check it against the read roots die Bearbeitungsdaten einer verknüpften Datei können nicht gelesen werden, um sie mit den Lesestammordnern abzugleichen
|
||||
@msg a number cannot be read eine Zahl kann nicht gelesen werden
|
||||
@msg a swatch exchange block is too long ein Block der Farbfeld-Austauschdatei ist zu lang
|
||||
@msg a swatch exchange name is too long ein Name in der Farbfeld-Austauschdatei ist zu lang
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -121,6 +121,7 @@
|
||||
Add to Swatches Προσθήκη στα δείγματα χρωμάτων
|
||||
Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων
|
||||
Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων
|
||||
Plug-in Instruction Budget Προϋπολογισμός εντολών επεκτάσεων
|
||||
Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών
|
||||
Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους
|
||||
Incoming Εισερχόμενο
|
||||
@@ -5719,6 +5720,7 @@ variable-list-end {0}, {1} {0} και {1}
|
||||
@msg a linked JavaScript file is outside the read roots ένα συνδεδεμένο αρχείο JavaScript είναι εκτός των ριζών ανάγνωσης
|
||||
@msg a linked image file is outside the read roots ένα συνδεδεμένο αρχείο εικόνας είναι εκτός των ριζών ανάγνωσης
|
||||
@msg a linked file's export folder is outside the read roots ο φάκελος εξαγωγής ενός συνδεδεμένου αρχείου είναι εκτός των ριζών ανάγνωσης
|
||||
@msg a linked file's editing data can't be read to check it against the read roots τα δεδομένα επεξεργασίας ενός συνδεδεμένου αρχείου δεν μπορούν να διαβαστούν για έλεγχο με τις ρίζες ανάγνωσης
|
||||
@msg the library's file is outside the read roots το αρχείο της βιβλιοθήκης είναι εκτός των ριζών ανάγνωσης
|
||||
@msg {file} names more than one linked JavaScript file το {file} αντιστοιχεί σε περισσότερα από ένα συνδεδεμένα αρχεία JavaScript
|
||||
@msg automation path rejected: outside the write root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας εγγραφής {root}: {path}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -141,6 +141,7 @@
|
||||
Add to Swatches Agregar a muestras
|
||||
Add Used Colors Agregar colores usados
|
||||
Additional Plug-ins Folder Carpeta de plugins adicionales
|
||||
Plug-in Instruction Budget Presupuesto de instrucciones de plugins
|
||||
Additional Fonts Folder Carpeta de fuentes adicionales
|
||||
Adjust Adjoining Width Points Ajustar puntos de anchura contiguos
|
||||
Incoming Entrante
|
||||
@@ -5760,6 +5761,7 @@ variable-list-end {0}, {1} {0} y {1}
|
||||
@msg a linked JavaScript file is outside the read roots un archivo JavaScript vinculado está fuera de las carpetas raíz de lectura
|
||||
@msg a linked image file is outside the read roots un archivo de imagen vinculado está fuera de las carpetas raíz de lectura
|
||||
@msg a linked file's export folder is outside the read roots la carpeta de exportación de un archivo vinculado está fuera de las carpetas raíz de lectura
|
||||
@msg a linked file's editing data can't be read to check it against the read roots no se pueden leer los datos de edición de un archivo vinculado para comprobarlos con las carpetas raíz de lectura
|
||||
@msg automation path rejected: outside the write root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de escritura {root}: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de escritura {roots}: {path}
|
||||
@msg automation path rejected: path is empty ruta de automatización rechazada: la ruta está vacía
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3984,6 +3984,7 @@ theme Appearance Ulkoasu
|
||||
90° & 45° Angles 90° ja 45° kulmat
|
||||
90° Angles 90° kulmat
|
||||
Additional Plug-ins Folder Lisälaajennusten kansio
|
||||
Plug-in Instruction Budget Laajennusten käskybudjetti
|
||||
Additional Fonts Folder Lisäfonttien kansio
|
||||
Alignment Guides Tasausapuviivat
|
||||
Anchor Points, Handle, and Bounding Box Display Ankkuripisteiden, kahvojen ja rajausruudun näyttö
|
||||
@@ -5942,6 +5943,7 @@ variable-list-end {0}, {1} {0} ja {1}
|
||||
@msg a linked JavaScript file is outside the read roots linkitetty JavaScript-tiedosto on lukujuurten ulkopuolella
|
||||
@msg a linked image file is outside the read roots linkitetty kuvatiedosto on lukujuurten ulkopuolella
|
||||
@msg a linked file's export folder is outside the read roots linkitetyn tiedoston vientikansio on lukujuurten ulkopuolella
|
||||
@msg a linked file's editing data can't be read to check it against the read roots linkitetyn tiedoston muokkaustietoja ei voi lukea niiden tarkistamiseksi lukujuuria vasten
|
||||
@msg the library's file is outside the read roots kirjaston tiedosto on lukujuurten ulkopuolella
|
||||
@msg {file} names more than one linked JavaScript file {file} vastaa useampaa kuin yhtä linkitettyä JavaScript-tiedostoa
|
||||
@msg automation path rejected: outside the write root {root}: {path} automaation polku hylättiin: kirjoitusjuuren {root} ulkopuolella: {path}
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -142,6 +142,7 @@
|
||||
Add to Swatches Ajouter au nuancier
|
||||
Add Used Colors Ajouter les couleurs utilisées
|
||||
Additional Plug-ins Folder Dossier de modules externes supplémentaires
|
||||
Plug-in Instruction Budget Budget d’instructions des modules externes
|
||||
Additional Fonts Folder Dossier de polices supplémentaires
|
||||
Adjust Adjoining Width Points Ajuster les points de largeur adjacents
|
||||
Incoming Entrant
|
||||
@@ -5737,6 +5738,7 @@ variable-list-end {0}, {1} {0} et {1}
|
||||
@msg a linked JavaScript file is outside the read roots un fichier JavaScript lié est hors des dossiers racines de lecture
|
||||
@msg a linked image file is outside the read roots un fichier image lié est hors des dossiers racines de lecture
|
||||
@msg a linked file's export folder is outside the read roots le dossier d’exportation d’un fichier lié est hors des dossiers racines de lecture
|
||||
@msg a linked file's editing data can't be read to check it against the read roots impossible de lire les données d’édition d’un fichier lié pour les vérifier par rapport aux dossiers racines de lecture
|
||||
@msg automation path rejected: outside the write root {root}: {path} chemin d’automatisation refusé : hors du dossier racine d’écriture {root} : {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines d’écriture {roots} : {path}
|
||||
@msg automation path rejected: path is empty chemin d’automatisation refusé : le chemin est vide
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -164,6 +164,7 @@
|
||||
Add to the Current Shortcuts વર્તમાન શૉર્ટકટમાં ઉમેરો
|
||||
Additional Fonts Folder વધારાનું ફોન્ટ ફોલ્ડર
|
||||
Additional Plug-ins Folder વધારાનું પ્લગ-ઇન ફોલ્ડર
|
||||
Plug-in Instruction Budget પ્લગ-ઇન સૂચના બજેટ
|
||||
Adjust Adjoining Width Points અડીને આવેલા પહોળાઈ બિંદુઓ ગોઠવો
|
||||
Incoming આવતી બાજુ
|
||||
Outgoing જતી બાજુ
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -257,6 +257,7 @@
|
||||
Add Used Colors उपयोग किए रंग जोड़ें
|
||||
Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर
|
||||
Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर
|
||||
Plug-in Instruction Budget प्लग-इन निर्देश बजट
|
||||
Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें
|
||||
Incoming आने वाली ओर
|
||||
Outgoing जाने वाली ओर
|
||||
@@ -6858,6 +6859,7 @@ antiAlias Sharp शार्प
|
||||
@msg a linked JavaScript file is outside the read roots एक लिंक की गई जावास्क्रिप्ट फ़ाइल पढ़ने की जड़ों के बाहर है
|
||||
@msg a linked image file is outside the read roots एक लिंक की गई छवि फ़ाइल पढ़ने की जड़ों के बाहर है
|
||||
@msg a linked file's export folder is outside the read roots एक लिंक की गई फ़ाइल का निर्यात फ़ोल्डर पढ़ने की जड़ों के बाहर है
|
||||
@msg a linked file's editing data can't be read to check it against the read roots एक लिंक की गई फ़ाइल का संपादन डेटा पढ़ने की जड़ों से जाँचने के लिए पढ़ा नहीं जा सकता
|
||||
@msg the library's file is outside the read roots लाइब्रेरी की फ़ाइल पढ़ने की जड़ों के बाहर है
|
||||
@msg {file} names more than one linked JavaScript file {file} एक से अधिक लिंक की गई जावास्क्रिप्ट फ़ाइलों से मेल खाता है
|
||||
@msg automation path rejected: outside the write root {root}: {path} स्वचालन पाथ खारिज: लिखने की जड़ के बाहर {root}: {path}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -211,6 +211,7 @@
|
||||
Add Used Colors Használt színek hozzáadása
|
||||
Additional Fonts Folder További betűtípusok mappája
|
||||
Additional Plug-ins Folder További bővítmények mappája
|
||||
Plug-in Instruction Budget Bővítmények utasításkerete
|
||||
Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása
|
||||
Incoming Bejövő
|
||||
Outgoing Kimenő
|
||||
@@ -5405,6 +5406,7 @@ imageTrace Outline Körvonal
|
||||
@msg a linked JavaScript file is outside the read roots egy csatolt JavaScript-fájl kívül esik az olvasási gyökereken
|
||||
@msg a linked image file is outside the read roots egy csatolt képfájl kívül esik az olvasási gyökereken
|
||||
@msg a linked file's export folder is outside the read roots egy csatolt fájl exportálási mappája kívül esik az olvasási gyökereken
|
||||
@msg a linked file's editing data can't be read to check it against the read roots egy csatolt fájl szerkesztési adatai nem olvashatók be az olvasási gyökerekkel való ellenőrzéshez
|
||||
@msg automation path rejected: outside the write root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökéren ({root}): {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökereken ({roots}): {path}
|
||||
@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} az automatizálás útvonala elutasítva: szülőmappára lépés egy nem létező mappa alatt: {path}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3715,6 +3715,7 @@ theme Appearance Tampilan
|
||||
90° & 45° Angles Sudut 90° & 45°
|
||||
90° Angles Sudut 90°
|
||||
Additional Plug-ins Folder Folder plug-in tambahan
|
||||
Plug-in Instruction Budget Anggaran instruksi plug-in
|
||||
Additional Fonts Folder Folder font tambahan
|
||||
Alignment Guides Panduan perataan
|
||||
Anchor Points, Handle, and Bounding Box Display Tampilan titik jangkar, pegangan, dan kotak pembatas
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2538 and column 5.
|
@@ -141,6 +141,7 @@
|
||||
Add to Swatches Aggiungi ai campioni
|
||||
Add Used Colors Aggiungi colori usati
|
||||
Additional Plug-ins Folder Cartella plug-in aggiuntivi
|
||||
Plug-in Instruction Budget Budget di istruzioni dei plug-in
|
||||
Additional Fonts Folder Cartella font aggiuntivi
|
||||
Adjust Adjoining Width Points Regola punti di larghezza adiacenti
|
||||
Incoming In entrata
|
||||
@@ -5782,6 +5783,7 @@ variable-list-end {0}, {1} {0} e {1}
|
||||
@msg a linked JavaScript file is outside the read roots un file JavaScript collegato è fuori dalle cartelle radice di lettura
|
||||
@msg a linked image file is outside the read roots un file immagine collegato è fuori dalle cartelle radice di lettura
|
||||
@msg a linked file's export folder is outside the read roots la cartella di esportazione di un file collegato è fuori dalle cartelle radice di lettura
|
||||
@msg a linked file's editing data can't be read to check it against the read roots impossibile leggere i dati di modifica di un file collegato per verificarli rispetto alle cartelle radice di lettura
|
||||
@msg automation path rejected: outside the write root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di scrittura {root}: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di scrittura {roots}: {path}
|
||||
@msg automation path rejected: path is empty percorso di automazione rifiutato: il percorso è vuoto
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1093,6 +1093,7 @@ digits Malayalam マラヤーラム数字
|
||||
Add to Selection 選択範囲に追加
|
||||
Add to Swatches スウォッチに追加
|
||||
Additional Plug-ins Folder 追加プラグインフォルダー
|
||||
Plug-in Instruction Budget プラグインの命令予算
|
||||
Additional Fonts Folder 追加フォントフォルダー
|
||||
Adjust Adjoining Width Points 隣接する幅ポイントを調整
|
||||
Incoming 入り側
|
||||
@@ -5830,6 +5831,7 @@ liquify-list-end {0}, {1} {0}、{1}
|
||||
@msg a linked JavaScript file is outside the read roots リンクされた JavaScript ファイルが読み込みルートの外にあります
|
||||
@msg a linked image file is outside the read roots リンクされた画像ファイルが読み込みルートの外にあります
|
||||
@msg a linked file's export folder is outside the read roots リンクされたファイルの書き出しフォルダーが読み込みルートの外にあります
|
||||
@msg a linked file's editing data can't be read to check it against the read roots リンクされたファイルの編集データを読み込めないため、読み込みルートと照合できません
|
||||
@msg automation path rejected: outside the write root {root}: {path} 自動化のパスを拒否しました: 書き込みルート {root} の外です: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} 自動化のパスを拒否しました: 書き込みルート {roots} のいずれの中でもありません: {path}
|
||||
@msg automation path rejected: path is empty 自動化のパスを拒否しました: パスが空です
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2066,6 +2066,7 @@
|
||||
@msg {var_key} must be at most {most} {var_key} უნდა იყოს მაქსიმუმ {most}
|
||||
@msg a linked image file is outside the read roots დაკავშირებული გამოსახულების ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა
|
||||
@msg a linked file's export folder is outside the read roots დაკავშირებული ფაილის ექსპორტის საქაღალდე წაკითხვის ძირეული საქაღალდეების გარეთაა
|
||||
@msg a linked file's editing data can't be read to check it against the read roots დაკავშირებული ფაილის რედაქტირების მონაცემების წაკითხვა ვერ ხერხდება წაკითხვის ძირეულ საქაღალდეებთან შესამოწმებლად
|
||||
Neon & Glow ნეონი და ნათება
|
||||
Show Hidden Panels at Edge დამალული პანელების ჩვენება კიდესთან
|
||||
@msg `anchor` must be a [subpath, anchor] pair `anchor` უნდა იყოს წყვილი [subpath, anchor]
|
||||
@@ -5809,6 +5810,7 @@ theme Appearance იერსახე
|
||||
90° & 45° Angles 90° და 45° კუთხეები
|
||||
90° Angles 90° კუთხეები
|
||||
Additional Plug-ins Folder დამატებითი პლაგინები
|
||||
Plug-in Instruction Budget პლაგინების ინსტრუქციების ბიუჯეტი
|
||||
Additional Fonts Folder შრიფტების დამატებითი საქაღალდე
|
||||
Alignment Guides გასწორების დამხმარე ხაზები
|
||||
Anchor Points, Handle, and Bounding Box Display საყრდენი წერტილების, სახელურებისა და შემომსაზღვრელი ჩარჩოს ჩვენება
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1083,6 +1083,7 @@ digits Malayalam 말라얄람어
|
||||
Add to Selection 선택 영역에 추가
|
||||
Add to Swatches 견본에 추가
|
||||
Additional Plug-ins Folder 추가 플러그인 폴더
|
||||
Plug-in Instruction Budget 플러그인 명령어 예산
|
||||
Additional Fonts Folder 추가 글꼴 폴더
|
||||
Adjust Adjoining Width Points 인접한 너비 점 조정
|
||||
Incoming 들어오는 쪽
|
||||
@@ -5759,6 +5760,7 @@ liquify-list-end {0}, {1} {0} 및 {1}
|
||||
@msg a linked JavaScript file is outside the read roots 연결된 JavaScript 파일이 읽기 루트 밖에 있습니다
|
||||
@msg a linked image file is outside the read roots 연결된 이미지 파일이 읽기 루트 밖에 있습니다
|
||||
@msg a linked file's export folder is outside the read roots 연결된 파일의 내보내기 폴더가 읽기 루트 밖에 있습니다
|
||||
@msg a linked file's editing data can't be read to check it against the read roots 연결된 파일의 편집 데이터를 읽을 수 없어 읽기 루트와 대조할 수 없습니다
|
||||
@msg automation path rejected: outside the write root {root}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {root} 밖입니다: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {roots} 밖입니다: {path}
|
||||
@msg automation path rejected: path is empty 자동화 경로가 거부되었습니다: 경로가 비어 있습니다
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4370,6 +4370,7 @@ theme Appearance Vormgeving
|
||||
90° & 45° Angles Hoeken van 90° & 45°
|
||||
90° Angles Hoeken van 90°
|
||||
Additional Plug-ins Folder Extra map met plug-ins
|
||||
Plug-in Instruction Budget Instructiebudget voor plug-ins
|
||||
Additional Fonts Folder Extra map met lettertypen
|
||||
Alignment Guides Uitlijnhulplijnen
|
||||
Anchor Points, Handle, and Bounding Box Display Weergave van ankerpunten, greep en begrenzingskader
|
||||
@@ -6494,6 +6495,7 @@ imageTrace Outline Contour
|
||||
@msg a linked JavaScript file is outside the read roots een gekoppeld JavaScript-bestand staat buiten de leesroots
|
||||
@msg a linked image file is outside the read roots een gekoppeld afbeeldingsbestand staat buiten de leesroots
|
||||
@msg a linked file's export folder is outside the read roots de exportmap van een gekoppeld bestand staat buiten de leesroots
|
||||
@msg a linked file's editing data can't be read to check it against the read roots de bewerkingsgegevens van een gekoppeld bestand kunnen niet worden gelezen om ze aan de leesroots te toetsen
|
||||
@msg a name names one asset: give multiple: false, or one object een naam noemt één asset: geef multiple: false, of één object
|
||||
@msg a namespace declaration uses a reserved prefix or URI een naamruimtedeclaratie gebruikt een gereserveerd voorvoegsel of een gereserveerde URI
|
||||
@msg a namespace qualifier is undefined een naamruimtekwalificatie is niet gedefinieerd
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3927,6 +3927,7 @@ theme Appearance Wygląd
|
||||
90° & 45° Angles Kąty 90° i 45°
|
||||
90° Angles Kąty 90°
|
||||
Additional Plug-ins Folder Dodatkowy folder wtyczek
|
||||
Plug-in Instruction Budget Budżet instrukcji wtyczek
|
||||
Additional Fonts Folder Dodatkowy folder czcionek
|
||||
Alignment Guides Linie wyrównania
|
||||
Anchor Points, Handle, and Bounding Box Display Wyświetlanie punktów kontrolnych, uchwytów i obwiedni
|
||||
@@ -5842,6 +5843,7 @@ variable-list-end {0}, {1} {0} i {1}
|
||||
@msg a linked JavaScript file is outside the read roots połączony plik JavaScript jest poza katalogami głównymi odczytu
|
||||
@msg a linked image file is outside the read roots połączony plik obrazu jest poza katalogami głównymi odczytu
|
||||
@msg a linked file's export folder is outside the read roots folder eksportu połączonego pliku jest poza katalogami głównymi odczytu
|
||||
@msg a linked file's editing data can't be read to check it against the read roots nie można odczytać danych edycji połączonego pliku, aby sprawdzić je względem katalogów głównych odczytu
|
||||
@msg automation path rejected: outside the write root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym zapisu {root}: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi zapisu {roots}: {path}
|
||||
@msg automation path rejected: path is empty odrzucono ścieżkę automatyzacji: ścieżka jest pusta
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -147,6 +147,7 @@
|
||||
Add to Selection Adicionar à Seleção
|
||||
Add to Swatches Adicionar às Amostras
|
||||
Additional Plug-ins Folder Pasta Adicional de Plug-ins
|
||||
Plug-in Instruction Budget Orçamento de Instruções de Plug-ins
|
||||
Additional Fonts Folder Pasta Adicional de Fontes
|
||||
Adjust Adjoining Width Points Ajustar Pontos de Largura Adjacentes
|
||||
Incoming Entrada
|
||||
@@ -4972,6 +4973,7 @@ variable-list-end {0}, {1} {0} e {1}
|
||||
@msg a linked JavaScript file is outside the read roots um arquivo JavaScript vinculado está fora das raízes de leitura
|
||||
@msg a linked image file is outside the read roots um arquivo de imagem vinculado está fora das raízes de leitura
|
||||
@msg a linked file's export folder is outside the read roots a pasta de exportação de um arquivo vinculado está fora das raízes de leitura
|
||||
@msg a linked file's editing data can't be read to check it against the read roots não é possível ler os dados de edição de um arquivo vinculado para verificá-los em relação às raízes de leitura
|
||||
@msg automation path rejected: outside the write root {root}: {path} caminho da automação rejeitado: fora da raiz de gravação {root}: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} caminho da automação rejeitado: fora das raízes de gravação {roots}: {path}
|
||||
@msg automation path rejected: path is empty caminho da automação rejeitado: o caminho está vazio
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -139,6 +139,7 @@
|
||||
Add to Swatches Добавить в образцы
|
||||
Add Used Colors Добавить использованные цвета
|
||||
Additional Plug-ins Folder Папка дополнительных модулей
|
||||
Plug-in Instruction Budget Бюджет инструкций модулей
|
||||
Additional Fonts Folder Папка дополнительных шрифтов
|
||||
Adjust Adjoining Width Points Настроить смежные точки ширины
|
||||
Incoming Входящая
|
||||
@@ -5781,6 +5782,7 @@ variable-list-end {0}, {1} {0} и {1}
|
||||
@msg a linked JavaScript file is outside the read roots связанный файл JavaScript находится вне корневых папок для чтения
|
||||
@msg a linked image file is outside the read roots связанный файл изображения находится вне корневых папок для чтения
|
||||
@msg a linked file's export folder is outside the read roots папка экспорта связанного файла находится вне корневых папок для чтения
|
||||
@msg a linked file's editing data can't be read to check it against the read roots не удаётся прочитать данные редактирования связанного файла, чтобы сверить их с корневыми папками для чтения
|
||||
@msg automation path rejected: outside the write root {root}: {path} путь автоматизации отклонён: вне корневой папки для записи {root}: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для записи {roots}: {path}
|
||||
@msg automation path rejected: path is empty путь автоматизации отклонён: путь пуст
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -129,6 +129,7 @@
|
||||
Add to Swatches Lägg till i färgrutor
|
||||
Add Used Colors Lägg till använda färger
|
||||
Additional Plug-ins Folder Mapp för ytterligare plugins
|
||||
Plug-in Instruction Budget Instruktionsbudget för plugins
|
||||
Additional Fonts Folder Mapp för ytterligare typsnitt
|
||||
Adjust Adjoining Width Points Justera angränsande breddpunkter
|
||||
Incoming Inkommande
|
||||
@@ -5659,6 +5660,7 @@ variable-list-end {0}, {1} {0} och {1}
|
||||
@msg automation path rejected: outside the read roots {roots}: {path} automatiseringssökvägen avvisades: utanför läsrötterna {roots}: {path}
|
||||
@msg a linked image file is outside the read roots en länkad bildfil ligger utanför läsrötterna
|
||||
@msg a linked file's export folder is outside the read roots exportmappen för en länkad fil ligger utanför läsrötterna
|
||||
@msg a linked file's editing data can't be read to check it against the read roots redigeringsdata för en länkad fil kan inte läsas för att kontrolleras mot läsrötterna
|
||||
@msg automation path rejected: outside the write root {root}: {path} automatiseringssökvägen avvisades: utanför skrivroten {root}: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} automatiseringssökvägen avvisades: utanför skrivrötterna {roots}: {path}
|
||||
@msg automation path rejected: path is empty automatiseringssökvägen avvisades: sökvägen är tom
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -126,6 +126,7 @@
|
||||
Add to Swatches Renk Örneklerine Ekle
|
||||
Add Used Colors Kullanılan Renkleri Ekle
|
||||
Additional Plug-ins Folder Ek Eklentiler Klasörü
|
||||
Plug-in Instruction Budget Eklenti Talimat Bütçesi
|
||||
Additional Fonts Folder Ek Yazı Tipleri Klasörü
|
||||
Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın
|
||||
Incoming Gelen
|
||||
@@ -7604,6 +7605,7 @@ axis Y Axis Y ekseni
|
||||
@msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında
|
||||
@msg a linked image file is outside the read roots bağlantılı bir görüntü dosyası okuma köklerinin dışında
|
||||
@msg a linked file's export folder is outside the read roots bağlantılı bir dosyanın dışa aktarma klasörü okuma köklerinin dışında
|
||||
@msg a linked file's editing data can't be read to check it against the read roots bağlantılı bir dosyanın düzenleme verileri okuma köklerine göre denetlemek için okunamıyor
|
||||
@msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla
|
||||
@msg the method needs an XML value yöntem için bir XML değeri gerekir
|
||||
@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) boya bir serbest biçimli degrade değil (paint.editGradient {{kind: "freeform"}} ile bir tane uygulayın)
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -135,6 +135,7 @@
|
||||
Add to Swatches Додати до зразків
|
||||
Add Used Colors Додати використані кольори
|
||||
Additional Plug-ins Folder Папка додаткових модулів
|
||||
Plug-in Instruction Budget Бюджет інструкцій модулів
|
||||
Additional Fonts Folder Папка додаткових шрифтів
|
||||
Adjust Adjoining Width Points Налаштувати суміжні точки ширини
|
||||
Incoming Вхідна
|
||||
@@ -5766,6 +5767,7 @@ variable-list-end {0}, {1} {0} і {1}
|
||||
@msg a linked JavaScript file is outside the read roots зв’язаний файл JavaScript перебуває поза кореневими папками для читання
|
||||
@msg a linked image file is outside the read roots зв’язаний файл зображення перебуває поза кореневими папками для читання
|
||||
@msg a linked file's export folder is outside the read roots папка експорту зв’язаного файлу перебуває поза кореневими папками для читання
|
||||
@msg a linked file's editing data can't be read to check it against the read roots не вдається прочитати дані редагування зв’язаного файлу, щоб звірити їх із кореневими папками для читання
|
||||
@msg automation path rejected: outside the write root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для запису {root}: {path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для запису {roots}: {path}
|
||||
@msg automation path rejected: path is empty шлях автоматизації відхилено: шлях порожній
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -157,6 +157,7 @@
|
||||
Add Used Colors Thêm các màu đã dùng
|
||||
Additional Fonts Folder Thư mục phông bổ sung
|
||||
Additional Plug-ins Folder Thư mục plug-in bổ sung
|
||||
Plug-in Instruction Budget Ngân sách lệnh của plug-in
|
||||
Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau
|
||||
Incoming Phía vào
|
||||
Outgoing Phía ra
|
||||
@@ -5071,6 +5072,7 @@ theme Appearance Giao diện
|
||||
@msg a linked JavaScript file is outside the read roots một tệp JavaScript được liên kết nằm ngoài các thư mục gốc đọc
|
||||
@msg a linked image file is outside the read roots một tệp hình ảnh được liên kết nằm ngoài các thư mục gốc đọc
|
||||
@msg a linked file's export folder is outside the read roots thư mục xuất của một tệp được liên kết nằm ngoài các thư mục gốc đọc
|
||||
@msg a linked file's editing data can't be read to check it against the read roots không thể đọc dữ liệu chỉnh sửa của một tệp được liên kết để kiểm tra với các thư mục gốc đọc
|
||||
@msg the library's file is outside the read roots tệp của thư viện nằm ngoài các thư mục gốc đọc
|
||||
@msg {file} names more than one linked JavaScript file {file} khớp với nhiều hơn một tệp JavaScript được liên kết
|
||||
@msg automation path rejected: outside the write root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc ghi {root}: {path}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -90,6 +90,7 @@
|
||||
Add to Swatches 添加到色板
|
||||
Add Used Colors 添加已用颜色
|
||||
Additional Plug-ins Folder 附加增效工具文件夹
|
||||
Plug-in Instruction Budget 增效工具指令预算
|
||||
Additional Fonts Folder 附加字体文件夹
|
||||
Adjust Adjoining Width Points 调整相邻宽度点
|
||||
Incoming 入侧
|
||||
@@ -5493,6 +5494,7 @@ liquify-list-end {0}, {1} {0}和{1}
|
||||
@msg a linked JavaScript file is outside the read roots 链接的 JavaScript 文件位于所有读取根目录之外
|
||||
@msg a linked image file is outside the read roots 链接的图像文件位于所有读取根目录之外
|
||||
@msg a linked file's export folder is outside the read roots 链接文件的导出文件夹位于所有读取根目录之外
|
||||
@msg a linked file's editing data can't be read to check it against the read roots 无法读取链接文件的编辑数据,因此无法对照读取根目录进行检查
|
||||
@msg automation path rejected: outside the write root {root}: {path} 已拒绝自动化路径:位于写入根目录 {root} 之外:{path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} 已拒绝自动化路径:位于所有写入根目录 {roots} 之外:{path}
|
||||
@msg automation path rejected: path is empty 已拒绝自动化路径:路径为空
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -99,6 +99,7 @@
|
||||
Add to Swatches 新增至色票
|
||||
Add Used Colors 新增使用中的顏色
|
||||
Additional Plug-ins Folder 額外的增效模組資料夾
|
||||
Plug-in Instruction Budget 增效模組指令預算
|
||||
Additional Fonts Folder 額外的字體資料夾
|
||||
Adjust Adjoining Width Points 調整相鄰寬度點
|
||||
Incoming 入側
|
||||
@@ -2960,6 +2961,7 @@ liquify-list-end {0}, {1} {0}和{1}
|
||||
@msg a linked JavaScript file is outside the read roots 連結的 JavaScript 檔案位於所有讀取根目錄之外
|
||||
@msg a linked image file is outside the read roots 連結的影像檔案位於所有讀取根目錄之外
|
||||
@msg a linked file's export folder is outside the read roots 連結檔案的匯出資料夾位於所有讀取根目錄之外
|
||||
@msg a linked file's editing data can't be read to check it against the read roots 無法讀取連結檔案的編輯資料,因此無法對照讀取根目錄進行檢查
|
||||
@msg automation path rejected: outside the write root {root}: {path} 已拒絕自動化路徑:位於寫入根目錄 {root} 之外:{path}
|
||||
@msg automation path rejected: outside the write roots {roots}: {path} 已拒絕自動化路徑:位於所有寫入根目錄 {roots} 之外:{path}
|
||||
@msg automation path rejected: path is empty 已拒絕自動化路徑:路徑是空的
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -795,10 +795,17 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
|
||||
Ok(edit) => edit.unwrap_or(false),
|
||||
Err(e) => return Some(Err(e)),
|
||||
};
|
||||
let keep_art = match opt_bool(p, "keepArt") {
|
||||
Ok(keep) => keep.unwrap_or(false),
|
||||
Err(e) => return Some(Err(e)),
|
||||
};
|
||||
if edit || name.is_some() {
|
||||
if keep_art {
|
||||
return Some(Err("`keepArt` applies only to a new symbol".into()));
|
||||
}
|
||||
crate::dialogs::symbol_options::open_edit(app, name.as_deref())
|
||||
} else {
|
||||
crate::dialogs::symbol_options::open(app)
|
||||
crate::dialogs::symbol_options::open(app, keep_art)
|
||||
}
|
||||
}
|
||||
"ui.newBrush" => crate::dialogs::new_brush::open(app, p.get("ids").cloned()),
|
||||
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user