Merge remote-tracking branch 'upstream/main' into fix/graphic-styles-list-height-2992

This commit is contained in:
Don Omondi committed 2026-11-12 20:51:29 -05:00
commit 2e73558bb4
124 files changed
+7418 -507

No files matched your search

+115
View File
@@ -485,6 +485,88 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
rows
}
/// The distinct colors [`theme_palette`] clusters, at most.
const THEME_CANDIDATES: usize = 4096;
/// The color palette of the weighted colors `samples` (color, weight), for Recolor Artwork's Color
/// Theme Picker: at most `n` colors. The same color given twice counts once with both weights,
/// and past [`THEME_CANDIDATES`] distinct colors, colors close in Lab merge into the heaviest of
/// them first.
/// The colors are grouped as [`cluster`] groups them, each group shows its heaviest color (a color
/// of `samples`, in its own model; on a tie the one given first), and the heaviest group comes
/// first (on a tie the group whose first color was given first). Samples without a positive,
/// finite weight are left out, so no samples give no colors.
pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
let mut index: std::collections::HashMap<ColorKey, usize> = std::collections::HashMap::new();
let mut colors: Vec<Color> = vec![];
let mut weights: Vec<f32> = vec![];
for (c, w) in samples {
if !(w.is_finite() && *w > 0.0) {
continue;
}
let i = *index.entry(ColorKey::of(c)).or_insert_with(|| {
colors.push(*c);
weights.push(0.0);
colors.len() - 1
});
weights[i] += w;
}
if colors.is_empty() || n == 0 {
return vec![];
}
// At most THEME_CANDIDATES colors are clustered: past that, colors in the same cube of Lab
// space merge into the heaviest of them, the cubes doubling in size until few enough remain.
if colors.len() > THEME_CANDIDATES {
let labs: Vec<[f32; 3]> = colors
.iter()
.map(|c| {
let l = c.to_lab();
[l.l, l.a, l.b]
})
.collect();
let mut side = 2.0f32;
loop {
let mut cube: std::collections::HashMap<[i32; 3], usize> = std::collections::HashMap::new();
let (mut top, mut sum): (Vec<usize>, Vec<f32>) = (vec![], vec![]);
for (i, lab) in labs.iter().enumerate() {
let k = lab.map(|v| (v / side).floor() as i32);
match cube.get(&k) {
Some(&j) => {
sum[j] += weights[i];
if weights[i] > weights[top[j]] {
top[j] = i;
}
}
None => {
cube.insert(k, top.len());
top.push(i);
sum.push(weights[i]);
}
}
}
if top.len() <= THEME_CANDIDATES {
colors = top.iter().map(|&i| colors[i]).collect();
weights = sum;
break;
}
side *= 2.0;
}
}
let mut groups: Vec<(f32, usize, Color)> = cluster(&colors, &weights, n)
.into_iter()
.filter_map(|g| {
let total: f32 = g.iter().map(|&i| weights[i]).sum();
let top = g.iter().copied().fold(None::<usize>, |best, i| match best {
Some(b) if weights[b] >= weights[i] => Some(b),
_ => Some(i),
})?;
Some((total, *g.first()?, colors[top]))
})
.collect();
groups.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
groups.into_iter().map(|g| g.2).collect()
}
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
#[derive(Clone, Debug, Default)]
pub struct Palette(Vec<(Color, Lab)>);
@@ -691,6 +773,39 @@ mod tests {
assert!(cluster(&[], &[], 3).is_empty());
}
/// The Color Theme Picker's palette: similar colors merge, each group shows its heaviest
/// color in its own model, and the heaviest group comes first.
#[test]
fn theme_palette_takes_the_heaviest_color_of_each_group_heaviest_first() {
let red = Color::rgb(1.0, 0.0, 0.0);
let pink = Color::rgb(1.0, 0.2, 0.2);
let blue = Color::cmyk(1.0, 0.8, 0.0, 0.0);
let navy = Color::cmyk(1.0, 0.9, 0.0, 0.3);
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 2.5), (red, 0.5)];
// Blue and navy weigh 4.5, and so do red (3 + 0.5, its two samples add up) and pink.
assert_eq!(theme_palette(&samples, 2), vec![red, navy], "a tie: the group given first");
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 1.0)];
assert_eq!(theme_palette(&samples, 2), vec![red, blue], "heaviest group first, its heaviest color");
assert_eq!(theme_palette(&samples, 9).len(), 4, "never more colors than given");
assert_eq!(theme_palette(&samples, 1), vec![red]);
assert!(theme_palette(&samples, 0).is_empty());
assert!(theme_palette(&[(red, 0.0), (blue, f32::NAN), (pink, -1.0)], 3).is_empty(), "no weight, no colors");
assert!(theme_palette(&[], 3).is_empty());
}
/// Past 4,096 distinct colors, close colors merge before clustering: the palette still keeps
/// a heavy color apart from thousands of light ones.
#[test]
fn theme_palette_merges_close_colors_past_its_candidate_limit() {
let mut samples: Vec<(Color, f32)> = (0..20_000).map(|i| (Color::rgb(0.0, 0.0, 0.3 + 0.7 * i as f32 / 20_000.0), 0.001)).collect();
samples.extend((0..20_000).map(|i| (Color::rgb(1.0, 0.8 * i as f32 / 20_000.0, 0.0), 0.0001)));
samples.push((Color::rgb(0.0, 1.0, 0.0), 50.0));
let p = theme_palette(&samples, 3);
assert_eq!(p.len(), 3);
assert_eq!(p[0], Color::rgb(0.0, 1.0, 0.0), "the heavy green first, exactly as given");
assert!(p[1].to_hsb()[0] > 180.0 && p[2].to_hsb()[0] < 90.0, "then the blues, then the reds and oranges: {p:?}");
}
#[test]
fn hue_shift_with_own_model_puts_every_colour_of_the_row_in_the_new_model() {
let to = Color::cmyk(0.0, 1.0, 1.0, 0.0);
+3 -3
View File
@@ -569,7 +569,7 @@ fn clip_contains(clip: &Node, p: Point) -> bool {
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
/// [`clip_contains`].
fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
let frame = |n: &Node| {
let b = n.geometric_bounds()?;
Some(Node::path(n.id, vectorcraft_geom::shapes::rectangle(b), Default::default()))
@@ -640,7 +640,7 @@ fn source_of(n: &Node, scope: Option<NodeId>) -> bool {
/// Do clicks and marquees skip the child `i` of `parent` with `scope` isolated? For a Shaper
/// Group that is its original shapes (its first child), or, in Construction mode, when they are
/// isolated, the art the group shows.
fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
pub fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
parent.extras().shaper.is_some() && (i == 0) != source_of(parent, scope)
}
@@ -1356,7 +1356,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
/// when the marquee misses it); otherwise it is all of `r`.
fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
match parent.children().and_then(|c| c.first()) {
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
_ => Some(r),
+1 -1
View File
@@ -51,7 +51,7 @@ pub mod overprint;
pub mod pattern;
pub mod perspective;
mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC};
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub mod placed_document;
pub mod plugin_data;
pub mod profiles;
+72
View File
@@ -11,6 +11,10 @@ use crate::ImageBlob;
/// address and aborts when an allocation fails, so it keeps the decoder's own 512 MB.
pub const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), and
/// the pixel centres to take from it ([`ImageBlob::sample_pixels`]).
pub type PixelPick<'a> = (Option<[f64; 4]>, &'a dyn Fn(f64, f64) -> bool);
/// The pixels of encoded image `bytes` as RGBA; `None` when they can't be decoded, would take
/// more than `max` bytes as RGBA, or need more than `max` bytes to decode. The size is read from
/// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter
@@ -61,6 +65,49 @@ impl ImageBlob {
Some(Self::png(png))
}
/// For each of `picks`, at most `budget` of the image's pixels (at least one), spread evenly
/// in rows and columns over the pick's box (`[u0, v0, u1, v1]`, where 0 to 1 spans the
/// image's width and height from the top left; clipped to the image; `None`: the whole image),
/// as straight RGBA. Only pixels whose centres the pick's function takes (in the same 0 to 1
/// units) are given. The image is decoded once for all the picks. `None` when it can't be
/// decoded within [`MAX_RASTER_ALLOC`].
pub fn sample_pixels(&self, picks: &[PixelPick<'_>], budget: usize) -> Option<Vec<Vec<[u8; 4]>>> {
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
let (w, h) = img.dimensions();
let (fw, fh) = (f64::from(w), f64::from(h));
let span = |a: f64, b: f64, n: f64| {
let (a, b) = (a.min(b), a.max(b));
((a * n).floor().clamp(0.0, n) as u32, (b * n).ceil().clamp(0.0, n) as u32)
};
let sample = |area: Option<[f64; 4]>, keep: &dyn Fn(f64, f64) -> bool| {
let [u0, v0, u1, v1] = area.unwrap_or([0.0, 0.0, 1.0, 1.0]);
let (x0, x1) = span(u0, u1, fw);
let (y0, y1) = span(v0, v1, fh);
if x0 >= x1 || y0 >= y1 {
return vec![];
}
// Rows and columns in proportion to the box, at most `budget` cells in all.
let (bw, bh, budget) = (f64::from(x1 - x0), f64::from(y1 - y0), budget.max(1) as f64);
let (sx, sy) = if bw * bh <= budget {
(1, 1)
} else {
let rows = (budget * bh / bw).sqrt().floor().clamp(1.0, bh.min(budget));
let cols = (budget / rows).floor().clamp(1.0, bw);
((bw / cols).ceil() as usize, (bh / rows).ceil() as usize)
};
let mut out = vec![];
for y in (y0..y1).step_by(sy) {
for x in (x0..x1).step_by(sx) {
if keep((f64::from(x) + 0.5) / fw, (f64::from(y) + 0.5) / fh) {
out.push(img.get_pixel(x, y).0);
}
}
}
out
};
Some(picks.iter().map(|(area, keep)| sample(*area, *keep)).collect())
}
/// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and
/// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct
/// color. `None` when the image can't be decoded, or when its file stores grayscale already
@@ -276,6 +323,31 @@ mod tests {
image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
}
/// Sampling reads the pixels of a box of the image, spread to about the budget, and only those
/// whose centres `keep` takes.
#[test]
fn sampled_pixels_stay_in_their_box_and_budget() {
// 4 × 2: a red left half and a blue right half.
let (r, b) = ([255, 0, 0, 255], [0, 0, 255, 255]);
let img = blob(&[r, r, b, b, r, r, b, b], 4, 2);
let any = |_: f64, _: f64| true;
let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, &any)], budget).unwrap().remove(0);
assert_eq!(one(&img, None, 100).len(), 8, "the budget covers every pixel");
assert_eq!(one(&img, Some([0.5, 0.0, 1.0, 1.0]), 100), vec![b; 4], "the right half");
assert_eq!(one(&img, Some([1.0, 1.0, 0.5, 0.0]), 100), vec![b; 4], "a box given backwards");
assert!(one(&img, Some([2.0, 0.0, 3.0, 1.0]), 100).is_empty(), "outside the image");
assert_eq!(one(&img, None, 2).len(), 2, "every second pixel of every second row");
assert_eq!(one(&img, None, 0), vec![r], "a budget of 0 counts as 1");
let left = |u: f64, _: f64| u < 0.5;
let both = img.sample_pixels(&[(None, &left), (Some([0.5, 0.0, 1.0, 1.0]), &any)], 100).unwrap();
assert_eq!(both, vec![vec![r; 4], vec![b; 4]], "several picks, each with the centres its function takes");
// A narrow image keeps to the budget too.
let tall = blob(&vec![r; 5000], 1, 5000);
let n = one(&tall, None, 100).len();
assert!((50..=100).contains(&n), "{n} pixels");
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, &any)], 100).is_none());
}
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
/// other pixels, and the decoder makes them transparent.
fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> {
+1 -1
View File
@@ -17,7 +17,7 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
+20 -1
View File
@@ -34,6 +34,16 @@ pub struct CharStyle {
/// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect.
#[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")]
pub kerning_before: f64,
/// Insert Aki Left (Character panel, East Asian options): space added before the character in
/// reading order, in 1/1000 em as [`Self::tracking`], 0 to 1000. Before is on the left in
/// left-to-right type, on the right in right-to-left type and above in vertical type. A
/// cluster takes the value of its first character, and full justification leaves it as it is.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "akiLeft", skip_serializing_if = "crate::skip::is_default")]
pub aki_left: f64,
/// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`].
#[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")]
pub aki_right: f64,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
pub optical_kerning: bool,
@@ -404,6 +414,9 @@ fn hundred() -> f64 {
100.0
}
/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em.
pub const MAX_AKI: f64 = 1000.0;
pub(super) fn yes() -> bool {
true
}
@@ -420,6 +433,8 @@ impl Default for CharStyle {
tracking: 0.0,
kerning: None,
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
optical_kerning: false,
baseline_shift: 0.0,
h_scale: 100.0,
@@ -468,7 +483,8 @@ impl CharStyle {
/// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way)
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
/// offsets are kept as the baseline shift is.
/// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to
/// [`MAX_AKI`], and one that is not a number becomes 0.
pub fn keep_dimensions_in_range(&mut self) {
let default = Self::default();
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
@@ -480,6 +496,9 @@ impl CharStyle {
self.baseline_shift = shift(self.baseline_shift);
self.tcy_up_down = shift(self.tcy_up_down);
self.tcy_left_right = shift(self.tcy_left_right);
let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) };
self.aki_left = aki(self.aki_left);
self.aki_right = aki(self.aki_right);
}
/// Do the characters draw a stroke (a paint and a positive weight)?
pub fn has_stroke(&self) -> bool {
+4
View File
@@ -490,6 +490,8 @@ impl crate::Document {
st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift);
st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down);
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
st.keep_dimensions_in_range();
let kept = [
("size", Some(st.size)),
@@ -498,6 +500,8 @@ impl crate::Document {
("baseline_shift", Some(st.baseline_shift)),
("tcyUpDown", Some(st.tcy_up_down)),
("tcyLeftRight", Some(st.tcy_left_right)),
("akiLeft", Some(st.aki_left)),
("akiRight", Some(st.aki_right)),
("leading", st.leading),
];
for (k, v) in kept {
+3 -1
View File
@@ -357,7 +357,7 @@ impl ParaList {
/// The style the marker is set in: `first` (the style of the paragraph's first character)
/// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning,
/// tate-chu-yoko, underline and strikethrough.
/// Insert Aki, tate-chu-yoko, underline and strikethrough.
pub fn marker_style(first: &CharStyle) -> CharStyle {
CharStyle {
baseline_shift: 0.0,
@@ -366,6 +366,8 @@ impl ParaList {
tracking: 0.0,
kerning: None,
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
optical_kerning: first.optical_kerning,
tate_chu_yoko: false,
underline: false,
+37
View File
@@ -92,6 +92,43 @@ fn font_height_reference_is_saved_only_when_not_the_em_box() {
assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().font_height_reference, FontHeightReference::EmBox);
}
/// Insert Aki Left and Right are 0 by default and saved only when not 0, each side on its own;
/// styles written before them read as 0, and a value out of range from a file is kept from 0 to one
/// em.
#[test]
fn insert_aki_is_saved_only_when_set() {
let st = CharStyle::default();
assert_eq!((st.aki_left, st.aki_right), (0.0, 0.0));
let saved = serde_json::to_value(&st).unwrap();
assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none());
for set in [
CharStyle { aki_left: 250.0, ..CharStyle::default() },
CharStyle { aki_right: 500.0, ..CharStyle::default() },
CharStyle { aki_left: 125.5, aki_right: 1000.0, ..CharStyle::default() },
] {
let saved = serde_json::to_value(&set).unwrap();
assert_eq!(saved.get("akiLeft").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_left);
assert_eq!(saved.get("akiRight").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_right);
assert_eq!(saved.get("akiLeft").is_some(), set.aki_left != 0.0);
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
}
let old = serde_json::to_value(&st).unwrap();
let read = serde_json::from_value::<CharStyle>(old).unwrap();
assert_eq!((read.aki_left, read.aki_right), (0.0, 0.0));
let mut damaged = CharStyle { aki_left: -20.0, aki_right: 4000.0, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
let mut damaged = CharStyle { aki_left: f64::NAN, aki_right: f64::INFINITY, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
// A character style from a file is kept in range the same way.
let mut d = crate::Document::new(100.0, 100.0);
let attrs = serde_json::json!({"akiLeft": 5000, "akiRight": -1});
d.char_styles.push(TextStyleDef { name: "Spaced".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
d.keep_type_values_in_range();
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
}
/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its
/// script's block; every system saves under its id, which reads back, and other names are refused.
#[test]
+2
View File
@@ -26,3 +26,5 @@ serde_json = { workspace = true }
[dev-dependencies]
vectorcraft-color = { workspace = true }
# A face built in code from the bundled Source Sans 3 (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
+1 -1
View File
@@ -689,7 +689,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
}
/// A path node of `id` on `path` (filled under `rule`) painted by `ap`.
fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
pub(crate) fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
let mut n = Node::path(id, path, ap);
if let NodeKind::Path { rule: r, .. } = &mut n.kind {
*r = rule;
+55 -6
View File
@@ -594,7 +594,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
if is_container(n) {
return group_art(n, expand);
}
let (path, _) = profile(n)?;
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
let mut children = vec![];
let mut copies = 0;
@@ -620,15 +620,17 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining = crate::without_geometry(&remaining);
// The object's Transform effects, applied to the path above, transform the items' raster
// effects too.
let mut items: Vec<AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect();
// effects too. Each copy keeps its item beside it, which plug-in effects are told they sit
// on.
let originals: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).collect();
let mut items: Vec<AppearanceItem> = originals.iter().map(|i| (*i).clone()).collect();
crate::raster::follow_paints(&mut items, &n.appearance.effects);
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for item in &items {
for (original, item) in originals.into_iter().zip(&items) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
let fx = item.effects().get(index)?;
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
@@ -640,7 +642,8 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
}
children.push(Arc::new(art));
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
}
}
children.splice(0..0, shadows);
@@ -1022,6 +1025,52 @@ mod tests {
assert!(surface.children().unwrap().iter().all(|c| c.opacity == 1.0 && !has_revolve(c)));
}
#[test]
fn a_fill_without_the_revolve_keeps_the_even_odd_hole() {
use vectorcraft_geom::FillRule;
use vectorcraft_geom::hit::fill_contains;
// Two nested squares drawn in the same direction: only the even-odd rule leaves a hole.
let [outer, inner] = [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
let mut b = BezPath::new();
b.move_to((lo, lo));
b.line_to((hi, lo));
b.line_to((hi, hi));
b.line_to((lo, hi));
b.close_path();
PathData::from_bezpath(&b)
});
let flat = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.1, 0.3, 0.9))));
for id in [REVOLVE, CLASSIC_REVOLVE] {
let mut top = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.8, 0.2, 0.1))));
top.effects_mut().push(crate::new_effect(id, &json!({})).unwrap());
let appearance = Appearance { items: vec![flat.clone(), top], ..Default::default() };
let members = vec![
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
];
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
compound.appearance = appearance.clone().into();
let both = PathData::new(outer.subpaths.iter().chain(&inner.subpaths).cloned().collect());
let path = crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance);
for (n, shape) in [(compound, "compound path"), (path, "path")] {
for (art, how) in [(revolve_art(&n), "live"), (expand_revolve_art(&n), "expanded")] {
let what = format!("{id} on the top fill of a {shape}, {how}");
let art = art.unwrap_or_else(|| panic!("{what}"));
let children = art.children().unwrap();
let plain: Vec<usize> = (0..children.len())
.filter(|&i| children[i].appearance.items == [flat.clone()] && children[i].path_data().is_some())
.collect();
let [index] = plain[..] else { panic!("{what}: one flat child, got {plain:?}") };
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
let bez = path.to_bezpath();
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
assert!(index + 1 < children.len(), "{what}: the revolved art is drawn above");
}
}
}
}
#[test]
fn export_bakes_faces_with_unique_ids_and_no_revolve_effects() {
let mut d = Document::new(300.0, 300.0);
let mut n = profile_node();
+2 -1
View File
@@ -1197,7 +1197,8 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
shadows.extend(shadow.into_iter().map(with_later));
children.extend(surfaces.into_iter().map(with_later));
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
}
}
children.splice(0..0, shadows);
+62
View File
@@ -457,6 +457,68 @@ fn transparency_stays_on_the_whole_surface_and_items_take_their_own_effect() {
assert!(matches!(surfaces[1].kind, NodeKind::Path { .. }));
}
/// Two nested squares drawn in the same direction, so only the even-odd rule leaves a hole.
fn nested_squares() -> [PathData; 2] {
[(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
let mut b = BezPath::new();
b.move_to((lo, lo));
b.line_to((hi, lo));
b.line_to((hi, hi));
b.line_to((lo, hi));
b.close_path();
PathData::from_bezpath(&b)
})
}
/// The nested squares as an even-odd compound path and as one even-odd path, painted by `items`.
fn even_odd_shapes(items: Vec<AppearanceItem>) -> [Node; 2] {
let [outer, inner] = nested_squares();
let appearance = Appearance { items, ..Default::default() };
let children = vec![
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
];
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd });
compound.appearance = appearance.clone().into();
let both = PathData::new(outer.subpaths.into_iter().chain(inner.subpaths).collect());
[compound, crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance)]
}
/// Check that `art` draws `item` as one flat child: an even-odd path with a hole in the middle,
/// below the 3D art after it.
fn assert_flat_item_keeps_the_hole(art: &Node, item: &AppearanceItem, what: &str) {
use vectorcraft_geom::hit::fill_contains;
let children = art.children().unwrap();
let flat: Vec<usize> =
(0..children.len()).filter(|&i| children[i].appearance.items == [item.clone()] && children[i].path_data().is_some()).collect();
let [index] = flat[..] else { panic!("{what}: one flat child, got {flat:?}") };
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
let bez = path.to_bezpath();
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
assert!(index + 1 < children.len(), "{what}: the 3D art is drawn above");
}
#[test]
fn a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole() {
let red = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(RED)));
let blue = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(BLUE)));
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 4.0));
for id in SOLIDS {
// The top fill and then the top stroke take the effect; the fill below stays flat.
for (top, on) in [(&red, "fill"), (&stroke, "stroke")] {
let mut lifted = top.clone();
lifted.effects_mut().push(fx(id, json!({})));
for (n, shape) in even_odd_shapes(vec![blue.clone(), lifted]).into_iter().zip(["compound path", "path"]) {
let what = format!("{id} on the top {on} of a {shape}");
let art = solid_art(&n).unwrap_or_else(|| panic!("{what}"));
assert_flat_item_keeps_the_hole(&art, &blue, &what);
}
}
}
}
#[test]
fn export_and_expand_bake_faces_with_their_own_ids() {
for id in SOLIDS {
+21 -3
View File
@@ -6,20 +6,38 @@
use std::sync::Arc;
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Point, Rect, Shape};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
/// The largest distance between the edges of `a` and `b`.
fn off(a: Rect, b: Rect) -> f64 {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
}
/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or
/// system fonts.
fn type_in_test_face() -> TextObject {
assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads");
TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() })
}
/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph.
fn outline_box(t: &TextObject) -> Rect {
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let outlines: Vec<Rect> = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect();
assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline");
outlines.into_iter().reduce(|a, b| a.union(b)).unwrap()
}
#[test]
fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() {
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
let t = type_in_test_face();
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
let laid = n.geometric_bounds().unwrap();
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
let ink = outline_box(&t);
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap();
assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {ink:?}");
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
+6 -1
View File
@@ -426,8 +426,13 @@ pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 {
p.get(key).and_then(Value::as_f64).unwrap_or(default)
}
/// The number `p` gives for `key`. A missing key or null is "missing number `{key}`"; any other
/// value, such as `"40"`, is "`{key}` must be a number, not {v}", as [`number_or`] words it.
pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`")))
match p.get(key) {
None | Some(Value::Null) => Err(bad(cmd, format!("missing number `{key}`"))),
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
}
}
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other
/// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}".
+6 -5
View File
@@ -12,7 +12,7 @@ use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, Para
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
use crate::cmd::fonts::{art_texts_of, edit_art_texts_of};
use crate::cmd::textedit::{editing_range, editing_story};
use crate::cmd::typecmd::refresh_bounds;
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Missing Fonts…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in its opacity masks and in the art of its symbols and patterns included, hidden or locked type and disabled masks too) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
has_doc,
replace_fonts
),
@@ -982,8 +982,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
// The type in the symbols' art too, which exports name when its font is missing.
if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) {
// The type in opacity masks and in the art of symbols and patterns too, hidden or locked type
// included, which exports name when its font is missing.
if ids.is_empty() && !art_texts_of(d).into_iter().any(|(_, t, _)| lacks(t)) {
return Err(EngineError::Other("No fonts are missing".into()));
}
let runs = s.edit("Replace Missing Fonts", |d, _| {
@@ -1008,7 +1009,7 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
replace(t);
}
}
edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace);
edit_art_texts_of(d, &lacks, &mut replace);
Ok(runs)
})?;
Ok(json!({ "runs": runs, "font": family }))
@@ -415,3 +415,53 @@ fn replace_missing_fonts_reaches_the_type_in_symbols() {
s.execute("symbol.exitEditing", &json!({})).unwrap();
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
}
/// Replace Missing Fonts reaches the type in opacity masks (of a hidden object, disabled, in a
/// symbol's art) and in a pattern swatch nothing paints with, and the export warning, the missing
/// fonts list and Find Font name that type's font until it is replaced.
#[test]
fn replace_missing_fonts_reaches_the_type_in_masks_and_patterns() {
let mut s = session();
let mask = |s: &mut Session, owner: NodeId, art: NodeId| {
s.edit("Mask", |d, _| {
let art = d.remove(art)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
};
let lost = |s: &mut Session| text(s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"}));
let rect =
|s: &mut Session| NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
let (hidden, disabled, in_symbol) = (rect(&mut s), rect(&mut s), rect(&mut s));
for owner in [hidden, disabled, in_symbol] {
let t = lost(&mut s);
mask(&mut s, owner, t);
}
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [disabled.0]})).unwrap();
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
let t = lost(&mut s);
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
select(&mut s, &[t]);
s.execute("edit.clear", &json!({})).unwrap();
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in masks, a symbol and a pattern");
let missing = |s: &Session| crate::cmd::fontfiles::missing_fonts(&s.doc().unwrap().doc).into_iter().map(|f| f.family).collect::<Vec<_>>();
assert_eq!(missing(&s), ["No Such Font Family"]);
assert!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc).is_some_and(|w| w.contains("No Such Font Family")));
let listed = s.execute("text.fonts", &json!({})).unwrap();
assert_eq!((listed[0]["family"].as_str(), listed[0]["objects"].as_u64()), (Some("No Such Font Family"), Some(4)), "{listed}");
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap();
assert_eq!(r["runs"].as_u64(), Some(4), "{r}");
assert_eq!(steps(&s), before + 1);
assert!(missing(&s).is_empty());
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing");
assert_eq!(steps(&s), before + 1);
}
+1 -1
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Weed Box and Lines…",
["Object", "Plug-ins", "Cutting Tools"],
None,
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt (instead of count: as few lines as keep them at most this far apart), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt more than 0 and at most 100000 (instead of count, never with it: as few lines as keep them at most this far apart, up to 1000 each way), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
has_selection,
weed
)]
@@ -723,12 +723,13 @@ pub(super) fn lines(region: &Region, outline: &[Segment], frame: Rect, n: Counts
continue;
}
// The lines (0-based) each outline segment comes within `gap` of: lines k (1-based) lie at
// v0 + k·step.
// v0 + k·step. The range is widened by a small tolerance so that a line whose position
// rounds just past a segment's end is still measured; `near` drops lines the segment misses.
let reach = |&(a, b): &Segment| {
let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1);
let (lo, hi) = (va.min(vb) - gap, va.max(vb) + gap);
let first = ((lo - v0) / step).ceil().max(1.0);
let last = ((hi - v0) / step).floor().min(count as f64);
let first = ((lo - v0) / step - 1e-9).ceil().max(1.0);
let last = ((hi - v0) / step + 1e-9).floor().min(count as f64);
if step > 0.0 && first <= last { (first as usize - 1)..(last as usize) } else { 0..0 }
};
// The outlines near each line, found once for all of them, by index into `outline`.
@@ -541,6 +541,24 @@ fn indexed_crossings_find_the_same_stretches() {
}
}
/// An outline that lies on a weeding line stops it even when the line's position rounds just past
/// the outline's: the one line across 0.1 to 0.5 lies at 0.1 + 0.2, which is 0.30000000000000004,
/// and (0.30000000000000004 - 0.1) / 0.2 is 1.0000000000000002.
#[test]
fn an_outline_on_a_rounded_line_position_stops_the_line() {
let doc = vectorcraft_doc::Document::new(800.0, 600.0);
let c = 0.1 + 0.2;
let mut p = BezPath::new();
p.move_to((20.0, c));
p.line_to((80.0, c));
let n = Node::path(NodeId(1), PathData::from_bezpath(&p), Appearance::default());
let region = super::geometry::Reader::new(&doc).read(&[&n]).unwrap().unwrap();
let outline = region.outline().unwrap();
let counts = super::geometry::Counts { horizontal: 1, vertical: 0 };
let pieces = super::geometry::lines(&region, &outline, Rect::new(0.0, 0.1, 100.0, 0.5), counts, 0.0, 100).unwrap();
assert_eq!(pieces, [(Point::new(0.0, c), Point::new(20.0, c)), (Point::new(80.0, c), Point::new(100.0, c))]);
}
#[test]
fn art_nested_too_deep_is_refused() {
// A rectangle inside `levels` groups, each holding the next. A document keeps none this deep,
+13 -4
View File
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Align",
[],
None,
"{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}",
"{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it, art inside two of them with the first by index, which may stay; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}",
has_doc,
align
),
@@ -114,18 +114,27 @@ fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option<f64>) -> Result<Option<
}
/// Moves each artboard of `moves` by its offset as undo step `label`, with its guides and, when
/// `b` says so, the art inside it. Locked artboards stay where they are. When no artboard moves
/// `b` says so, the art inside it; art inside two of the artboards `b` names goes with the one
/// first in artboard order, and stays when that one stays. Locked artboards stay where they are.
/// When no artboard moves
/// more than 1e-9 pt on either axis, the document and its undo history stay as they are. The edit
/// fails with nothing changed when an artboard would end up past the canvas, as every edit does.
fn apply(s: &mut Session, label: &str, p: &Value, b: &Boards, moves: &[(usize, Vec2)]) -> Result<Value> {
let d = &s.doc()?.doc;
let moves: Vec<(usize, Vec2)> =
let mut moves: Vec<(usize, Vec2)> =
moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect();
// In artboard order, as the other artboard edits take them, whatever order the Distribute
// commands spaced them in.
moves.sort_by_key(|(i, _)| *i);
let moved: Vec<usize> = moves.iter().map(|(i, _)| *i).collect();
if moves.is_empty() {
return Ok(json!({ "moved": moved }));
}
let arts = artboards_art(s, &moved, b.move_art, b.locked_art, true)?;
// The art of every artboard named, those that stay included, so that art on overlapping
// artboards goes with the first by index; then that of the artboards that move.
let named: Vec<usize> = b.items.iter().map(|(i, _)| *i).collect();
let arts: Vec<(usize, Vec<NodeId>)> =
artboards_art(s, &named, b.move_art, b.locked_art, true)?.into_iter().filter(|(i, _)| moved.contains(i)).collect();
let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() };
s.edit(label, |d, _| {
@@ -265,6 +265,39 @@ fn bad_params_are_errors() {
assert_eq!((undo_steps(&s), corners(&s)), (steps, before));
}
/// Art inside two overlapping artboards moves with the one first in artboard order, as with the
/// other artboard edits, even when Distribute spaces the other one first: artboard 2 at x 140 is
/// left of artboard 1 at x 200, and the square inside both goes with artboard 1.
#[test]
fn art_on_overlapping_artboards_moves_with_the_first_by_index() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 140, "y": 0, "width": 100, "height": 100})).unwrap();
let sq = s.execute("shape.rectangle", &json!({"x": 210, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.none", &json!({})).unwrap();
let p = json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 10});
assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [1, 2]}));
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 0.0), (110.0, 0.0)]);
assert_eq!(corner(&s, sq), (230.0, 10.0), "with artboard 1, 20 pt to the right");
}
/// Art inside an artboard that stays and a later one that moves stays with the first: artboard 2
/// overlaps artboard 0, and aligning it to artboard 0 leaves the square inside both in place.
#[test]
fn art_shared_with_an_artboard_that_stays_stays() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 60, "y": 0, "width": 100, "height": 100})).unwrap();
let sq = s.execute("shape.rectangle", &json!({"x": 70, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.none", &json!({})).unwrap();
let p = json!({"indices": [0, 2], "horizontal": "left", "to": "artboard", "artboard": 0});
assert_eq!(s.execute("artboard.align", &p).unwrap(), json!({"moved": [2]}));
assert_eq!(corners(&s)[2], (0.0, 0.0));
assert_eq!(corner(&s, sq), (70.0, 10.0), "with artboard 0, which stays");
}
/// An artboard's own guides move with it.
#[test]
fn an_artboards_guides_move_with_it() {
+28 -70
View File
@@ -712,15 +712,6 @@ fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
relinked(&Relink::default(), ours) == relinked(r, theirs)
}
/// Does brush `b`'s art show symbols or patterns?
fn shows_definitions(b: &Brush) -> bool {
let mut found = false;
for a in b.art() {
node_refs(a, &mut |r| found |= matches!(r, Ref::Name(Res::Symbol | Res::Pattern, _)));
}
found
}
/// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and
/// given to it under the name pasting adds it as.
#[derive(Clone, Debug, PartialEq)]
@@ -754,7 +745,7 @@ impl SymbolOptions {
}
/// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or
/// brush (placed with the others only when they are placed in use order) to place
/// brush to place
/// ([`Clipboard::import_used`]).
#[derive(Clone, Copy)]
enum Def<'c> {
@@ -1070,49 +1061,40 @@ impl Clipboard {
}
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
/// pasted copies relink to them. An error, with `d` unchanged, when a pasted SVG filter finds no
/// free name ([`Self::filter_links`]).
/// pasted copies relink to them. Each style, symbol, pattern and brush is placed after those it
/// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added
/// under a free name ("Dots 2") is compared and added with that name. An error, with `d`
/// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]).
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
self.import_used(d, &self.used(), choices, same_doc, false)
self.import_used(d, &self.used(), choices, same_doc)
}
/// [`Self::import_into`] for the resources `used` names. The character and paragraph styles
/// come before the symbols and patterns, whose art may set type in them; with `in_use_order`,
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
/// of definitions that use each other is matched on its own ([`loop_groups`]).
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Result<Imported> {
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
/// compared and relinked with their names here, and each loop of definitions that use each
/// other is matched on its own ([`loop_groups`]). Pasted back into its own document
/// (`same_doc`), each definition of a loop is the document's of its name.
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
let mut out = Imported::default();
out.relink.filters = self.filter_links(d, same_doc)?;
self.import_images(d, used, same_doc, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
// they may brush; the others once those are in. With `in_use_order`, the brushes are
// placed in use order with the others.
let mut added_brushes: HashSet<String> =
if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() };
let mut defs: Vec<Def<'_>> = vec![];
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
}
defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name))));
defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern));
if in_use_order {
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
}
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
// Groups to place in order; true for a loop of definitions that use each other.
let groups: Vec<(Vec<Def<'_>>, bool)> = if in_use_order {
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
std::iter::once((order, false)).chain(loops).collect()
} else {
vec![(defs, false)]
};
// Styles (their colors relinked first), symbols and patterns (compared once relinked,
// symbols with their options too). The symbols and patterns added are relinked at the end,
// when every new name and graphic style id is known; with `in_use_order`, so are the
// styles added, which a loop of uses may place before a pattern they paint with.
let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]);
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
let groups: Vec<(Vec<Def<'_>>, bool)> = std::iter::once((order, false)).chain(loops).collect();
// Styles (their colors relinked first), symbols, patterns and brushes (compared once
// relinked, symbols with their options too). The styles, symbols, patterns and brushes
// added are relinked at the end, when every new name and graphic style id is known: a loop
// of uses may place one before a definition it uses.
let (mut added_symbols, mut added_patterns, mut added_brushes, mut added_styles) = (HashSet::new(), HashSet::new(), HashSet::new(), vec![]);
// Each definition, whether it is in a loop, and the loop it starts.
let steps = groups
.iter()
@@ -1122,8 +1104,8 @@ impl Clipboard {
let mut fresh = false;
// The names in the document of the loop being placed, when it has them all at once.
let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new();
// The document's brush library, read the first time a brush is placed in use order and
// stored again after each brush added; nothing else in the loop changes it.
// The document's brush library, read the first time a brush is placed and stored again
// after each brush added; nothing else in the loop changes it.
let mut library: Option<Vec<Brush>> = None;
for (def, looped, starts) in steps {
fresh &= looped;
@@ -1131,8 +1113,9 @@ impl Clipboard {
matched.clear();
}
// A loop of uses that the document has all at once is known under those names before
// its definitions are compared.
if let Some(group) = starts {
// its definitions are compared. In its own document, each definition is the
// document's of its name, as outside a loop.
if let Some(group) = starts.filter(|_| !same_doc) {
matched.clear();
match names_of_loop(d, group, &out.relink) {
Some(names) => {
@@ -1161,7 +1144,7 @@ impl Clipboard {
out.relink.attrs(&mut s.attrs);
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b);
if in_use_order && let Some(name) = p.new_name(&def.name) {
if let Some(name) = p.new_name(&def.name) {
added_styles.push((r, name, def));
}
out.placed(r, &def.name, &p);
@@ -1215,9 +1198,6 @@ impl Clipboard {
}
}
}
if !in_use_order {
added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out));
}
self.import_graphic_styles(d, used, same_doc, &mut out);
for (r, name, def) in added_styles {
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
@@ -1338,28 +1318,6 @@ impl Clipboard {
}
}
/// The brushes whose art shows symbols or patterns (`late`), or the others: each one the
/// document has (its art compared once relinked) is used, the others are added. → the names of
/// those added, whose art is relinked at the end.
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, late: bool, out: &mut Imported) -> Vec<String> {
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name) && shows_definitions(b) == late).collect();
if brushes.is_empty() {
return vec![];
}
let mut lib = vectorcraft_brush::library(d);
let mut added = vec![];
for b in brushes {
let r = &out.relink;
let p = place(&mut lib, b, same_doc, |ours, theirs| same_brush(r, ours, theirs));
added.extend(p.new_name(&b.name));
out.placed(Res::Brush, &b.name, &p);
}
if !added.is_empty() {
vectorcraft_brush::store(d, &lib);
}
added
}
/// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint
/// swatches of the tints used and the gradient swatches.
fn import_swatches(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, out: &mut Imported) {
@@ -1444,7 +1402,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true)?;
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
let mut placed: Vec<LoadedStyle> = vec![];
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
for s in list {
+77 -1
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
has_doc,
info
),
@@ -627,6 +627,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
// The document's fonts include those of the type in opacity masks and in the art of its
// symbols and patterns, as Find Font lists them.
if !selection_only {
fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style))));
}
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
@@ -756,6 +761,40 @@ mod tests {
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
}
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
#[test]
fn info_fonts_include_masks_symbols_and_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
let text = |s: &mut Session, font: &str| id(s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": font})).unwrap());
let rect = |s: &mut Session| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap());
let (masked, in_symbol) = (rect(&mut s), rect(&mut s));
for (owner, font) in [(masked, "Mask Family"), (in_symbol, "Symbol Mask Family")] {
let t = text(&mut s, font);
s.edit("Mask", |d, _| {
let art = d.remove(t)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
}
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
let t = text(&mut s, "Pattern Family");
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let plain = text(&mut s, "Source Sans 3");
let fonts = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["fonts"].clone();
assert_eq!(
fonts(&mut s, json!({})),
json!(["Mask Family Regular", "Pattern Family Regular", "Source Sans 3 Regular", "Symbol Mask Family Regular"])
);
s.execute("select.set", &json!({"ids": [plain.0]})).unwrap();
assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"]));
}
/// Document Info › Objects gives the paths' total length in the document's units (#1958): an
/// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't.
#[test]
@@ -1379,6 +1418,43 @@ mod tests {
assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]);
}
/// Spot Color Objects leaves out a fill or stroke at an opacity of 0, which prints no ink, and
/// keeps the object while another of its fills or strokes prints the spot color. Gradient
/// Objects leaves out a clear gradient fill as well.
#[test]
fn spot_color_objects_skip_clear_fills_and_strokes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [rect], "swatch": "Ink"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [rect], "swatch": "Ink"})).unwrap();
let ramp = s.execute("shape.rectangle", &json!({"x": 50, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let stops = json!([{"offset": 0, "color": "#000", "swatch": "Ink"}, {"offset": 1, "color": "#fff", "swatch": "Ink"}]);
s.execute("paint.setFill", &json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap();
let items = |s: &Session, id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().appearance.items.clone();
let spots = |s: &mut Session| {
let i = s.execute("document.info", &json!({})).unwrap();
let mut ids: Vec<u64> = i["spotObjects"].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect();
ids.sort_unstable();
(ids, i["objects"]["spots"].as_u64(), i["objects"]["gradients"].as_u64())
};
// The rectangle's fill at an opacity of 0: its stroke still prints the spot color.
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
let fill = items(&s, &rect).iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": fill, "opacity": 0})).unwrap();
assert_eq!(spots(&mut s), (vec![rect.as_u64().unwrap(), ramp.as_u64().unwrap()], Some(2), Some(1)));
// Every fill and stroke of both objects at an opacity of 0.
for id in [&rect, &ramp] {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for index in 0..items(&s, id).len() {
s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap();
}
}
assert_eq!(spots(&mut s), (vec![], None, None));
}
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
/// it counts that object once.
+31 -11
View File
@@ -408,15 +408,31 @@ pub(crate) fn anti_alias(id: &str) -> std::result::Result<AntiAlias, String> {
/// The `useArtboards` param of a PDF, AI, DXF or raster export (SVG has its own): `true` writes every
/// chosen artboard (default all), `false` the bounds of the visible art instead, absent one
/// artboard (raster, DXF) or the chosen pages (PDF, AI).
fn use_artboards(p: &Value) -> Result<Option<bool>> {
/// artboard (raster, DXF) or the chosen pages (PDF, AI). Errors name the command `cmd`.
pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result<Option<bool>> {
match p.get("useArtboards") {
None | Some(Value::Null) => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(v) => Err(bad(C, format!("useArtboards must be true or false, not {v}"))),
Some(v) => Err(bad(cmd, format!("useArtboards must be true or false, not {v}"))),
}
}
/// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and
/// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None`
/// when `useArtboards` is absent, null or true. A document with no visible art is refused.
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Document, Value)>> {
if use_artboards(cmd, p)? != Some(false) {
return Ok(None);
}
let doc = &*doc.without_edit_modes();
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
let mut q = super::export::without_artboards(p);
if let Some(o) = q.as_object_mut() {
o.remove("useArtboards");
}
Ok(Some((single_artboard(doc, bounds, "Art"), q)))
}
/// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when
/// absent; an error when it is not four finite numbers with a positive size, when the format isn't
/// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would
@@ -596,7 +612,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
let doc = &*doc.without_edit_modes();
let n = doc.artboards.len();
// SVG reads its own `useArtboards` (an SVG option).
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(p)? } else { None };
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None };
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
if let Some(rect) = page_rect(f, p)? {
let mut q = super::export::without_artboards(p);
@@ -606,13 +622,17 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
}
return encode_files(&single_artboard(doc, rect, "Rect"), f, &q);
}
if use_artboards == Some(false) {
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?;
let mut q = super::export::without_artboards(p);
if let Some(o) = q.as_object_mut() {
o.remove("useArtboards");
}
return encode_files(&single_artboard(doc, bounds, "Art"), f, &q);
// A PDF of the art's bounds carries no editing data (it would replace the artboards).
if use_artboards == Some(false)
&& f.id == "pdf"
&& let Some((bytes, notes)) = super::pdf::encode_art_page(C, doc, p)?
{
return Ok(Encoded::one_with_notes(bytes, notes));
}
if use_artboards == Some(false)
&& let Some((art, q)) = art_page(C, doc, p)?
{
return encode_files(&art, f, &q);
}
let bytes = match f.id {
"vectorcraft" => super::native::encode(C, f, doc, p)?,
+11 -8
View File
@@ -782,9 +782,9 @@ pub fn open_extensions() -> &'static [&'static str] {
/// File › Open's filters: "All readable files" first, then one per readable format, then one per
/// importer plug-in (under its name, with the extensions [`open_extensions`] takes from it), then
/// swatch libraries (which open in the library panel), Libraries panel libraries, flattener, PDF,
/// print and export presets (imported), scripts (checked without running them) and plug-ins
/// (installed).
/// swatch and graphic style libraries (which open in their library panels), Libraries panel
/// libraries, flattener, PDF, print, perspective grid and export presets and composite fonts
/// (imported), shortcut sets, scripts (checked without running them) and plug-ins (installed).
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
let (all, importers) = importer_open_part();
std::iter::once(("All readable files", all)).chain(format_filters()).chain(importers).chain(other_open_filters())
@@ -797,14 +797,17 @@ pub fn builtin_open_filters() -> impl Iterator<Item = (&'static str, &'static [&
std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters())
}
/// The open-dialog filters after the document formats: swatch libraries, Libraries panel
/// libraries, presets, composite fonts, shortcut sets, scripts and plug-ins.
/// The open-dialog filters after the document formats: swatch and graphic style libraries,
/// Libraries panel libraries, presets (perspective grid presets among them), composite fonts,
/// shortcut sets, scripts and plug-ins.
fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once(("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS))
.chain(std::iter::once(("Graphic Style Libraries", std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT))))
.chain(std::iter::once(("Libraries", crate::cmd::library::LIBRARY_EXTS)))
.chain(std::iter::once(("Flattener presets", crate::cmd::flatten::PRESET_EXTS)))
.chain(std::iter::once(("PDF presets", crate::cmd::pdfcmds::PRESET_EXTS)))
.chain(std::iter::once(("Print presets", crate::cmd::printpresets::PRESET_EXTS)))
.chain(std::iter::once(("Perspective grid presets", crate::cmd::perspgrid::PRESET_EXTS)))
.chain(std::iter::once(("Export presets", screens::PRESET_FILE_EXTS)))
.chain(std::iter::once(("Composite fonts", crate::cmd::compositefonts::EXTS)))
.chain(std::iter::once(("Shortcut sets", crate::cmd::shortcutset::EXTS)))
@@ -815,13 +818,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
/// match the default filter) still list `.ase` and the other library extensions; then the same
/// filters as [`builtin_open_filters`] so a document can be picked for its swatches or graphic
/// styles.
/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document
/// can be picked for its swatches or graphic styles.
pub fn library_open_filters(
library_label: &'static str,
library_exts: &'static [&'static str],
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once((library_label, library_exts)).chain(builtin_open_filters())
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts)))
}
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
+39 -4
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), out Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdf Line truncated
has_doc,
export_pdf
),
@@ -137,7 +137,7 @@ pub fn specs() -> Vec<CommandSpec> {
"PDF Settings",
[],
None,
"{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused",
"{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory (one page of the art's bounds with useArtboards: false) and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused",
always,
pdf_settings
),
@@ -280,6 +280,27 @@ fn options_at(cmd: &str, doc: &Document, p: &Value, now: Option<i64>) -> Result<
pub const EDITING_NEEDS_EVERY_ARTBOARD: &str =
"Preserve editing was left out: it needs a PDF of every artboard, in order (reopened, this one would show the others too)";
/// Why a PDF of the art's bounds (`useArtboards: false`) carries no editing data.
pub const EDITING_NEEDS_THE_ARTBOARDS: &str =
"Preserve editing was left out: it needs a PDF of the artboards (reopened, this one would replace them with one artboard around the art)";
/// With `useArtboards: false` in `p`: the PDF of one page, the bounds of `doc`'s visible art
/// ([`super::encode::art_page`]) → (bytes, notes). It carries no editing data: with Preserve
/// Editing on, the notes end with [`EDITING_NEEDS_THE_ARTBOARDS`]. `None` when `p` asks for the
/// artboards.
pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Vec<u8>, Vec<Note>)>> {
let Some((art, mut q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
let left_out = settings(cmd, &q)?.preserve_editing;
if left_out && let Some(o) = q.as_object_mut() {
o.insert("preserveEditing".into(), json!(false));
}
let (bytes, mut notes) = encode(cmd, &art, &q)?;
if left_out {
notes.push(Note::setting(EDITING_NEEDS_THE_ARTBOARDS));
}
Ok(Some((bytes, notes)))
}
/// The warning for a PDF/X file that leaves out the document's bleed
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
@@ -482,7 +503,12 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
} else {
q = json!({ "_displayDocTitle": display_doc_title });
}
let (bytes, notes) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?;
// The opacity-mask or symbol editing layer is left out.
let doc = titled.as_ref().unwrap_or(&st.doc).without_edit_modes();
let (bytes, notes) = match encode_art_page(C, &doc, &q)? {
Some(encoded) => encoded,
None => encode(C, &doc, &q)?,
};
write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": note_texts(&notes) }))
}
@@ -513,9 +539,18 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> {
const Q: &str = "document.pdfSettings";
let saved = &s.prefs.pdf_presets;
let set = settings_with(Q, p, saved)?;
super::encode::use_artboards(Q, p)?;
let diff = changes(&set, &preset_settings(Q, p, saved)?);
let warnings = match s.active() {
Some(st) if bool_or(p, "includeDocument", false) => note_texts(&encode(Q, &st.doc, &*expand_preset(s, Q, p)?)?.1),
Some(st) if bool_or(p, "includeDocument", false) => {
let q = expand_preset(s, Q, p)?;
let doc = st.doc.without_edit_modes();
let (_, notes) = match encode_art_page(Q, &doc, &q)? {
Some(encoded) => encoded,
None => encode(Q, &doc, &q)?,
};
note_texts(&notes)
}
_ => set.warnings(),
};
let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?;
+18 -2
View File
@@ -390,9 +390,20 @@ fn open_exts_cover_every_readable_format() {
assert_eq!(filters[0], ("All readable files", OPEN_EXTS));
assert_eq!(
filters.len(),
11 + FORMATS.iter().filter(|f| f.read).count(),
"and swatch libraries, libraries, flattener, PDF, print and export presets, composite fonts, shortcut sets, scripts, plug-ins"
13 + FORMATS.iter().filter(|f| f.read).count(),
"and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \
fonts, shortcut sets, scripts, plug-ins"
);
let at = |label: &str| filters.iter().position(|f| f.0 == label).unwrap_or_else(|| panic!("File › Open has no {label} filter"));
let styles: &[&str] = &[vectorcraft_doc::style_libs::STYLES_EXT];
assert_eq!(filters[at("Graphic Style Libraries")].1, styles, "File › Open opens graphic style libraries");
assert_eq!(at("Graphic Style Libraries"), at("Swatch libraries") + 1, "next to the swatch libraries");
assert_eq!(filters[at("Perspective grid presets")].1, crate::cmd::perspgrid::PRESET_EXTS, "File › Open imports perspective grid presets");
assert_eq!(at("Perspective grid presets"), at("Print presets") + 1, "among the presets");
assert_eq!(at("Export presets"), at("Perspective grid presets") + 1, "among the presets");
for e in [vectorcraft_doc::style_libs::STYLES_EXT].iter().chain(crate::cmd::perspgrid::PRESET_EXTS) {
assert!(!filters[0].1.contains(e), "All readable files lists documents only, not .{e}");
}
assert!(filters.contains(&("Export presets", SCREEN_EXPORT_PRESET_EXTS)), "File › Open imports export presets");
assert!(filters.contains(&("Scripts", crate::cmd::scripts::EXTS)), "File › Open checks scripts");
assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins");
@@ -404,6 +415,11 @@ fn library_open_filters_list_library_formats_first() {
assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS));
assert!(filters[0].1.contains(&"ase"));
assert_eq!(filters[1], ("All readable files", OPEN_EXTS));
let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT);
for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] {
let filters: Vec<_> = library_open_filters(label, exts).collect();
assert_eq!(filters.iter().filter(|f| f.0 == label).count(), 1, "{label} is listed once");
}
}
/// The extensions usage texts list for export: one per writable format, each picking that format
+120
View File
@@ -56,6 +56,126 @@ fn export_pdf_writes_the_compatibility_header_and_the_range() {
assert!(b64(&v).starts_with(b"%PDF-1.6"));
}
/// `useArtboards: false` writes one page, the bounds of the visible art, as `document.export`
/// does, whatever artboards are chosen. Art longer than 200 in keeps its size with
/// `longPagesInPoints`. A document with no visible art and a value that isn't a boolean are
/// refused.
#[test]
fn use_artboards_false_writes_one_page_of_the_arts_bounds() {
let mut s = session(3);
let page = |bytes: &[u8]| {
let d = vectorcraft_pdf::import(bytes).unwrap();
(d.artboards.len(), d.artboards[0].rect.size())
};
let through_export = page(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap()));
assert!(through_export.0 == 1 && through_export.1.width < 50.0 && through_export.1.height < 40.0, "{through_export:?}");
for p in [
json!({"useArtboards": false}),
json!({"useArtboards": false, "range": "2"}),
json!({"useArtboards": false, "artboards": [0, 1]}),
json!({"useArtboards": false, "artboard": 2}),
] {
assert_eq!(page(&b64(&export(&mut s, p.clone()))), through_export, "{p}");
}
assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": true})))), 3);
assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": null})))), 3);
// A 10 m drawing on a small artboard: its page is 10 m long, in points.
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 28_346.46, "height": 100})).unwrap();
let v = export(&mut s, json!({"useArtboards": false, "longPagesInPoints": true}));
let pdf = b64(&v);
let (n, size) = page(&pdf);
assert!(n == 1 && size.width > 28_346.0 && size.width < 28_350.0, "{size:?}");
assert!(!String::from_utf8_lossy(&pdf).contains("/UserUnit"));
assert!(warnings(&v).iter().any(|w| w.contains("written without a UserUnit, in points")), "{v}");
// The Summary's export in memory writes the same page.
let mut long = |p: Value| warnings(&s.execute("document.pdfSettings", &p).unwrap()).iter().any(|w| w.contains("longer than PDF's page limit"));
assert!(long(json!({"includeDocument": true, "useArtboards": false})));
assert!(!long(json!({"includeDocument": true})), "the artboards are small");
let e = s.execute("document.pdfSettings", &json!({"useArtboards": "no"})).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "without includeDocument too: {e}");
s.execute("select.all", &json!({})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
for p in [json!({"useArtboards": false}), json!({"useArtboards": "no"})] {
let e = s.execute("document.exportPdf", &p).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "{p}: {e}");
}
}
/// A PDF of the art's bounds carries no Preserve Editing data, through `document.exportPdf`,
/// `document.export` and the Summary's export in memory, and says so in a warning: reopened, its
/// editing data would replace the document's artboards with the one around the art. A PDF of the
/// artboards keeps the data, and it reopens with every artboard. With Preserve Editing off, there
/// is no warning.
#[test]
fn a_pdf_of_the_arts_bounds_carries_no_editing_data() {
let mut s = session(3);
let left_out = |v: &Value| warnings(v).iter().any(|w| w == super::pdf::EDITING_NEEDS_THE_ARTBOARDS);
let art = json!({"useArtboards": false});
for v in [export(&mut s, art.clone()), s.execute("document.export", &as_export(&art)).unwrap()] {
let pdf = b64(&v);
assert!(vectorcraft_pdf::editing(&pdf).is_none(), "{:?}", warnings(&v));
assert!(left_out(&v), "{:?}", warnings(&v));
assert_eq!(pages(&pdf), 1);
}
let summary = s.execute("document.pdfSettings", &json!({"includeDocument": true, "useArtboards": false})).unwrap();
assert!(left_out(&summary), "{summary}");
let quiet = export(&mut s, json!({"useArtboards": false, "preserveEditing": false}));
assert!(!left_out(&quiet), "{:?}", warnings(&quiet));
for v in [export(&mut s, json!({})), export(&mut s, json!({"useArtboards": true}))] {
let editing = vectorcraft_pdf::editing(&b64(&v)).expect("editing data");
let reopened = vectorcraft_format::load(&editing.data).unwrap();
assert_eq!(reopened.artboards.len(), 3);
assert!(!left_out(&v), "{:?}", warnings(&v));
}
}
/// While an opacity mask is edited, a PDF of the art's bounds measures the art without the
/// editing layer, as `document.export` does: a mask shape drawn past the masked object doesn't
/// widen the page.
#[test]
fn a_pdf_of_the_art_leaves_out_the_mask_editing_layer() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone();
let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap();
s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap();
s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap();
assert!(s.doc().unwrap().doc.mask_edit.is_some());
let width = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.width();
let through_export = width(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap()));
assert!(through_export < 250.0, "{through_export}");
assert_eq!(width(&b64(&export(&mut s, json!({"useArtboards": false})))), through_export);
}
/// While an opacity mask is edited, a PDF of the artboards leaves out the editing layer too, as
/// `document.export` does: from the drawn page and from the Preserve Editing data.
#[test]
fn a_pdf_of_the_artboards_leaves_out_the_mask_editing_layer() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone();
let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap();
s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap();
s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap();
assert!(s.doc().unwrap().doc.mask_edit.is_some());
let nodes = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().node_count();
let plain = json!({"preserveEditing": false});
let through_export = nodes(&b64(&s.execute("document.export", &as_export(&plain)).unwrap()));
assert_eq!(nodes(&b64(&export(&mut s, plain))), through_export, "the drawn page");
let layers = |v: &Value| vectorcraft_format::load(&vectorcraft_pdf::editing(&b64(v)).unwrap().data).unwrap().layers;
let through_export = layers(&s.execute("document.export", &as_export(&json!({}))).unwrap());
assert_eq!(layers(&export(&mut s, json!({}))), through_export, "the Preserve Editing data");
}
#[test]
fn bad_options_are_refused() {
let mut s = session(2);
+2 -2
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Missing Fonts",
[],
None,
"{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers and its symbols (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)",
"{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers, its symbols and its patterns, opacity masks included (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)",
has_doc,
missing
),
@@ -103,7 +103,7 @@ pub struct MissingFont {
pub resolved: Option<(String, String)>,
}
/// The fonts the type of `d` uses, in its layers and its symbols (a composite font's parts, those
/// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those
/// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif`
/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
+617 -177
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fonts in Document",
[],
None,
"{selectionOnly?} (the type in the art of the symbols in scope included: all of the document's, or those the selected instances show) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks",
"{selectionOnly?} (the type in the opacity masks of the objects in scope and in the art of the symbols and patterns in scope included: all of the document's, a pattern swatch that nothing paints included, or those the selected objects show through their instances and paints; disabled masks too) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks",
has_doc,
fonts
),
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Font",
[],
None,
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the opacity masks of the objects in scope (disabled masks too) and in the art of the symbols and patterns in scope changes too (all of the document's, or those the selected objects show through their instances and paints, so every instance of a symbol and every object a pattern paints follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's, pattern's or mask's art), in the mask of a hidden or locked object, or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
has_doc,
replace
),
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Text by Font",
[],
None,
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, and the instances of the symbols whose art uses it, that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the objects painted with a pattern whose art uses it and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
has_doc,
select_font
),
@@ -64,15 +64,23 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Text objects in scope: the selection's (and their descendants') or the whole document's.
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
/// Text objects in scope: the selection's (and their descendants') or the whole document's, and
/// the objects among them that have an opacity mask (not the object whose mask is being edited:
/// its art is on the editing layer).
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<(Vec<NodeId>, Vec<NodeId>)> {
let st = s.doc()?;
let mut v = vec![];
let editing = st.doc.mask_edit.map(|m| m.object);
let (mut texts, mut masked) = (vec![], vec![]);
let mut seen = HashSet::new();
let mut add = |n: &vectorcraft_doc::Node| {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) {
v.push(c.id);
if seen.insert(c.id) {
if matches!(c.kind, NodeKind::Text(_)) {
texts.push(c.id);
}
if c.extras().mask.is_some() && Some(c.id) != editing {
masked.push(c.id);
}
}
})
};
@@ -87,7 +95,7 @@ fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Resu
add(l);
}
}
Ok(v)
Ok((texts, masked))
}
/// Whether `name` is the symbol being edited, whose art is on the editing layer.
@@ -95,106 +103,269 @@ fn being_edited(d: &Document, name: &str) -> bool {
d.symbol_edit.as_ref().is_some_and(|e| e.symbol == name)
}
/// The symbols that the selected objects of `s` show: those of the instances among them and their
/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a
/// hidden or locked group of the art. Returned as (all of them, those shown by instances the
/// Selection tool can reach: not hidden or locked, as `Document::editable` says).
fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
fn open_instances(n: &Node, out: &mut BTreeSet<String>) {
/// Whether `name` is the pattern being edited, whose tile art is on the editing layer.
fn pattern_being_edited(d: &Document, name: &str) -> bool {
d.pattern_edit.as_ref().is_some_and(|e| e.pattern == name)
}
/// The patterns that the fills and strokes `n` draws name (of a text object, also those of its
/// characters): visible ones, and strokes wider than 0.
fn paint_patterns(n: &Node) -> impl Iterator<Item = &str> {
let runs = match &n.kind {
NodeKind::Text(t) => t.runs.as_slice(),
_ => &[],
};
n.appearance
.items
.iter()
.filter(|i| i.visible() && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0))
.map(AppearanceItem::paint)
.chain(runs.iter().flat_map(|r| [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)]).flatten())
.filter_map(|p| match p {
Paint::Pattern { pattern, .. } => Some(pattern.as_str()),
_ => None,
})
}
/// Symbols and patterns, by name: those whose art is in scope.
#[derive(Clone, Debug, Default)]
struct Resources {
symbols: BTreeSet<String>,
patterns: BTreeSet<String>,
}
impl Resources {
/// Adds what `n` itself shows: the symbol of an instance, the patterns its paints name, and
/// what the art of its opacity mask shows (not hidden or locked objects of that art).
fn add_own(&mut self, n: &Node) {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
self.symbols.insert(symbol.clone());
}
self.patterns.extend(paint_patterns(n).map(str::to_string));
if let Some(m) = n.extras().mask.as_deref() {
self.add(&m.art);
}
}
/// Adds what `n` and its descendants show, leaving out hidden or locked objects and what they
/// hold.
fn add(&mut self, n: &Node) {
if !n.visible || n.locked {
return;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
out.insert(symbol.clone());
}
self.add_own(n);
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
open_instances(c, out);
self.add(c);
}
}
let expand = |names: &mut BTreeSet<String>, d: &Document| loop {
let mut more = BTreeSet::new();
for sym in d.symbols.iter().filter(|sym| names.contains(&sym.name)) {
open_instances(&sym.art, &mut more);
/// Adds what the art of the symbols and patterns named shows, until nothing more is added; each
/// symbol and pattern is read once, so art that shows itself ends.
fn expand(&mut self, d: &Document) {
let mut symbols: Vec<String> = self.symbols.iter().cloned().collect();
let mut patterns: Vec<String> = self.patterns.iter().cloned().collect();
while !symbols.is_empty() || !patterns.is_empty() {
let mut more = Resources::default();
for name in symbols.drain(..) {
if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) {
more.add(&sym.art);
}
}
for name in patterns.drain(..) {
for art in d.pattern(&name).map(|p| p.art.as_slice()).unwrap_or_default() {
more.add(art);
}
}
symbols.extend(more.symbols.into_iter().filter(|name| self.symbols.insert(name.clone())));
patterns.extend(more.patterns.into_iter().filter(|name| self.patterns.insert(name.clone())));
}
let before = names.len();
names.extend(more);
if names.len() == before {
break;
}
/// The symbols and patterns of `self` that are not in `other`.
fn difference(&self, other: &Self) -> Self {
Self {
symbols: self.symbols.difference(&other.symbols).cloned().collect(),
patterns: self.patterns.difference(&other.patterns).cloned().collect(),
}
};
}
}
/// The symbols and patterns that the selected objects of `s` show: those of the instances among
/// them and their descendants and the patterns their paints name (also in the art of their
/// opacity masks), and those that the art of these symbols and patterns shows through objects that
/// are not hidden or locked, nor in a hidden or locked group of the art. Returned as (all of them,
/// those shown by objects the Selection tool can reach: not hidden or locked, as
/// `Document::editable` says).
fn selected_art(s: &Session, selected: Option<&[NodeId]>) -> Result<(Resources, Resources)> {
let st = s.doc()?;
let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new());
let (mut all, mut open) = (Resources::default(), Resources::default());
let editable = st.doc.editable();
for id in selected.unwrap_or(&st.selection.objects) {
if let Some(n) = st.doc.node(*id) {
n.walk(&mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
all.insert(symbol.clone());
if editable(c.id) {
open.insert(symbol.clone());
}
all.add_own(c);
if editable(c.id) {
open.add_own(c);
}
});
}
}
drop(editable);
expand(&mut all, &st.doc);
expand(&mut open, &st.doc);
all.expand(&st.doc);
open.expand(&st.doc);
Ok((all, open))
}
/// The text objects in the art of `d`'s symbols (with `only`, of those it names), each with
/// whether it is open: neither it nor a group around it in the art is hidden or locked. The symbol
/// being edited is left out: its art is on the editing layer.
pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> {
fn visit<'a>(n: &'a Node, open: bool, out: &mut Vec<(&'a TextObject, bool)>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind {
out.push((&**t, open));
}
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
visit(c, open, out);
}
/// A text object found in art: its id, the text and whether it is open (neither it nor a group
/// around it, nor an object whose opacity mask holds it, is hidden or locked).
pub(super) type ArtText<'a> = (NodeId, &'a TextObject, bool);
/// Adds the text objects of `n` and its descendants, the art of their opacity masks included, to
/// `out`; each is open when `open` holds and [`ArtText`] says so.
fn art_texts<'a>(n: &'a Node, open: bool, out: &mut Vec<ArtText<'a>>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind {
out.push((n.id, &**t, open));
}
if let Some(m) = n.extras().mask.as_deref() {
art_texts(&m.art, open, out);
}
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
art_texts(c, open, out);
}
}
/// The text objects in the art of the opacity masks of the objects `masked` (each with whether
/// the object is open: when it isn't, none of its mask's text is).
fn mask_texts<'a>(d: &'a Document, masked: &[(NodeId, bool)]) -> Vec<ArtText<'a>> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) {
visit(&s.art, true, &mut out);
for (id, open) in masked {
if let Some(m) = d.node(*id).and_then(|n| n.extras().mask.as_deref()) {
art_texts(&m.art, *open, &mut out);
}
}
out
}
/// Calls `f` on each text object in the art of `d`'s symbols (with `only`, of those it names) for
/// which `wants(text, open)` holds (open as in [`symbol_texts`]), the symbol being edited left out.
/// Art without such text is left as it is.
pub(super) fn edit_symbol_texts(
d: &mut Document,
only: Option<&BTreeSet<String>>,
wants: &impl Fn(&TextObject, bool) -> bool,
f: &mut impl FnMut(&mut TextObject),
) {
fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool {
let open = open && n.visible && !n.locked;
matches!(&n.kind, NodeKind::Text(t) if wants(t, open)) || n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants)))
/// The text objects in the art of `d`'s symbols and patterns (with `only`, of those it names, a
/// pattern's art read once however many objects it paints), opacity masks in that art included.
/// The symbol and the pattern being edited are left out: their art is on the editing layer.
fn resource_texts<'a>(d: &'a Document, only: Option<&Resources>) -> Vec<ArtText<'a>> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.symbols.contains(&s.name))) {
art_texts(&s.art, true, &mut out);
}
fn visit(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &mut n.kind
&& wants(t, open)
{
f(t);
for p in d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name) && only.is_none_or(|o| o.patterns.contains(&p.name))) {
for art in &p.art {
art_texts(art, true, &mut out);
}
for c in n.children_mut().into_iter().flatten() {
if wanted(c, open, wants) {
visit(Arc::make_mut(c), open, wants, f);
}
out
}
/// The text objects in the art of `d`'s symbols (with `only`, of those it names), as
/// [`resource_texts`] finds them, each with whether it is open.
#[cfg(test)]
pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) {
art_texts(&s.art, true, &mut out);
}
out.into_iter().map(|(_, t, open)| (t, open)).collect()
}
/// Whether `n` or a descendant (the art of their opacity masks included) holds a text object for
/// which `wants(text, open)` holds, open as [`ArtText`] says.
fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool {
let open = open && n.visible && !n.locked;
matches!(&n.kind, NodeKind::Text(t) if wants(t, open))
|| n.extras().mask.as_deref().is_some_and(|m| wanted(&m.art, open, wants))
|| n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants)))
}
/// Calls `f` on each text object of `n` and its descendants (the art of their opacity masks
/// included) for which `wants(text, open)` holds; only the nodes on the way to such text are
/// copied.
fn edit_art(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &mut n.kind
&& wants(t, open)
{
f(t);
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& wanted(&m.art, open, wants)
{
edit_art(Arc::make_mut(&mut m.art), open, wants, f);
}
for c in n.children_mut().into_iter().flatten() {
if wanted(c, open, wants) {
edit_art(Arc::make_mut(c), open, wants, f);
}
}
}
/// Calls `f` on each text object in the opacity masks of the objects `masked` (as [`mask_texts`]
/// finds them) for which `wants(text, open)` holds. Masks without such text are left as they are.
fn edit_mask_texts(d: &mut Document, masked: &[(NodeId, bool)], wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
for (id, open) in masked {
if d.node(*id).and_then(|n| n.extras().mask.as_deref()).is_some_and(|m| wanted(&m.art, *open, wants))
&& let Some(m) = d.node_mut(*id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut())
{
edit_art(Arc::make_mut(&mut m.art), *open, wants, f);
}
}
}
/// Calls `f` on each text object in the art of `d`'s symbols and patterns (as [`resource_texts`]
/// finds them) for which `wants(text, open)` holds. Art without such text is left as it is.
fn edit_resource_texts(d: &mut Document, only: Option<&Resources>, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let symbol = d.symbol_edit.as_ref().map(|e| e.symbol.clone());
let pattern = d.pattern_edit.as_ref().map(|e| e.pattern.clone());
for s in &mut d.symbols {
if symbol.as_ref() != Some(&s.name) && only.is_none_or(|o| o.symbols.contains(&s.name)) && wanted(&s.art, true, wants) {
edit_art(Arc::make_mut(&mut s.art), true, wants, f);
}
}
for p in &mut d.patterns {
if pattern.as_ref() != Some(&p.name) && only.is_none_or(|o| o.patterns.contains(&p.name)) {
for art in &mut p.art {
if wanted(art, true, wants) {
edit_art(Arc::make_mut(art), true, wants, f);
}
}
}
}
let edited = d.symbol_edit.as_ref().map(|e| e.symbol.clone());
for s in &mut d.symbols {
if edited.as_ref() != Some(&s.name) && only.is_none_or(|o| o.contains(&s.name)) && wanted(&s.art, true, wants) {
visit(Arc::make_mut(&mut s.art), true, wants, f);
}
/// Every text object of `d` outside the objects of its layers: in the opacity masks of the
/// objects on its layers, and in the art of its symbols and patterns (as [`mask_texts`] and
/// [`resource_texts`] find them, each mask's text open).
pub(super) fn art_texts_of(d: &Document) -> Vec<ArtText<'_>> {
let masked = masked_objects(d);
let mut out = mask_texts(d, &masked);
out.extend(resource_texts(d, None));
out
}
/// Calls `f` on each text object of [`art_texts_of`] for which `wants(text)` holds.
pub(super) fn edit_art_texts_of(d: &mut Document, wants: &impl Fn(&TextObject) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let masked = masked_objects(d);
edit_mask_texts(d, &masked, &|t, _| wants(t), f);
edit_resource_texts(d, None, &|t, _| wants(t), f);
}
/// The objects on the layers of `d` that have an opacity mask (not the object whose mask is being
/// edited), each as open.
fn masked_objects(d: &Document) -> Vec<(NodeId, bool)> {
let editing = d.mask_edit.map(|m| m.object);
let mut out = vec![];
d.walk(|n| {
if n.extras().mask.is_some() && Some(n.id) != editing {
out.push((n.id, true));
}
}
});
out
}
/// A font as type names it: family, style and, when it names one, the installed version.
@@ -218,14 +389,16 @@ pub(super) fn run_fonts(r: &TextRun) -> Vec<UsedFont> {
}
}
/// The fonts (family, style, version) the type in the layers and symbols of `d` is drawn in, a
/// composite font's parts in place of its name ([`run_fonts`]).
/// The fonts (family, style, version) the type in the layers, symbols and patterns of `d` is drawn
/// in, the type in opacity masks included, a composite font's parts in place of its name
/// ([`run_fonts`]).
pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
art_fonts(d, &[])
}
/// The fonts (family, style, version) of the type in the layers and symbols of `d` and in `art`
/// (art read from a file, its resources in `d`).
/// The fonts (family, style, version) of the type in the layers, symbols and patterns of `d` and
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
/// pattern being edited is read from the editing layer only.
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
let mut fonts = BTreeSet::new();
let mut add = |n: &Node| {
@@ -233,12 +406,9 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
fonts.extend(t.runs.iter().flat_map(run_fonts));
}
};
d.walk(&mut add);
for s in &d.symbols {
s.art.walk(&mut add);
}
for n in art {
n.walk(&mut add);
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
for n in d.layers.iter().map(|l| &**l).chain(d.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(art) {
vectorcraft_doc::swatches::walk_with_masks(n, &mut add);
}
fonts
}
@@ -513,50 +683,78 @@ impl Session {
pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
let (family, style) = font_param(params, "from", "text.replaceFont")?;
let selection_only = bool_or(params, "selectionOnly", false);
let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?;
let d = &self.doc()?.doc;
let other: Vec<NodeId> = {
let editable = d.editable();
scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect()
};
let in_scope = ReplaceScope::read(self, selection_only, selected)?;
let uses = |t: &TextObject| {
t.runs.iter().any(|r| {
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name))
})
};
let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::<Vec<_>>();
fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec<NodeId>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind
&& (!open || closed)
&& uses(t)
{
ids.push(n.id);
}
for child in n.children().map(Vec::as_slice).unwrap_or_default() {
visit(child, open, closed, uses, ids);
}
Ok(in_scope.skipped(&self.doc()?.doc, &uses))
}
}
/// What Replace Font looks at: the text objects in scope that the Selection tool can reach and
/// those it can't, the objects with an opacity mask (each with whether it can reach them), and the
/// symbols and patterns whose art is in scope (`None`: all of the document's) with those shown
/// only by hidden or locked objects of the selection.
struct ReplaceScope {
ids: Vec<NodeId>,
other: Vec<NodeId>,
masked: Vec<(NodeId, bool)>,
resources: Option<Resources>,
closed: Resources,
}
impl ReplaceScope {
fn read(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Self> {
// With selectionOnly: the symbols and patterns the selection shows; those shown only by
// hidden or locked objects keep their type, counted in `skipped`.
let (resources, closed) = if selection_only {
let (all, open) = selected_art(s, selected)?;
let closed = all.difference(&open);
(Some(open), closed)
} else {
(None, Resources::default())
};
let d = &s.doc()?.doc;
let editable = d.editable();
let (texts, masked) = scope(s, selection_only, selected)?;
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = texts.into_iter().partition(|id| editable(*id));
let masked = masked.into_iter().map(|id| (id, editable(id))).collect();
Ok(Self { ids, other, masked, resources, closed })
}
/// The text objects in the art of opacity masks, symbols and patterns in scope.
fn art<'a>(&self, d: &'a Document) -> Vec<ArtText<'a>> {
let mut texts = mask_texts(d, &self.masked);
texts.extend(resource_texts(d, self.resources.as_ref()));
texts
}
/// The text objects in scope set in a font `uses` matches that Replace Font leaves as they are:
/// those the Selection tool can't reach, hidden or locked text in art, and the text of the
/// symbols and patterns shown only by hidden or locked objects of the selection.
fn skipped(&self, d: &Document, uses: &impl Fn(&TextObject) -> bool) -> Vec<NodeId> {
let mut ids: Vec<NodeId> = self.other.iter().copied().filter(|id| text(d, *id).is_some_and(uses)).collect();
ids.extend(self.art(d).into_iter().filter(|(_, t, open)| !open && uses(t)).map(|(id, ..)| id));
if !self.closed.symbols.is_empty() || !self.closed.patterns.is_empty() {
ids.extend(resource_texts(d, Some(&self.closed)).into_iter().filter(|(_, t, _)| uses(t)).map(|(id, ..)| id));
}
for symbol in d
.symbols
.iter()
.filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name)))
{
let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name));
visit(&symbol.art, true, closed, &uses, &mut ids);
}
Ok(ids)
ids
}
}
fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result<Value> {
let ids = scope(s, selected.is_some(), selected)?;
let (ids, masked) = scope(s, selected.is_some(), selected)?;
let d = &s.doc()?.doc;
let db = vectorcraft_text::FontDb::global();
// The type in the art of the symbols in scope too: all of them, or those the selection shows.
let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None };
// The type in the art of the opacity masks of the objects in scope, and of the symbols and
// patterns in scope: all of them, or those the selection shows.
let resources = if selected.is_some() { Some(selected_art(s, selected)?.0) } else { None };
let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect();
texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t));
let masked: Vec<(NodeId, bool)> = masked.into_iter().map(|id| (id, true)).collect();
texts.extend(mask_texts(d, &masked).into_iter().map(|(_, t, _)| t));
texts.extend(resource_texts(d, resources.as_ref()).into_iter().map(|(_, t, _)| t));
// Each font's runs, objects and the text of its runs.
let mut found: BTreeMap<UsedFont, (usize, usize, Vec<&str>)> = BTreeMap::new();
for t in texts {
@@ -617,21 +815,6 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option<String>)> {
Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string)))
}
fn skipped_font_texts(
d: &Document,
other: &[NodeId],
symbols: &[(&TextObject, bool)],
closed: &BTreeSet<String>,
uses: &impl Fn(&TextObject) -> bool,
) -> usize {
let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count();
skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count();
if !closed.is_empty() {
skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count();
}
skipped
}
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.replaceFont";
let (ff, fs) = font_param(p, "from", C)?;
@@ -660,35 +843,25 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
};
// Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked
// group or layer, or on a locked artboard. The text left in the font is counted. The type in
// the art of the symbols in scope (all of them, or those the selection shows) changes too,
// unless it or a group around it in the art is hidden or locked.
// the opacity masks of the objects in scope, and in the art of the symbols and patterns in
// scope (all of them, or those the selection shows), changes too, unless it, a group around it
// in the art or the object whose mask holds it is hidden or locked.
let selection_only = bool_or(p, "selectionOnly", false);
// With selectionOnly: the symbols the selection shows; those shown only by hidden or locked
// instances keep their type, counted in `skipped`.
let (symbols, closed) = if selection_only {
let (all, open) = selected_symbols(s, None)?;
let closed: BTreeSet<String> = all.difference(&open).cloned().collect();
(Some(open), closed)
} else {
(None, BTreeSet::new())
};
let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style));
// Whether a run of `t` changes.
let changes = |t: &TextObject| t.runs.iter().any(|r| new_style(&r.style).is_some());
let (ids, skipped, in_symbols) = {
let in_scope = ReplaceScope::read(s, selection_only, None)?;
let (ids, skipped, in_art) = {
let d = &s.doc()?.doc;
let editable = d.editable();
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id));
let texts = symbol_texts(d, symbols.as_ref());
let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses);
let skipped = in_scope.skipped(d, &uses).len();
// The text that changes: when none does, the document and its undo history stay as they are.
let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect();
let in_symbols = texts.iter().any(|(t, open)| *open && changes(t));
(ids, skipped, in_symbols)
let ids: Vec<NodeId> = in_scope.ids.iter().copied().filter(|id| text(d, *id).is_some_and(changes)).collect();
let in_art = in_scope.art(d).iter().any(|(_, t, open)| *open && changes(t));
(ids, skipped, in_art)
};
// The fonts the replaced runs are set in, for the warning.
let mut set = BTreeSet::new();
let n = if ids.is_empty() && !in_symbols {
let n = if ids.is_empty() && !in_art {
0
} else {
s.edit("Replace Font", |d, _| {
@@ -717,7 +890,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
replace_in(t);
}
}
edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && changes(t), &mut replace_in);
let wants = |t: &TextObject, open: bool| open && changes(t);
edit_mask_texts(d, &in_scope.masked, &wants, &mut replace_in);
edit_resource_texts(d, in_scope.resources.as_ref(), &wants, &mut replace_in);
Ok(n)
})?
};
@@ -734,13 +909,26 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// Whether `n` or a descendant that is not hidden or locked, nor in a hidden or locked group,
/// shows type in a font `uses` matches: text set in it, an instance of a symbol in `found`, a paint
/// naming a pattern in `found`, or such type in the art of its opacity mask.
fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, found: &Resources) -> bool {
n.visible
&& !n.locked
&& (matches!(&n.kind, NodeKind::Text(t) if uses(t))
|| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol))
|| paint_patterns(n).any(|p| found.patterns.contains(p))
|| n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, uses, found))
|| n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, found))))
}
/// What Replace Font says when it left text in the font that it can't reach.
const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced";
fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string();
let style = str_param(p, "style").map(str::to_string);
let ids = scope(s, false, None)?;
let (ids, masked) = scope(s, false, None)?;
let d = &s.doc()?.doc;
let within = FontScope::read(d, p)?;
// Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group
@@ -752,37 +940,40 @@ fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
.any(|r| r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x)))
};
let mut hits: Vec<NodeId> = ids.into_iter().filter(|id| editable(*id) && text(d, *id).is_some_and(uses)).collect();
// The symbols whose art uses the font in type that is not hidden or locked, nor in a hidden or
// locked group of the art, also through the instances of other symbols it holds.
fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, symbols: &BTreeSet<&str>) -> bool {
n.visible
&& !n.locked
&& match &n.kind {
NodeKind::Text(t) => uses(t),
NodeKind::SymbolInstance { symbol, .. } => symbols.contains(symbol.as_str()),
_ => n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, symbols))),
}
}
let mut symbols: BTreeSet<&str> = BTreeSet::new();
// The symbols and patterns whose art uses the font in type that is not hidden or locked, nor in
// a hidden or locked group of the art, also through the instances, patterns and opacity masks
// it holds. The pattern being edited is left out: its art is on the editing layer.
let mut found = Resources::default();
loop {
let found: Vec<&str> = d
let symbols: Vec<String> = d
.symbols
.iter()
.filter(|sym| !symbols.contains(sym.name.as_str()) && reaches(&sym.art, &uses, &symbols))
.map(|sym| sym.name.as_str())
.filter(|sym| !found.symbols.contains(&sym.name) && reaches(&sym.art, &uses, &found))
.map(|sym| sym.name.clone())
.collect();
if found.is_empty() {
let patterns: Vec<String> = d
.patterns
.iter()
.filter(|p| !pattern_being_edited(d, &p.name) && !found.patterns.contains(&p.name) && p.art.iter().any(|a| reaches(a, &uses, &found)))
.map(|p| p.name.clone())
.collect();
if symbols.is_empty() && patterns.is_empty() {
break;
}
symbols.extend(found);
found.symbols.extend(symbols);
found.patterns.extend(patterns);
}
// Their instances the Selection tool can reach.
if !symbols.is_empty() {
// The objects the Selection tool can reach that show such type: the instances of those
// symbols, the objects that those patterns paint, and the objects whose opacity mask holds it
// (not layers, which the Selection tool doesn't select).
let masked: HashSet<NodeId> = masked.into_iter().collect();
if !found.symbols.is_empty() || !found.patterns.is_empty() || !masked.is_empty() {
let texts: HashSet<NodeId> = hits.iter().copied().collect();
d.walk(&mut |n: &Node| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& symbols.contains(symbol.as_str())
&& editable(n.id)
{
let shows = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol))
|| paint_patterns(n).any(|p| found.patterns.contains(p))
|| (masked.contains(&n.id) && n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, &uses, &found)));
if shows && !n.is_layer() && !texts.contains(&n.id) && editable(n.id) {
hits.push(n.id);
}
});
@@ -1311,6 +1502,255 @@ mod tests {
assert_eq!(s.execute("text.replaceFont", &serif_to_sans).unwrap(), json!({"runs": 0}));
}
/// Moves object `art` of the layers into the opacity mask of `owner` (a layer or an object).
fn mask_with(s: &mut Session, owner: u64, art: u64) {
s.edit("Mask", |d, _| {
let art = d.remove(NodeId(art))?;
d.node_mut(NodeId(owner)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
}
/// The font families of the first runs of the text in the opacity mask of `owner`.
fn mask_families(s: &Session, owner: u64) -> Vec<String> {
let d = &s.doc().unwrap().doc;
mask_texts(d, &[(NodeId(owner), true)]).iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect()
}
/// The font families of the first runs of the text in the art of pattern `name`.
fn pattern_families(s: &Session, name: &str) -> Vec<String> {
let d = &s.doc().unwrap().doc;
let mut out = vec![];
for art in &d.pattern(name).unwrap().art {
art_texts(art, true, &mut out);
}
out.iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect()
}
/// The rows of `text.fonts` with `p`: family, runs and objects.
fn font_rows(s: &mut Session, p: Value) -> Vec<(String, u64, u64)> {
let fonts = s.execute("text.fonts", &p).unwrap();
fonts
.as_array()
.unwrap()
.iter()
.map(|f| (f["family"].as_str().unwrap().to_string(), f["runs"].as_u64().unwrap(), f["objects"].as_u64().unwrap()))
.collect()
}
/// Find Font lists, selects and changes the type in opacity masks: on objects, on a layer,
/// disabled and inside the art of another mask. The type in the mask of a locked object is
/// listed and left in its font; Find selects the objects whose mask holds the type.
#[test]
fn find_font_reaches_the_type_in_opacity_masks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let text = |s: &mut Session, y: i32| {
s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap()
};
let rect = |s: &mut Session, y: i32| {
s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap()
};
let mut owners = vec![];
for y in [20, 50, 80] {
let owner = rect(&mut s, y);
let t = text(&mut s, y);
mask_with(&mut s, owner, t);
owners.push(owner);
}
let (open, locked, disabled) = (owners[0], owners[1], owners[2]);
s.execute("select.set", &json!({"ids": [locked]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [disabled]})).unwrap();
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
// A mask whose art is an object with a mask of its own, and a layer's mask.
let nested = rect(&mut s, 110);
let inner = rect(&mut s, 110);
let t = text(&mut s, 110);
mask_with(&mut s, inner, t);
mask_with(&mut s, nested, inner);
let layer = s.doc().unwrap().doc.layers[0].id.0;
let t = text(&mut s, 140);
mask_with(&mut s, layer, t);
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in masks");
assert_eq!(font_rows(&mut s, json!({})), [("Source Serif 4".to_string(), 5, 5)]);
s.execute("select.set", &json!({"ids": [open]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]);
// Find selects the objects whose mask holds the type, not the locked one or the layer.
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 3);
let mut selected = s.doc().unwrap().selection.objects.clone();
selected.sort();
assert_eq!(selected, [NodeId(open), NodeId(disabled), NodeId(nested)]);
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": [0]}})).unwrap()["count"], 3);
// Change All: one undo step, the locked object's mask left in its font and counted.
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let serif_to_sans = json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}});
let r = s.execute("text.replaceFont", &serif_to_sans).unwrap();
assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(4), Some(1)), "{r}");
assert_eq!(steps(&s), before + 1);
for owner in [open, disabled, nested, layer] {
assert_eq!(mask_families(&s, owner), ["Source Sans 3"], "the mask of {owner}");
}
assert_eq!(mask_families(&s, locked), ["Source Serif 4"]);
let r = s.execute("text.replaceFont", &serif_to_sans).unwrap();
assert_eq!(r, json!({"runs": 0, "skipped": 1, "warning": REPLACE_SKIPPED}));
assert_eq!(steps(&s), before + 1);
s.execute("edit.undo", &json!({})).unwrap();
for owner in [open, disabled, nested, layer] {
assert_eq!(mask_families(&s, owner), ["Source Serif 4"], "the mask of {owner} after Undo");
}
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(mask_families(&s, nested), ["Source Sans 3"]);
// While a mask is edited, its type on the editing layer is counted and changed once.
s.execute("transparency.editOpacityMask", &json!({"id": open})).unwrap();
assert_eq!(font_rows(&mut s, json!({})), [("Source Sans 3".to_string(), 4, 4), ("Source Serif 4".to_string(), 1, 1)]);
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
assert_eq!(r["runs"].as_u64(), Some(4), "{r}");
let families: Vec<String> = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect();
assert_eq!(families, ["Inter", "Source Serif 4"], "the edited mask is written back after each edit");
s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap();
assert_eq!(mask_families(&s, open), ["Inter"]);
}
/// Find Font lists the type in pattern swatches once, also when nothing paints with them;
/// Find selects the objects the pattern paints, and Change changes the pattern's art once for
/// every object it paints. While a pattern is edited, its type is taken from the editing layer.
#[test]
fn find_font_reaches_the_type_in_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let pattern = |s: &mut Session, name: &str, font: &str| {
let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": font})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [t], "name": name, "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
};
pattern(&mut s, "Dots", "Source Serif 4");
pattern(&mut s, "Unused", "Inter");
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in patterns");
let all = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)];
assert_eq!(font_rows(&mut s, json!({})), all);
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
let mut painted = vec![];
for y in [20, 60] {
painted.push(s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
}
s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": painted})).unwrap();
assert_eq!(font_rows(&mut s, json!({})), all, "a pattern's type counts once");
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0]), NodeId(painted[1])]);
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0);
// Only the selection: the patterns the selected objects paint with.
s.execute("select.set", &json!({"ids": [painted[0]]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]);
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let r = s
.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}))
.unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(steps(&s), before + 1);
assert_eq!(pattern_families(&s, "Dots"), ["Source Sans 3"]);
assert_eq!(pattern_families(&s, "Unused"), ["Inter"]);
// No run changes: no undo step.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!(r, json!({"runs": 0}));
assert_eq!(steps(&s), before + 1);
// Change All reaches the swatch nothing paints with.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(pattern_families(&s, "Unused"), ["Source Serif 4"]);
// A pattern in a hidden fill doesn't show: Find doesn't select the object for its type.
let hidden = s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
s.edit("Hide the fill", |d, _| {
for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() {
if let AppearanceItem::Fill(f) = it {
f.visible = false;
}
}
Ok(())
})
.unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
// Nor does a pattern on a stroke of no width.
s.execute("paint.setStroke", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
s.edit("Thin the stroke", |d, _| {
for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() {
if let AppearanceItem::Stroke(st) = it {
st.width = 0.0;
}
}
Ok(())
})
.unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
// A locked painted object: its pattern's type is listed and left in its font.
s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap();
let r =
s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true})).unwrap();
assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}");
assert_eq!(s.execute("select.font", &json!({"family": "Source Sans 3"})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0])]);
// While the pattern is edited, its type on the editing layer is counted and changed once.
s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap();
let rows = font_rows(&mut s, json!({}));
assert_eq!(rows, [("Source Sans 3".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]);
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
assert_eq!(r, json!({"runs": 1}));
let families: Vec<String> = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect();
assert_eq!(families, ["Inter", "Source Serif 4"], "the pattern's stored art is left out while it is edited");
s.execute("object.pattern.done", &json!({})).unwrap();
assert_eq!(pattern_families(&s, "Dots"), ["Inter"]);
}
/// A pattern whose art holds a symbol instance, painting objects inside and outside a symbol:
/// Find Font lists each pattern's and symbol's type once and reaches the symbol's type through
/// the pattern.
#[test]
fn find_font_reaches_symbols_through_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let inter = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "In", "font": "Inter"})).unwrap()["id"].clone();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [inter]})).unwrap();
let instance = s.doc().unwrap().selection.objects[0].0;
let serif = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Se", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
let tile = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [tile, serif, instance], "name": "Loop", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [tile, serif, instance]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
// Another object paints with the pattern too: its type is still read once.
let other = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [other]})).unwrap();
s.execute("symbol.new", &json!({"name": "Outer", "ids": [other]})).unwrap();
let outer = s.doc().unwrap().selection.objects[0];
let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [painted]})).unwrap();
let both = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)];
assert_eq!(font_rows(&mut s, json!({})), both);
s.execute("select.set", &json!({"ids": [painted]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), both);
// Find reaches the symbol's type through the pattern, and through a symbol whose art paints
// with the pattern.
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 2);
assert_eq!(s.doc().unwrap().selection.objects, [outer, NodeId(painted)]);
s.execute("select.set", &json!({"ids": [painted]})).unwrap();
let r =
s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})).unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3");
}
/// The font family of text object `id`'s first run.
fn text_family(s: &Session, id: u64) -> String {
text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone()
+11 -1
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave Line truncated
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave Line truncated
has_doc,
set_format
),
@@ -571,6 +571,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"tateChuYoko",
"tcyUpDown",
"tcyLeftRight",
"akiLeft",
"akiRight",
"standardVerticalRoman",
"noBreak",
"digits",
@@ -613,6 +615,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let font_height_reference = super::textedit::font_height_reference_param(p, C)?;
let tcy_up_down = super::textedit::tcy_offset_param(p, "tcyUpDown", C)?;
let tcy_left_right = super::textedit::tcy_offset_param(p, "tcyLeftRight", C)?;
let aki_left = super::textedit::aki_param(p, "akiLeft", C)?;
let aki_right = super::textedit::aki_param(p, "akiRight", C)?;
let mojikumi = match p.get("mojikumi") {
None | Some(Value::Null) => None,
Some(v) => Some(match v.as_str() {
@@ -773,6 +777,12 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = tcy.1 {
st.tcy_left_right = v;
}
if let Some(v) = aki_left {
st.aki_left = v;
}
if let Some(v) = aki_right {
st.aki_right = v;
}
if let Some(v) = flag("standardVerticalRoman") {
st.standard_vertical_roman = v;
}
@@ -472,6 +472,7 @@ pub(super) const ALLOWED: &[&str] = &[
"perspective.transform",
"recolor.apply",
"recolor.colors",
"recolor.pickTheme",
"recolor.randomize",
"recolor.reduce",
"select.add",
+819
View File
@@ -11,6 +11,7 @@ use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng,
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Point, Rect};
use super::colorcmds::{NotChanged, Recolor, Scope, left_out};
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param};
@@ -53,9 +54,827 @@ pub fn specs() -> Vec<CommandSpec> {
always,
randomize
),
cmd!(
query "recolor.pickTheme",
"Color Theme Picker",
[],
None,
"{picks: [{at: [x, y]} (a click: the object a Selection tool click there takes, with everything inside it) | {rect: [x0, y0, x1, y1]} (a marquee: every painted object it touches, and the part of each image inside it)] (1 to 256, in document points), colors?: 5 (1 to 64)} → {colors: [colour keys, the most used first], objects: the number of objects read} the colour palette of the art picked, for Recolor Artwork's Color Theme Picker: visible fills and strokes, gradient stops, text, mesh points, pattern tiles (with the patterns they use), the art of symbol instances (placed through their 9-slice guides), the colorize colour of an image it applies to and other images' pixels (at most 65,536 pixels of each pick of an image, spread evenly, and 1,048,576 pixels of at most 64 images in all; pixels less than half opaque and images that can't be decoded are left out). In a clip group, or under an opacity mask that clips, only what shows inside the clipping path or the mask art is read; a blend, envelope or repeat a marquee touches is read whole. Hidden or fully transparent objects and fill or stroke items are left out; locked objects are read. Each object read weighs the same, shared among its colours (an image's among its pixels; the vector art a symbol instance places counts as one object, each image it places on its own); similar colours merge (k-means in Lab) into at most `colors`, each shown by its most used colour in its own model. Picks that touch no art give no colours. Changes nothing",
has_doc,
pick_theme
),
]
}
/// The pixels one read of an image by the Color Theme Picker takes, at most, the pixels all its
/// reads share, and the images one pick reads, at most.
const THEME_PIXELS: usize = 65_536;
const THEME_TOTAL_PIXELS: usize = 1 << 20;
const MAX_THEME_IMAGES: usize = 64;
/// The image reads one pick queues, at most.
const MAX_THEME_READS: usize = 4096;
/// The stroke segments the opacity masks one pick reads are outlined along, at most.
const MASK_OUTLINE_SEGMENTS: usize = 20_000;
/// The point-in-region tests one pick makes to find whether outlines show through clip groups,
/// and the clipping-path elements the pixels of one image are tested against, at most.
const THEME_WORK: usize = 4_000_000;
/// The picks one `recolor.pickTheme` takes, and the colours it gives, at most.
const MAX_PICKS: usize = 256;
const MAX_THEME_COLORS: u64 = 64;
/// The objects the Color Theme Picker reads through, one inside another, at most.
const MAX_THEME_DEPTH: usize = 256;
/// A pick of the Color Theme Picker: a click at a point or a marquee.
enum Pick {
At(Point),
Area(Rect),
}
impl Pick {
/// `{at: [x, y]}` or `{rect: [x0, y0, x1, y1]}`, finite numbers.
fn param(v: &Value, cmd: &str) -> Result<Self> {
let numbers = |a: &Value, n: usize| -> Option<Vec<f64>> {
let a = a.as_array().filter(|a| a.len() == n)?;
a.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect()
};
match (v.get("at"), v.get("rect")) {
(Some(at), None) => {
numbers(at, 2).map(|p| Pick::At(Point::new(p[0], p[1]))).ok_or_else(|| bad(cmd, format!("`at` must be [x, y] (got {at})")))
}
(None, Some(r)) => numbers(r, 4)
.map(|r| Pick::Area(Rect::new(r[0], r[1], r[2], r[3]).abs()))
.ok_or_else(|| bad(cmd, format!("`rect` must be [x0, y0, x1, y1] (got {r})"))),
_ => Err(bad(cmd, format!("each pick is {{at: [x, y]}} or {{rect: [x0, y0, x1, y1]}} (got {v})"))),
}
}
}
/// A filled region: its outline and fill rule.
type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule);
/// An image the Color Theme Picker reads: its pixels, where it lies, the marquee it is read in
/// (`None`: all of it) and the region the clip groups around it show (`None`: unclipped). An
/// image its colorize paint applies to ([`vectorcraft_doc::ImageBlob::takes_colorize`]) gives that
/// paint's colours where a pixel read shows ink (opaque and darker than white).
#[derive(Clone)]
struct ImageRead<'a> {
blob: &'a vectorcraft_doc::ImageBlob,
xf: vectorcraft_geom::Affine,
size: (f64, f64),
area: Option<Rect>,
clip: Option<Vec<Region>>,
colorize: Option<Vec<Color>>,
}
/// The colours the Color Theme Picker has read: each object weighs 1, shared among its colours.
struct Theme<'a> {
d: &'a Document,
boxes: vectorcraft_doc::SymbolBoxes<'a>,
samples: Vec<(Color, f32)>,
/// The images to read, each image decoded once for all its reads ([`Self::read_images`]),
/// and the images they read.
images: Vec<ImageRead<'a>>,
blobs: std::collections::HashSet<*const vectorcraft_doc::ImageBlob>,
/// What the clip groups being read show, in document space: the union of these regions
/// (none: nothing shows); `None` outside clip groups.
clip: Option<Vec<Region>>,
/// The colours of the patterns read so far, and the patterns whose tiles are being read.
pattern_colors: HashMap<String, (Vec<Color>, Vec<ImageRead<'a>>)>,
pattern_stack: Vec<String>,
/// The region tests [`Self::shows`] has made.
work: std::cell::Cell<usize>,
/// The object isolated in isolation mode.
scope: Option<NodeId>,
/// The stroke segments opacity masks may still be outlined along ([`mask_regions`]).
mask_budget: usize,
objects: usize,
}
/// The region both `a` and `b` (each a union of regions) cover, filled non-zero.
fn intersect_regions(a: &[Region], b: &[Region]) -> Vec<Region> {
let paths: Vec<vectorcraft_geom::PathData> = a.iter().chain(b).map(|(bp, _)| vectorcraft_geom::PathData::from_bezpath(bp)).collect();
let inputs: Vec<(&vectorcraft_geom::PathData, vectorcraft_geom::FillRule)> =
paths.iter().zip(a.iter().chain(b)).map(|(p, (_, rule))| (p, *rule)).collect();
let split = a.len();
let both = vectorcraft_pathops::boolean_n(&inputs, |inside| inside.iter().any(|i| *i < split) && inside.iter().any(|i| *i >= split));
if both.subpaths.is_empty() { vec![] } else { vec![(both.to_bezpath(), vectorcraft_geom::FillRule::NonZero)] }
}
impl<'a> Theme<'a> {
fn new(d: &'a Document) -> Self {
Self {
d,
boxes: d.symbol_boxes(),
samples: vec![],
images: vec![],
blobs: std::collections::HashSet::new(),
clip: None,
pattern_colors: HashMap::new(),
pattern_stack: vec![],
work: std::cell::Cell::new(0),
scope: None,
mask_budget: MASK_OUTLINE_SEGMENTS,
objects: 0,
}
}
fn add(&mut self, colors: Vec<Color>) {
if colors.is_empty() {
return;
}
let w = 1.0 / colors.len() as f32;
self.samples.extend(colors.into_iter().map(|c| (c, w)));
self.objects += 1;
}
/// Read the images queued, each image's pixels decoded once, as colours: the pixels a read
/// gives that fall in one cell of 16 levels a channel merge into their average, weighted by how
/// many there are, and the cells of all the reads add up, so the images give at most 16³
/// colours. Images that can't be decoded give none. The first [`MAX_THEME_IMAGES`] images
/// are read, and all the reads share [`THEME_TOTAL_PIXELS`] pixels (each read at least one, at
/// most [`THEME_PIXELS`]).
fn read_images(&mut self) {
let reads = std::mem::take(&mut self.images);
// The reads of each image, in the order its first read came.
let mut by_image: Vec<(*const vectorcraft_doc::ImageBlob, Vec<&ImageRead>)> = vec![];
for r in &reads {
let key: *const vectorcraft_doc::ImageBlob = r.blob;
match by_image.iter().position(|(k, _)| *k == key) {
Some(i) => by_image[i].1.push(r),
None if by_image.len() < MAX_THEME_IMAGES => by_image.push((key, vec![r])),
None => {}
}
}
let count: usize = by_image.iter().map(|(_, g)| g.len()).sum();
let budget = (THEME_TOTAL_PIXELS / count.max(1)).clamp(1, THEME_PIXELS);
let mut pixels: HashMap<[u8; 3], ([f64; 3], f64)> = HashMap::new();
for (_, group) in by_image {
let keeps: Vec<Box<dyn Fn(f64, f64) -> bool + '_>> = group
.iter()
.map(|r| {
let (xf, (w, h), area, clip) = (r.xf, r.size, r.area, &r.clip);
Box::new(move |u: f64, v: f64| {
let p = xf * Point::new(u * w, v * h);
area.is_none_or(|a| a.contains(p))
&& clip.as_ref().is_none_or(|rs| rs.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)))
}) as Box<dyn Fn(f64, f64) -> bool + '_>
})
.collect();
let picks: Vec<vectorcraft_doc::PixelPick> = group
.iter()
.zip(&keeps)
.map(|(r, keep)| {
use vectorcraft_geom::kurbo::Shape;
let (w, h) = r.size;
let inv = r.xf.inverse();
// The box sampled: the marquee, cut to the clipping paths' bounds, so a small
// region a clip shows of a large image is still sampled densely.
let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default());
let region = match (r.area, clip_box) {
(Some(a), Some(c)) => Some(a.intersect(c)),
(a, c) => a.or(c),
};
let box_uv = region.map(|a| {
let uv: Vec<Point> =
[(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect();
let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min);
let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max);
[low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h]
});
(box_uv, keep.as_ref())
})
.collect();
// Each sampled pixel inside a clip group is tested against the clipping regions: the
// pixels one image gives keep that work within THEME_WORK path elements.
let elements =
group.iter().map(|r| r.clip.as_ref().map_or(0, |rs| rs.iter().map(|(bp, _)| bp.elements().len()).sum::<usize>())).max().unwrap_or(0);
let budget = THEME_WORK.checked_div(elements).map_or(budget, |w| budget.min(w.max(1)));
let Some(each) = group[0].blob.sample_pixels(&picks, budget) else { continue };
for (px, read) in each.into_iter().zip(&group) {
if let Some(colors) = &read.colorize {
// Ink: an opaque pixel darker than white takes the colorize paint.
if !colors.is_empty() && px.iter().any(|p| p[3] >= 128 && p[..3].iter().any(|v| *v < 255)) {
let w = 1.0 / colors.len().max(1) as f32;
self.samples.extend(colors.iter().map(|c| (*c, w)));
self.objects += 1;
}
continue;
}
let mut cells: HashMap<[u8; 3], ([u64; 3], u64)> = HashMap::new();
for [r, g, b, _] in px.into_iter().filter(|p| p[3] >= 128) {
let cell = cells.entry([r >> 4, g >> 4, b >> 4]).or_default();
for (sum, v) in cell.0.iter_mut().zip([r, g, b]) {
*sum += u64::from(v);
}
cell.1 += 1;
}
let total: u64 = cells.values().map(|c| c.1).sum();
if total == 0 {
continue;
}
for (key, (sum, n)) in cells {
let cell = pixels.entry(key).or_default();
for (acc, s) in cell.0.iter_mut().zip(sum) {
*acc += s as f64 / total as f64;
}
cell.1 += n as f64 / total as f64;
}
self.objects += 1;
}
}
let mut cells: Vec<_> = pixels.into_iter().collect();
// The same order on every run.
cells.sort_unstable_by_key(|c| c.0);
for (_, (sum, w)) in cells {
let [r, g, b] = sum.map(|s| (s / w).round().clamp(0.0, 255.0) as u8);
self.samples.push((Color::rgb8(r, g, b), w as f32));
}
}
/// Read `n` and everything visible inside it: each image (its part inside `area` when given,
/// and inside the clipping paths around it) and each other object with colours of its own
/// (that touches `area` when given, and shows inside the clipping paths around it). The art a
/// symbol instance shows (with a dynamic instance's own paints), placed where the instance
/// draws it, and the objects a blend, an envelope or a repeat draws elsewhere than they lie,
/// are read whole when the instance or the live object touches `area`. `depth` counts the
/// objects passed through: deeper art is left out. An enabled opacity mask that clips (and is
/// not inverted) shows the object only where its mask art is lighter than black
/// ([`mask_regions`]), as a clip group would.
fn read(&mut self, n: &Node, area: Option<Rect>, depth: usize) {
let Some(mask) = n.extras().mask.as_deref().filter(|m| !m.disabled && m.clip && !m.invert) else {
return self.read_unmasked(n, area, depth);
};
let regions = mask_regions(&mask.art, &mut self.mask_budget);
let outer = self.clip.clone();
self.clip = Some(match &outer {
None => regions,
Some(o) => intersect_regions(o, &regions),
});
self.read_unmasked(n, area, depth);
self.clip = outer;
}
/// [`Self::read`] without `n`'s opacity mask.
fn read_unmasked(&mut self, n: &Node, area: Option<Rect>, depth: usize) {
// Hidden and fully transparent objects show nothing.
if depth > MAX_THEME_DEPTH || !n.visible || n.opacity <= 0.0 || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return;
}
let touches = area.is_none_or(|r| self.touches(n, r));
match &n.kind {
NodeKind::Image(im) => {
if !touches {
return;
}
// A document keeps its images' pixels in its image store.
let Some(blob) = self.d.images.get(&im.key) else { return };
// An image with a colorize paint shows that paint's color, not its own pixels;
// other paints its appearance has (with effects that draw them) count as well.
let colorized = n.extras().colorize.is_some() && blob.takes_colorize();
let own = if colorized || n.extras().colorize.is_none() {
self.own(n, true)
} else {
// A colorize paint the image does not take (a linked image's preview)
// shows nothing.
let mut plain = n.clone();
plain.extras_mut().colorize = None;
self.own(&plain, true)
};
let colorize = if colorized {
Some(own)
} else {
if self.shows(n, area) {
self.add(own);
}
None
};
let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize });
return;
}
NodeKind::SymbolInstance { symbol, xf } => {
if touches
&& self.shows(n, area)
&& let Some(s) = self.d.symbols.iter().find(|s| s.name == *symbol)
{
// The instance's own paints; its overrides show in its art.
let own = self.own(n, false);
self.add(own);
// The art as the instance places it: through the symbol's 9-slice guides when
// it has them, else by the instance's transform. Art that would place too many
// objects is left out, as the renderer leaves it out.
let dynamic = (!n.extras().symbol_overrides.is_empty()).then(|| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n));
if let Some(placed) = self.d.place_symbol_art(symbol, dynamic.as_ref().unwrap_or(&s.art), *xf) {
// The vector art counts as one object, each of its colours once, so an
// object the 9-slice guides cut into several copies does not count more.
// Each image placed is read on its own, as images are elsewhere.
let (samples, objects) = (self.samples.len(), self.objects);
self.read(&placed, None, depth + 1);
let added = self.samples.split_off(samples);
self.objects = objects;
let mut seen = std::collections::HashSet::new();
let colors: Vec<Color> = added.into_iter().map(|(c, _)| c).filter(|c| seen.insert(ColorKey::of(c))).collect();
self.add(colors);
}
}
return;
}
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) => {
if touches && self.shows(n, area) {
let own = self.own(n, true);
self.add(own);
// The copies are drawn elsewhere than the objects lie: the clipping paths
// around the live object, tested above, do not apply to the objects.
let clip = self.clip.take();
for c in n.children().into_iter().flatten() {
self.read(c, None, depth + 1);
}
self.clip = clip;
}
return;
}
_ => {}
}
if touches && self.shows(n, area) {
let own = self.own(n, true);
self.add(own);
}
// A compound path's members are its geometry: the compound paints them.
if matches!(n.kind, NodeKind::Compound { .. }) {
return;
}
// A clip group's clipping path paints whole, over the art it clips: it is read in the
// marquee as given and under the clip groups around it alone.
let clip_child = n.children().and_then(|c| c.first()).filter(|_| n.clips());
if let Some(first) = clip_child {
self.read(first, area, depth + 1);
}
let inner = match area {
Some(r) => match vectorcraft_doc::hit::marquee_in(n, r) {
Some(inner) => Some(inner),
None => return,
},
None => None,
};
// A clip group shows its art where its clipping path's regions and the clip groups around
// it all show.
let outer = self.clip.clone();
if n.clips()
&& let Some(first) = n.children().and_then(|c| c.first())
{
let regions: Vec<Region> = vectorcraft_doc::hit::clip_regions(first);
self.clip = Some(match &outer {
None => regions,
Some(o) => intersect_regions(o, &regions),
});
}
// A Shaper Group's original shapes, which the group keeps but does not show, are left out.
for (i, c) in n.children().into_iter().flatten().enumerate().skip(usize::from(clip_child.is_some())) {
if !vectorcraft_doc::hit::shaper_hides(n, i, self.scope) {
self.read(c, inner, depth + 1);
}
}
self.clip = outer;
}
/// Does `n` show inside the region the clip groups around it show, in `area` when given? Its
/// box (cut to `area`) meets a region of it: the region's outline crosses the box, or a point
/// on a 9 × 9 grid over the part of the box inside the region's bounds lies in the region.
fn shows(&self, n: &Node, area: Option<Rect>) -> bool {
use vectorcraft_geom::kurbo::Shape;
let Some(regions) = &self.clip else { return true };
let Some(b) = n.visual_bounds_with(&self.boxes) else { return false };
let b = area.map_or(b, |r| b.intersect(r));
let valid = |r: &Rect| r.width() >= 0.0 && r.height() >= 0.0;
if !valid(&b) {
return false;
}
// A path or compound path paints along its outline, and inside it where it has a visible
// fill: a point along the outline, or (filled) a point of a 9 × 9 grid over the part of the
// box inside a region's bounds that lies in both its fill and the region, must show.
let filled = has_fill(n);
let outline: Option<(Vec<&vectorcraft_geom::PathData>, vectorcraft_geom::FillRule)> = match &n.kind {
NodeKind::Path { path, rule, .. } => Some((vec![path], *rule)),
NodeKind::Compound { children, rule } => Some((children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).collect(), *rule)),
_ => None,
};
if let Some((paths, own_rule)) = outline {
use vectorcraft_geom::ParamCurve;
use vectorcraft_geom::kurbo::ParamCurveArclen;
// The work all these tests do is bounded: past it, objects count as shown.
if self.work.get() > THEME_WORK {
return true;
}
let half = stroke_reach(n);
let cost: usize = regions.iter().map(|(bp, _)| bp.elements().len().max(1)).sum();
let in_region = |p: Point| {
// Past the work allowed, the outline counts as shown.
if self.work.get() > THEME_WORK {
return true;
}
self.work.set(self.work.get() + cost);
regions.iter().any(|(bp, rule)| {
vectorcraft_geom::hit::fill_contains(bp, *rule, p) || half > 0.0 && vectorcraft_geom::hit::stroke_contains(bp, 0.0, half, p)
})
};
let mut fill = vectorcraft_geom::BezPath::new();
for p in &paths {
fill.extend(p.to_bezpath().elements().iter().copied());
}
// At most 4,096 points along the outline, shared among its segments by length, no
// farther apart than half the smallest region's width or height where that allows.
let step = regions
.iter()
.map(|(bp, _)| bp.bounding_box())
.chain(area)
.map(|rb| rb.width().min(rb.height()))
.fold(f64::INFINITY, f64::min)
.max(0.01)
/ 2.0;
// With a marquee, only the outline inside it (within the stroke's reach) counts.
let picked = area.map(|r| r.inflate(half, half));
let segs: Vec<(vectorcraft_geom::PathSeg, f64)> = fill
.segments()
.take(4096)
.map(|s| {
let len = s.arclen(0.5);
(s, if len.is_finite() { len } else { 0.0 })
})
.collect();
let total: f64 = segs.iter().map(|(_, l)| l).sum();
let points = (total / step).ceil().clamp(64.0, 4096.0);
let along = segs.iter().any(|(seg, len)| {
let n = if total > 0.0 { (points * len / total).round().clamp(1.0, 4096.0) as u32 } else { 1 };
(0..=n).any(|i| {
let p = seg.eval(f64::from(i) / f64::from(n));
picked.is_none_or(|r| r.contains(p)) && in_region(p)
})
});
return along
|| filled
&& regions.iter().any(|(bp, _)| {
let g = b.intersect(bp.bounding_box());
valid(&g)
&& (0..81).any(|i| {
let p = Point::new(g.x0 + g.width() * f64::from(i % 9) / 8.0, g.y0 + g.height() * f64::from(i / 9) / 8.0);
in_region(p) && vectorcraft_geom::hit::fill_contains(&fill, own_rule, p)
})
});
}
regions.iter().any(|(bp, rule)| {
let g = b.intersect(bp.bounding_box());
valid(&g)
&& (vectorcraft_geom::hit::intersects_rect(&vectorcraft_geom::PathData::from_bezpath(bp), b)
|| (0..81).any(|i| {
let p = Point::new(g.x0 + g.width() * f64::from(i % 9) / 8.0, g.y0 + g.height() * f64::from(i / 9) / 8.0);
vectorcraft_geom::hit::fill_contains(bp, *rule, p)
}))
})
}
/// Does the marquee `r` touch what `n` paints? A path or a compound path is touched where its
/// outline comes within half its widest visible stroke of `r` or, when it has a visible fill,
/// where `r`'s centre lies in that fill; any other object is touched by its box.
fn touches(&self, n: &Node, r: Rect) -> bool {
let boxed = n.visual_bounds_with(&self.boxes).is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1);
let filled = || has_fill(n);
let half = stroke_reach(n);
let near = r.inflate(half, half);
let crosses = |paths: &[&vectorcraft_geom::PathData], rule: vectorcraft_geom::FillRule| {
paths.iter().any(|p| vectorcraft_geom::hit::intersects_rect(p, near))
|| filled() && {
let mut bp = vectorcraft_geom::BezPath::new();
for p in paths {
bp.extend(p.to_bezpath().elements().iter().copied());
}
// A point on a 5 × 5 grid over the part of the marquee in the path's box lies
// in its fill.
use vectorcraft_geom::kurbo::Shape;
let g = r.intersect(bp.bounding_box());
g.width() >= 0.0
&& g.height() >= 0.0
&& (0..25).any(|i| {
let p = Point::new(g.x0 + g.width() * f64::from(i % 5) / 4.0, g.y0 + g.height() * f64::from(i / 5) / 4.0);
vectorcraft_geom::hit::fill_contains(&bp, rule, p)
})
}
};
match &n.kind {
NodeKind::Path { path, rule, .. } => boxed && crosses(&[path], *rule),
NodeKind::Compound { children, rule } => {
let paths: Vec<&vectorcraft_geom::PathData> = children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).collect();
boxed && crosses(&paths, *rule)
}
_ => boxed,
}
}
}
/// The regions where opacity mask art `art` lets the masked object show: the regions
/// ([`vectorcraft_doc::hit::clip_regions`]) of its visible paths and compound paths filled lighter
/// than black (a solid color, a gradient with a stop lighter than black, or a pattern), the
/// outlines of the strokes lighter than black they have (dashes read as solid), the frames of its
/// images, the boxes of its type painted lighter than black, the boxes of art with effects (with
/// what the effects reach), and the regions of its clip groups and live objects whole. Black,
/// unfilled and unstroked paths without effects hide; how light the art is beyond that is not
/// read. Strokes are outlined along at most `budget` segments in all (it counts down); past that
/// a stroke counts by its box grown by half its width.
fn mask_regions(art: &Node, budget: &mut usize) -> Vec<Region> {
// Any color but black lets the masked art show.
fn light(p: &Paint) -> bool {
let lit = |c: &Color| c.to_rgba8(1.0)[..3].iter().any(|v| *v > 0);
match p {
Paint::None => false,
Paint::Solid { color, .. } => lit(color),
Paint::Gradient(g) => g.gradient.stops.iter().any(|s| lit(&s.color)),
_ => true,
}
}
fn walk(n: &Node, depth: usize, out: &mut Vec<Region>, budget: &mut usize) {
use vectorcraft_geom::kurbo::Shape;
// The mask art's root masks even when it is hidden.
// Guides draw nothing.
if depth > MAX_THEME_DEPTH || depth > 0 && (!n.visible || n.opacity <= 0.0) || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return;
}
// Art with effects can show light anywhere near it (a glow on black art): it counts
// whole, as a clipping path would.
let effects = !n.appearance.effects.is_empty()
|| n.appearance.items.iter().any(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(l) => l.visible && !l.effects.is_empty(),
vectorcraft_doc::AppearanceItem::Stroke(l) => l.visible && !l.effects.is_empty(),
});
if effects {
if let Some(b) = n.visual_bounds() {
out.push((b.to_path(0.1), vectorcraft_geom::FillRule::NonZero));
}
return;
}
let lit = n
.appearance
.items
.iter()
.any(|it| matches!(it, vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 && light(&l.paint)));
let stroke = n
.appearance
.items
.iter()
.filter_map(|it| match it {
vectorcraft_doc::AppearanceItem::Stroke(l) if l.visible && l.opacity > 0.0 && l.width > 0.0 && light(&l.paint) => Some(l.width / 2.0),
_ => None,
})
.fold(None, |a: Option<f64>, w| Some(a.map_or(w, |a| a.max(w))));
let boxed = |out: &mut Vec<Region>| {
if let Some(b) = n.geometric_bounds() {
out.push((b.to_path(0.1), vectorcraft_geom::FillRule::NonZero));
}
};
match &n.kind {
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
if lit {
out.extend(vectorcraft_doc::hit::clip_regions(n));
}
// A stroke shows the art along it: its outline with round ends and corners, a
// dashed stroke read as solid (the most it can show).
if let Some(half) = stroke {
let paths: Vec<&vectorcraft_geom::PathData> = match &n.kind {
NodeKind::Path { path, .. } => vec![path],
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).collect(),
_ => vec![],
};
for p in paths {
// Past MASK_OUTLINE_SEGMENTS outlined segments, a stroke counts by its
// box grown by half its width.
let segments = p.to_bezpath().elements().len();
if *budget < segments {
if let Some(b) = p.bounds().filter(|_| half.is_finite()) {
out.push((b.inflate(half, half).to_path(0.1), vectorcraft_geom::FillRule::NonZero));
}
continue;
}
*budget -= segments;
let region = vectorcraft_pathops::outline_stroke(
p,
half * 2.0,
vectorcraft_pathops::Cap::Round,
vectorcraft_pathops::Join::Round,
10.0,
);
if !region.subpaths.is_empty() {
out.push((region.to_bezpath(), vectorcraft_geom::FillRule::NonZero));
}
}
}
}
NodeKind::Image(_) => out.extend(vectorcraft_doc::hit::clip_regions(n)),
NodeKind::Text(t) => {
if lit || stroke.is_some() || t.runs.iter().any(|r| light(&r.style.fill) || r.style.stroke_width > 0.0 && light(&r.style.stroke)) {
boxed(out);
}
}
NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } => {
// A Shaper Group's original shapes are kept but not drawn.
for (i, c) in n.children().into_iter().flatten().enumerate() {
if !vectorcraft_doc::hit::shaper_hides(n, i, None) {
walk(c, depth + 1, out, budget);
}
}
}
// Clip groups, live objects and placed documents count by the regions they clip to.
_ => out.extend(vectorcraft_doc::hit::clip_regions(n)),
}
}
let mut out = vec![];
walk(art, 0, &mut out, budget);
out
}
/// Does `n` have a fill item that paints: visible, not fully transparent and not None?
fn has_fill(n: &Node) -> bool {
n.appearance
.items
.iter()
.any(|it| matches!(it, vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 && !matches!(l.paint, Paint::None)))
}
/// How far `n`'s widest painting stroke reaches from its path: half its width (0 without one).
fn stroke_reach(n: &Node) -> f64 {
let paints = |l: &vectorcraft_doc::StrokeLayer| l.visible && l.opacity > 0.0 && !matches!(l.paint, Paint::None) && l.width.is_finite();
n.appearance
.items
.iter()
.filter_map(|it| match it {
vectorcraft_doc::AppearanceItem::Stroke(l) if paints(l) => Some(l.width.max(0.0) / 2.0),
_ => None,
})
.fold(0.0, f64::max)
}
/// The paints `m` shows: its visible fill items and its visible strokes wider than 0, its text's
/// fills and strokes wider than 0, and its colorize paint.
fn shown_paints(m: &Node) -> impl Iterator<Item = &Paint> {
let runs = match &m.kind {
NodeKind::Text(t) => t.runs.as_slice(),
_ => &[],
};
let items = m.appearance.items.iter().filter_map(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(l) if l.visible && l.opacity > 0.0 => Some(&l.paint),
vectorcraft_doc::AppearanceItem::Stroke(l) if l.visible && l.opacity > 0.0 && l.width > 0.0 => Some(&l.paint),
_ => None,
});
let text = runs.iter().flat_map(|r| std::iter::once(&r.style.fill).chain((r.style.stroke_width > 0.0).then_some(&r.style.stroke)));
items.chain(text).chain(m.extras().colorize.as_deref())
}
/// Add the colours `m` shows itself to `out` (solid colours, gradient stops, its text's colours
/// and its mesh points; the paints a dynamic symbol instance keeps for objects of its art only
/// when `overrides` is set), and the names of the patterns it paints with to `patterns`, leaving
/// out names already there.
fn paint_colors_of(m: &Node, overrides: bool, out: &mut Vec<Color>, patterns: &mut Vec<String>) {
let kept = override_paints(m).filter(|_| overrides);
for p in shown_paints(m).chain(kept) {
match p {
Paint::Solid { color, .. } => out.push(*color),
Paint::Gradient(g) => out.extend(g.gradient.stops.iter().map(|s| s.color)),
Paint::Pattern { pattern, .. } if !patterns.contains(pattern) => patterns.push(pattern.clone()),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
out.extend(mesh.points.iter().map(|p| p.color));
}
}
impl<'a> Theme<'a> {
/// Queue image read `r`, within the limits of a pick: at most [`MAX_THEME_READS`] reads of
/// [`MAX_THEME_IMAGES`] images; nothing inside clip groups that show nothing.
fn queue_image(&mut self, r: ImageRead<'a>) {
if self.images.len() >= MAX_THEME_READS || r.clip.as_ref().is_some_and(Vec::is_empty) {
return;
}
let key: *const vectorcraft_doc::ImageBlob = r.blob;
if !self.blobs.contains(&key) {
if self.blobs.len() >= MAX_THEME_IMAGES {
return;
}
self.blobs.insert(key);
}
self.images.push(r);
}
/// The colours `m` paints itself ([`paint_colors_of`]; a dynamic symbol instance's paints for
/// objects of its art only with `overrides`), and the colours its pattern tiles show, read as
/// document art is read (clip groups and symbols included; the tiles' images join this pick's
/// image reads). Each pattern's colours
/// are read once; a pattern whose tile uses itself, directly or through other patterns, adds
/// nothing more the second time.
fn own(&mut self, m: &Node, overrides: bool) -> Vec<Color> {
let mut out = vec![];
let mut patterns: Vec<String> = vec![];
paint_colors_of(m, overrides, &mut out, &mut patterns);
for name in patterns {
if let Some((colors, reads)) = self.pattern_colors.get(&name) {
out.extend(colors);
// The tiles' images count again for each use, within the pick's limits.
let reads = reads.clone();
for r in reads {
self.queue_image(r);
}
continue;
}
if self.pattern_stack.contains(&name) || self.pattern_stack.len() >= MAX_THEME_DEPTH {
continue;
}
let Some(def) = self.d.pattern(&name) else { continue };
let mut sub = Theme::new(self.d);
sub.pattern_stack = std::mem::take(&mut self.pattern_stack);
sub.pattern_stack.push(name.clone());
sub.pattern_colors = std::mem::take(&mut self.pattern_colors);
// The tiles' images join this pick's image reads, within its limits.
sub.images = std::mem::take(&mut self.images);
sub.blobs = std::mem::take(&mut self.blobs);
// The tiles share this pick's limits on work too.
sub.work.set(self.work.get());
sub.mask_budget = self.mask_budget;
let before = sub.images.len();
for a in &def.art {
sub.read(a, None, 0);
}
sub.pattern_stack.pop();
self.pattern_stack = std::mem::take(&mut sub.pattern_stack);
self.pattern_colors = std::mem::take(&mut sub.pattern_colors);
let reads: Vec<ImageRead<'a>> = sub.images.get(before..).unwrap_or_default().to_vec();
self.images = std::mem::take(&mut sub.images);
self.blobs = std::mem::take(&mut sub.blobs);
self.work.set(sub.work.get());
self.mask_budget = sub.mask_budget;
let colors: Vec<Color> = sub.samples.iter().map(|(c, _)| *c).collect();
out.extend(&colors);
self.pattern_colors.insert(name, (colors, reads));
}
out
}
}
fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "recolor.pickTheme";
let picks = match p.get("picks") {
Some(Value::Array(a)) if !a.is_empty() && a.len() <= MAX_PICKS => a.iter().map(|v| Pick::param(v, C)).collect::<Result<Vec<_>>>()?,
Some(Value::Array(a)) => return Err(bad(C, format!("`picks` must hold 1 to {MAX_PICKS} picks (got {})", a.len()))),
Some(v) => return Err(bad(C, format!("`picks` must be an array (got {v})"))),
None => return Err(bad(C, "missing `picks`")),
};
let n = super::menucmds::whole_or(p, "colors", 5, C)?;
if !(1..=MAX_THEME_COLORS).contains(&n) {
return Err(bad(C, format!("`colors` must be between 1 and {MAX_THEME_COLORS} (got {n})")));
}
let st = s.doc()?;
let d = &st.doc;
let mut theme = Theme::new(d);
theme.scope = st.isolation;
// In isolation mode: the isolated object, everything inside it and the containers around it.
let scope: Option<std::collections::HashSet<NodeId>> = st.isolation.and_then(|iso| d.node(iso)).map(|iso| {
let mut allowed = std::collections::HashSet::new();
iso.walk(&mut |m| {
allowed.insert(m.id);
});
let mut up = d.parent_of(iso.id);
while let Some(p) = up {
allowed.insert(p);
up = d.parent_of(p);
}
allowed
});
for pick in picks {
match pick {
Pick::At(pt) => {
// In isolation mode only the isolated art (and the groups around it) can be hit;
// isolated Shaper Group originals are hittable then.
let opt = vectorcraft_doc::hit::HitOptions { scope: st.isolation, ..Default::default() };
let hit = match &scope {
Some(allowed) => vectorcraft_doc::hit::hit_test_visible_skipping(d, pt, opt, &|id| !allowed.contains(&id)),
None => vectorcraft_doc::hit::hit_test_visible(d, pt, opt),
};
if let Some(n) = hit.and_then(|h| d.node(h.top_object(st.isolation))) {
theme.read(n, None, 0);
}
}
Pick::Area(r) => match st.isolation.and_then(|iso| d.node(iso)) {
// In isolation mode a marquee reads the isolated art alone.
Some(iso) => theme.read(iso, Some(r), 0),
None => {
for l in &d.layers {
theme.read(l, Some(r), 0);
}
}
},
}
}
theme.read_images();
let colors = vectorcraft_color::recolor::theme_palette(&theme.samples, index(n));
Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects}))
}
/// A colour the art uses: how often, and the global swatch it is linked to.
struct Used {
color: Color,
+23 -1
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes Line truncated
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such a Line truncated
has_doc,
set_range_style
),
@@ -459,6 +459,9 @@ pub(crate) struct CharChange {
/// Tate-chu-yoko Settings › Up/Down and Left/Right, in points.
tcy_up_down: Option<f64>,
tcy_left_right: Option<f64>,
/// Insert Aki Left and Right, in 1/1000 em.
aki_left: Option<f64>,
aki_right: Option<f64>,
standard_vertical_roman: Option<bool>,
no_break: Option<bool>,
digits: Option<vectorcraft_doc::Digits>,
@@ -492,6 +495,15 @@ pub(crate) fn tcy_offset_param(p: &Value, key: &str, cmd: &str) -> Result<Option
if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) }
}
/// `akiLeft` or `akiRight` (Insert Aki Left and Right): a number of thousandths of an em from 0 to
/// [`vectorcraft_doc::text::MAX_AKI`]. Any other value is an error.
pub(crate) fn aki_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) };
let v = v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?;
let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI);
if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) }
}
/// `digits: "default"|"arabic"|"hindi"|"farsi"|"devanagari"|…` ([`Digits::id`]) → the numeral
/// system the digits are drawn in.
///
@@ -754,6 +766,8 @@ impl CharChange {
tate_chu_yoko: flag("tateChuYoko"),
tcy_up_down: tcy_offset_param(p, "tcyUpDown", cmd)?,
tcy_left_right: tcy_offset_param(p, "tcyLeftRight", cmd)?,
aki_left: aki_param(p, "akiLeft", cmd)?,
aki_right: aki_param(p, "akiRight", cmd)?,
standard_vertical_roman: flag("standardVerticalRoman"),
no_break: flag("noBreak"),
digits: digits_param(p, cmd)?,
@@ -811,6 +825,8 @@ impl CharChange {
&& self.tate_chu_yoko.is_none()
&& self.tcy_up_down.is_none()
&& self.tcy_left_right.is_none()
&& self.aki_left.is_none()
&& self.aki_right.is_none()
&& self.standard_vertical_roman.is_none()
&& self.no_break.is_none()
&& self.digits.is_none()
@@ -877,6 +893,12 @@ impl CharChange {
if let Some(v) = self.tcy_left_right {
st.tcy_left_right = v;
}
if let Some(v) = self.aki_left {
st.aki_left = v;
}
if let Some(v) = self.aki_right {
st.aki_right = v;
}
if let Some(v) = self.standard_vertical_roman {
st.standard_vertical_roman = v;
}
+12 -2
View File
@@ -215,6 +215,8 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("tateChuYoko", json!(v.tate_chu_yoko)),
("tcyUpDown", json!(v.tcy_up_down)),
("tcyLeftRight", json!(v.tcy_left_right)),
("akiLeft", json!(v.aki_left)),
("akiRight", json!(v.aki_right)),
("standardVerticalRoman", json!(v.standard_vertical_roman)),
("noBreak", json!(v.no_break)),
("digits", json!(v.digits)),
@@ -558,6 +560,12 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
}
}
let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI);
for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] {
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
// A language of the list, stored as its tag (as text.setFormat takes it).
if let Some(l) = &st.language
&& kept.and_then(|k| k.get("language")) != m.get("language")
@@ -1042,17 +1050,19 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, whose
/// scales, leading, shifts, Insert Aki or stroke width are out of the range `charStyle.new` takes, whose
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
/// `src` of those skipped)
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
const RANGED: [&str; 16] = [
const RANGED: [&str; 18] = [
"size",
"h_scale",
"v_scale",
"leading",
"baseline_shift",
"akiLeft",
"akiRight",
"tcyUpDown",
"tcyLeftRight",
"stroke_width",
+4 -1
View File
@@ -395,6 +395,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
json!({"baseline_shift": 1296.1}),
json!({"tcyUpDown": 1296.1}),
json!({"tcyLeftRight": -1296.1}),
json!({"akiLeft": -0.1}),
json!({"akiRight": 1000.1}),
] {
let key = attrs.as_object().unwrap().keys().next().unwrap();
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
@@ -416,7 +418,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
"size": 1296.0, "leading": 5000.0,
"h_scale": 1.0, "v_scale": 10000.0,
"baseline_shift": -1296.0,
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
"akiLeft": 0.0, "akiRight": 1000.0
}}),
)
.unwrap();
@@ -1663,6 +1663,63 @@ fn tate_chu_yoko_settings_are_character_attributes_saved_only_when_set() {
assert_eq!(offsets(&s), before);
}
/// Insert Aki Left and Right (Character panel, East Asian options): character attributes in
/// thousandths of an em, 0 by default and saved only when not 0. Both commands set either side
/// alone, keeping the other side of every run, in one undo step; a value that is not a number or
/// lies outside 0 to 1000 is refused, naming the key, before anything changes; a character style
/// captured from the characters carries them.
#[test]
fn insert_aki_is_a_character_attribute_set_one_side_at_a_time() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "(日本)"})).unwrap()["id"].as_u64().unwrap();
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("text"),
};
let aki = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.aki_left, r.style.aki_right)).collect::<Vec<_>>();
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none());
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"akiLeft": 250})).unwrap();
assert_eq!(aki(&s), [("(日本)".to_string(), 250.0, 0.0)]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(aki(&s), [("(日本)".to_string(), 0.0, 0.0)], "one undo step");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(aki(&s), [("(日本)".to_string(), 250.0, 0.0)]);
// One side on part of the text: the runs keep their other side.
let paren = "(".len();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": paren, "akiRight": 500})).unwrap();
assert_eq!(aki(&s), [("(".to_string(), 250.0, 500.0), ("日本)".to_string(), 250.0, 0.0)]);
s.execute("text.setFormat", &json!({"akiLeft": 0})).unwrap();
assert_eq!(aki(&s), [("(".to_string(), 0.0, 500.0), ("日本)".to_string(), 0.0, 0.0)]);
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
assert_eq!((saved.get("akiLeft"), saved["akiRight"].clone()), (None, json!(500.0)));
// Saved and reopened as they were.
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.aki_left, r.style.aki_right)).collect();
assert_eq!(reopened, aki(&s));
let attrs = super::super::textstyles::char_attrs(&runs(&s)[0].style);
assert_eq!((attrs["akiLeft"].clone(), attrs["akiRight"].clone()), (json!(0.0), json!(500.0)));
let before = aki(&s);
let undo = s.doc().unwrap().history.undo.len();
for (cmd, p, want) in [
("text.setFormat", json!({"akiLeft": "250"}), "`akiLeft` must be a number"),
("text.setFormat", json!({"akiRight": -1}), "`akiRight` must be from 0 to 1000"),
("text.setFormat", json!({"akiLeft": 250, "akiRight": 1000.5}), "`akiRight` must be from 0 to 1000"),
("text.setRangeStyle", json!({"id": id, "akiRight": true}), "`akiRight` must be a number"),
("text.setRangeStyle", json!({"id": id, "start": 0, "end": paren, "akiLeft": 2000}), "`akiLeft` must be from 0 to 1000"),
] {
let e = s.execute(cmd, &p).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}");
}
assert_eq!(aki(&s), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
}
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character
/// attribute, off by default and saved only when on. Documents written before it read as off; a
/// character style captured from the characters carries it.
+3 -3
View File
@@ -2179,8 +2179,8 @@ fn failure_text(report: &Value) -> String {
let s = |k: &str| report[k].as_str().unwrap_or_default();
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
let at = match report["file"].as_str() {
Some(file) if line > 0 => format!(" line {line}, column {column} of {file}"),
_ if line > 0 => format!(" line {line}, column {column}"),
Some(file) if line > 0 => format!(": line {line}, column {column} of {file}"),
_ if line > 0 => format!(": line {line}, column {column}"),
_ => String::new(),
};
let written = report["written"].as_array().map_or(0, Vec::len);
@@ -2190,7 +2190,7 @@ fn failure_text(report: &Value) -> String {
} else {
String::new()
};
format!("{}:{at}: {} ({}){kept}", s("name"), s("message"), s("kind"))
format!("{}{at}: {} ({}){kept}", s("name"), s("message"), s("kind"))
}
/// A run's slice: the working copy in, the real session lent to the host functions, one measured
+216
View File
@@ -492,6 +492,222 @@ fn pasting_again_reuses_what_an_earlier_paste_added() {
assert!(doc(&s).swatch("Brand 3").is_none() && doc(&s).char_styles.len() == 1);
}
/// The active document, to edit its definitions directly.
fn doc_mut(s: &mut Session) -> &mut Document {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
}
/// The pattern a paint paints with.
fn pattern_of(p: &Paint) -> Option<&str> {
match p {
Paint::Pattern { pattern, .. } => Some(pattern),
_ => None,
}
}
/// The pattern the fill of the active document's character style `name` paints with.
fn style_pattern(s: &Session, name: &str) -> Option<String> {
let attrs = &doc(s).char_styles.iter().find(|x| x.name == name)?.attrs;
pattern_of(&serde_json::from_value::<Paint>(attrs.get("fill")?.clone()).ok()?).map(str::to_string)
}
/// A pattern "Dots" made from a `size` square of `color` in the active document.
fn dots(s: &mut Session, size: f64, color: &str) {
let square = rect(s, 300.0, 200.0, size, size);
s.execute("paint.setFill", &json!({"ids": [square.0], "color": color})).unwrap();
s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [square.0]})).unwrap();
}
/// Type "Hi" filled with the pattern "Dots" (a small red square), set in a character style
/// "Patterned" whose fill is that pattern.
fn patterned_type(s: &mut Session) -> NodeId {
dots(s, 10.0, "#ff0000");
let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap());
s.execute("paint.setFill", &json!({"ids": [t.0], "swatch": "Dots"})).unwrap();
s.execute("charStyle.new", &json!({"name": "Patterned", "id": t.0})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Patterned", "id": t.0})).unwrap();
t
}
/// The character style name of a type object's first run, and the pattern that run paints with.
fn type_links(s: &Session, id: NodeId) -> (Option<String>, Option<String>) {
let NodeKind::Text(tx) = node(s, id).kind else { panic!("not type") };
(tx.runs[0].style.style_name.clone(), pattern_of(&tx.runs[0].style.fill).map(str::to_string))
}
/// Type set in a style that paints with a pattern, pasted into a document with another pattern of
/// that name: the pattern comes in as "Dots 2", and the style paints with "Dots 2" too, so applying
/// it later paints with the pasted pattern. Pasting again adds nothing.
#[test]
fn pasted_styles_paint_with_the_renamed_pattern_they_use() {
let mut s = session();
let t = patterned_type(&mut s);
copy(&mut s, &[t]);
new_doc(&mut s);
dots(&mut s, 30.0, "#0000ff");
let v = s.execute("edit.paste", &json!({})).unwrap();
assert!(doc(&s).pattern("Dots 2").is_some(), "{v}");
assert_eq!(style_pattern(&s, "Patterned").as_deref(), Some("Dots 2"), "{v}");
let named = |n: &str| Some(n.to_string());
assert_eq!(type_links(&s, ids_of(&v)[0]), (named("Patterned"), named("Dots 2")));
let other = id_of(&s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Yo"})).unwrap());
s.execute("charStyle.apply", &json!({"name": "Patterned", "id": other.0})).unwrap();
assert_eq!(type_links(&s, other).1.as_deref(), Some("Dots 2"), "the applied style paints with the pasted pattern");
let counts = |s: &Session| (doc(s).patterns.len(), doc(s).char_styles.len());
let before = counts(&s);
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
assert_eq!(counts(&s), before);
assert_eq!(type_links(&s, ids_of(&v)[0]), (named("Patterned"), named("Dots 2")));
}
/// A document whose "Patterned" style has the pasted style's attributes but whose "Dots" is
/// another pattern: that style paints with the document's "Dots", so the pasted one comes in as
/// "Patterned 2", painting with "Dots 2", and the document's own is left as it was. Pasting again
/// uses the numbered copies.
#[test]
fn pasted_styles_are_not_matched_to_styles_that_paint_with_another_pattern() {
let mut s = session();
let t = patterned_type(&mut s);
let style = doc(&s).char_styles.iter().find(|x| x.name == "Patterned").unwrap().clone();
copy(&mut s, &[t]);
new_doc(&mut s);
dots(&mut s, 30.0, "#0000ff");
doc_mut(&mut s).char_styles.push(style);
let own = (doc(&s).char_styles.clone(), doc(&s).pattern("Dots").cloned());
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(style_pattern(&s, "Patterned 2").as_deref(), Some("Dots 2"), "{v}");
let d = doc(&s);
assert_eq!((&d.char_styles[..own.0.len()], d.pattern("Dots")), (&own.0[..], own.1.as_ref()), "the document's own are unchanged");
let named = |n: &str| Some(n.to_string());
let links = (named("Patterned 2"), named("Dots 2"));
assert_eq!(type_links(&s, ids_of(&v)[0]), links);
let counts = |s: &Session| (doc(s).patterns.len(), doc(s).char_styles.len());
let before = counts(&s);
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
assert_eq!(counts(&s), before);
assert_eq!(type_links(&s, ids_of(&v)[0]), links);
}
/// A style that paints with a pattern whose tile sets type in that same style is pasted with the
/// pattern: when the pattern comes in as "Dots 2", the style paints with "Dots 2", and the tile's
/// type is set in the style. Pasting again adds nothing. The commands do not make that loop, so the
/// source is a document edited directly.
#[test]
fn a_pasted_style_and_the_pattern_whose_tile_uses_it_come_in_together() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Tile"})).unwrap());
s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Accent", "id": t.0})).unwrap();
s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [t.0]})).unwrap();
let other = id_of(&s.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap());
s.execute("charStyle.apply", &json!({"name": "Accent", "id": other.0})).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [other.0]})).unwrap();
s.execute("charStyle.new", &json!({"name": "Painted", "id": other.0})).unwrap();
let d = doc_mut(&mut s);
let painted = d.char_styles.iter().find(|x| x.name == "Painted").unwrap().attrs.clone();
d.char_styles.retain(|x| x.name != "Painted");
d.char_styles.iter_mut().find(|x| x.name == "Accent").unwrap().attrs = painted;
assert_eq!(style_pattern(&s, "Accent").as_deref(), Some("Dots"));
copy(&mut s, &[other]);
new_doc(&mut s);
dots(&mut s, 30.0, "#0000ff");
let v = s.execute("edit.paste", &json!({})).unwrap();
assert!(doc(&s).pattern("Dots 2").is_some(), "{v}");
assert_eq!(style_pattern(&s, "Accent").as_deref(), Some("Dots 2"), "{v}");
let NodeKind::Text(tile) = &doc(&s).pattern("Dots 2").unwrap().art[0].kind else { panic!("the tile is type") };
assert_eq!(tile.runs[0].style.style_name.as_deref(), Some("Accent"));
let after = doc(&s).clone();
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
assert!(doc(&s).patterns == after.patterns && doc(&s).char_styles == after.char_styles, "nothing is added");
// Back in the source document, the loop is the document's own.
s.execute("document.activate", &json!({"index": 0})).unwrap();
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!((v["added"].as_u64(), v["renamed"].as_array().map(Vec::len)), (Some(0), Some(0)), "{v}");
}
/// A symbol whose art paints with a pattern is not matched to the document's symbol of that name
/// and art when the document's pattern of that name is another one: it comes in as "Mark 2",
/// painting with "Dots 2".
#[test]
fn pasted_symbols_are_not_matched_to_symbols_that_paint_with_another_pattern() {
let mut s = session();
dots(&mut s, 10.0, "#ff0000");
let r = rect(&mut s, 20.0, 20.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [r.0], "swatch": "Dots"})).unwrap();
sel(&mut s, &[r]);
let mark = id_of(&s.execute("symbol.new", &json!({"name": "Mark"})).unwrap());
copy(&mut s, &[mark]);
// The document gets "Mark" and "Dots" from a first paste; then its "Dots" gets another tile.
new_doc(&mut s);
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["renamed"], json!([]), "{v}");
let tile = &mut doc_mut(&mut s).patterns.iter_mut().find(|p| p.name == "Dots").unwrap().tile;
*tile = Rect::new(tile.x0, tile.y0, tile.x1 + 30.0, tile.y1 + 30.0);
let v = s.execute("edit.paste", &json!({})).unwrap();
assert!(renamed(&v).contains(&("symbol".to_string(), "Mark".to_string(), "Mark 2".to_string())), "{v}");
let art = |s: &Session, name: &str| fill_of(&doc(s).symbols.iter().find(|x| x.name == name).unwrap().art);
assert_eq!((art(&s, "Mark").as_deref(), art(&s, "Mark 2").as_deref()), (Some("Dots"), Some("Dots 2")));
assert!(matches!(node(&s, ids_of(&v)[0]).kind, NodeKind::SymbolInstance { ref symbol, .. } if symbol == "Mark 2"));
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
}
/// The pattern the first filled object in `n` paints with.
fn fill_of(n: &Node) -> Option<String> {
let mut found = None;
n.walk(&mut |m| {
if found.is_none() {
found = pattern_of(&m.appearance.fill_paint()).map(str::to_string);
}
});
found
}
/// A brush whose art sets type in a character style is not matched to the document's brush of
/// that name and art when the document's style of that name is another one: the style comes in as
/// "Accent 2", and the brush as a copy whose type is set in "Accent 2".
#[test]
fn pasted_brushes_are_not_matched_to_brushes_that_use_another_style() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ink"})).unwrap());
s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Accent", "id": t.0})).unwrap();
let name = s.execute("brush.new", &json!({"type": "art", "name": "Lettering", "ids": [t.0]})).unwrap()["name"].as_str().unwrap().to_string();
let path = rect(&mut s, 200.0, 200.0, 40.0, 10.0);
s.execute("brush.apply", &json!({"name": name, "ids": [path.0]})).unwrap();
let brush = vectorcraft_brush::find(doc(&s), &name).unwrap();
copy(&mut s, &[path]);
new_doc(&mut s);
s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 10}})).unwrap();
let d = doc_mut(&mut s);
let mut lib = vectorcraft_brush::library(d);
lib.push(brush);
vectorcraft_brush::store(d, &lib);
let v = s.execute("edit.paste", &json!({})).unwrap();
let names = renamed(&v);
let copied = names.iter().find(|(k, from, _)| k == "brush" && *from == name).map(|(_, _, to)| to.clone());
assert!(names.contains(&("charStyle".to_string(), "Accent".to_string(), "Accent 2".to_string())), "{v}");
let copied = copied.unwrap_or_else(|| panic!("the brush is added under a free name: {v}"));
let style_of = |s: &Session, b: &str| {
let b = vectorcraft_brush::find(doc(s), b).unwrap();
let mut found = None;
for a in b.art() {
a.walk(&mut |m| {
if let NodeKind::Text(tx) = &m.kind {
found = found.take().or_else(|| tx.runs[0].style.style_name.clone());
}
});
}
found
};
assert_eq!((style_of(&s, &name).as_deref(), style_of(&s, &copied).as_deref()), (Some("Accent"), Some("Accent 2")));
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
}
#[test]
fn brushes_travel_with_their_strokes() {
let mut s = session();
+3 -1
View File
@@ -77,10 +77,12 @@ fn saturate_needs_a_number_intensity() {
let mut s = session();
let a = rect(&mut s, json!("#cc6666"));
let undo = s.doc().unwrap().history.undo.len();
for p in [json!({}), json!({"intensity": "40"}), json!({"intensity": null})] {
for p in [json!({}), json!({"intensity": null})] {
let e = s.execute("edit.colors.saturate", &p).unwrap_err().to_string();
assert!(e.contains("missing number `intensity`"), "{p}: {e}");
}
let e = s.execute("edit.colors.saturate", &json!({"intensity": "40"})).unwrap_err().to_string();
assert!(e.contains("`intensity` must be a number, not \"40\""), "{e}");
assert_eq!(fill_of(&s, a).to_hex(), "#cc6666");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
s.execute("edit.colors.saturate", &json!({"intensity": 100})).unwrap();
+39
View File
@@ -104,6 +104,45 @@ fn the_object_brought_over_shows_no_seam_of_the_one_below() {
assert!(worst < 8, "blue shows through ring A at the top crossing (blue {worst})");
}
fn green(r: &Rendered, x: u32, y: u32) -> bool {
let p = r.pixel(x, y);
p[3] > 200 && p[1] > 200 && p[0] < 60 && p[2] < 60
}
/// The margin an object brought over another is raised in past their overlap reaches only where
/// that object alone paints: a third member that meets the overlap's edge stays in front of it
/// there. Red A (20..80 × 20..60) and blue B (40..60 × 30..70) overlap in 40..60 × 30..60; the
/// green sliver C (38..40 × 40..50), in front of both, meets that overlap at x = 40 over A only.
#[test]
fn raising_one_overlap_keeps_an_adjacent_third_member_above_its_seam() {
let mut s = session();
let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64, color: &str| {
let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": color})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap();
id
};
let a = rect(&mut s, 20.0, 20.0, 60.0, 40.0, "#ff0000");
let b = rect(&mut s, 40.0, 30.0, 20.0, 40.0, "#0000ff");
let c = rect(&mut s, 38.0, 40.0, 2.0, 10.0, "#00ff00");
select(&mut s, &[a, b, c]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
let r = render(&s);
assert!(green(&r, 39, 45) && blue(&r, 50, 45) && red(&r, 39, 55));
let v = arrange(&mut s, json!({"at": [50, 45], "order": "front", "member": a.0}));
assert_eq!((&v["count"], &v["top"]), (&json!(1), &json!([a.0])));
assert_eq!(order_at(&s.doc().unwrap().doc, g, 50.0, 45.0), [b, a]);
let r = render(&s);
assert!(red(&r, 50, 45), "A is brought over B");
assert!(green(&r, 39, 45), "C stays in front of A within the margin");
assert!(red(&r, 39, 55));
let raised = area(&s, a).unwrap();
let inside = |x, y| vectorcraft_tools::intertwine::contains(&raised, vectorcraft_geom::Point::new(x, y));
assert!(inside(50.5, 45.5), "the overlap");
assert!(inside(39.5, 55.5), "the margin where only A paints");
assert!(!inside(39.5, 45.5), "the margin leaves out where C paints too");
}
#[test]
fn clicking_the_same_overlap_again_swaps_back() {
let mut s = session();
+51
View File
@@ -484,6 +484,57 @@ fn a_malformed_object_id_is_not_reported_as_missing() {
assert_eq!(undo(&s), before);
}
/// A required number given as something other than a number (`"40"`, `true`, `[]`, `{}`) is refused
/// as the wrong type, naming its key and showing the value as given, not as a missing number; one left
/// out or given as null is still a missing number. Neither changes the document or records an undo step.
#[test]
fn a_malformed_required_number_is_not_reported_as_missing() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let with = |base: &serde_json::Value, key: &str, v: Option<serde_json::Value>| {
let mut p = base.clone();
let o = p.as_object_mut().unwrap();
match v {
Some(v) => o.insert(key.into(), v),
None => o.remove(key),
};
p
};
let cases = [
("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}), "x"),
("edit.colors.saturate", json!({"intensity": 40}), "intensity"),
("object.envelope.setMeshPoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "index"),
("object.envelope.setMeshPoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "x"),
("object.mesh.movePoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "y"),
("guide.add", json!({"pos": 40}), "pos"),
];
for (cmd, base, key) in &cases {
for (v, shown) in [(json!("40"), "\"40\""), (json!(true), "true"), (json!([]), "[]"), (json!({}), "{}")] {
let p = with(base, key, Some(v));
match s.execute(cmd, &p) {
Err(EngineError::BadParams { cmd: c, msg }) => {
assert_eq!((c.as_str(), msg), (*cmd, format!("`{key}` must be a number, not {shown}")), "{p}");
}
other => panic!("{cmd} {p}: {other:?}"),
}
}
for p in [with(base, key, None), with(base, key, Some(json!(null)))] {
match s.execute(cmd, &p) {
Err(EngineError::BadParams { cmd: c, msg }) => assert_eq!((c.as_str(), msg), (*cmd, format!("missing number `{key}`")), "{p}"),
other => panic!("{cmd} {p}: {other:?}"),
}
}
}
assert_eq!(s.doc().unwrap().doc, doc);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
// A whole JSON number is a number for a fractional parameter.
s.execute("guide.add", &json!({"pos": 40})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
}
/// A command that takes the keys of one that isn't checked yet isn't checked either.
#[test]
fn a_reference_to_an_unchecked_command_is_unchecked() {
+23
View File
@@ -329,6 +329,29 @@ fn expanding_a_fill_gives_its_plug_in_effect_the_fill_it_sits_on() {
assert_eq!(clip.path_data().unwrap().bounds(), triangle().bounds(), "the triangle the canvas fills");
}
/// A plug-in effect on a fill, before the fill's own 3D Revolve, is given the fill it sits on
/// (`_context.item`), so the fill revolves the shape the plug-in returns for it.
#[test]
fn a_fills_revolve_gives_the_plug_in_effect_before_it_the_fill_it_sits_on() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let tri = json!({"objects": [{"path": triangle()}]}).to_string();
let on_fill = tpl::when_given(&tpl::manifest("test.engine.revolvefill", "effect", "{}"), tpl::Given::Params, r#""item":{"fill":0}"#, &tri);
install_wat(&mut s, &on_fill);
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.revolvefill", "item": fill}));
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "threeD.revolve", "item": fill}));
let n = node(&s, id);
// The same object with the triangle as its path and only the Revolve on its fill.
let mut expected = n.clone();
if let vectorcraft_doc::NodeKind::Path { path, .. } = &mut expected.kind {
*path = triangle();
}
expected.appearance.items[fill].effects_mut().retain(|e| e.id == "threeD.revolve");
let art = vectorcraft_render::effects::revolve_art(&n).unwrap();
assert_eq!(art, vectorcraft_render::effects::revolve_art(&expected).unwrap(), "the fill revolves the triangle");
}
/// The manifest of a test live effect `id` that declares `paintOutput` (at `api` 2), or that
/// doesn't (`paints` off).
fn painting(id: &str, paints: bool) -> String {
+269
View File
@@ -1079,3 +1079,272 @@ fn global_adjust_refuses_params_of_the_wrong_form() {
run(&mut s, "recolor.apply", json!({"map": map, "globalAdjust": {"saturation": null, "temperature": -100}}));
assert_ne!(fill(&s, art).to_hex(), "#ff0000", "an amount at the end of the range applies");
}
/// A placed `w` × `h` px image whose left half is `left` and right half `right` (RGBA), and its
/// bounds on the page.
fn halves_image(s: &mut Session, w: u32, h: u32, left: [u8; 4], right: [u8; 4]) -> (NodeId, vectorcraft_geom::Rect) {
let img = image::RgbaImage::from_fn(w, h, |x, _| image::Rgba(if x < w / 2 { left } else { right }));
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let r = run(s, "file.place", json!({"name": "halves.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
let id = NodeId(r["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap();
(id, b)
}
fn pick_theme(s: &mut Session, p: Value) -> Vec<String> {
keys(&run(s, "recolor.pickTheme", p)["colors"])
}
/// A click takes the palette of the object a Selection tool click takes (a whole group), the most
/// used color first, each in its own model; a click on empty canvas or on a hidden object takes
/// nothing. Locked objects are read. Picking changes nothing.
#[test]
fn theme_picker_click_takes_the_palette_of_the_whole_object() {
let mut s = session();
let a = rect(&mut s, json!("#ff0000"));
let b = rect(&mut s, json!({"c": 0, "m": 0, "y": 100, "k": 0}));
let c = rect(&mut s, json!("#ff0000"));
run(&mut s, "paint.setStroke", json!({"ids": [c.0], "color": "#0000ff"}));
// x 70 to 85 and 90 to 105.
let hidden = rect(&mut s, json!("#00ff00"));
let locked = rect(&mut s, json!("#ff00ff"));
run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]}));
run(&mut s, "object.group", json!({}));
run(&mut s, "object.hide", json!({"ids": [hidden.0]}));
run(&mut s, "object.lock", json!({"ids": [locked.0]}));
let undo = s.doc().unwrap().history.undo.len();
let doc = s.doc().unwrap().doc.clone();
// A click on `b` (x 30 to 45): the group's three rectangles, red the most used.
let r = run(&mut s, "recolor.pickTheme", json!({"picks": [{"at": [37, 17]}]}));
assert_eq!(keys(&r["colors"]), ["rgb 255 0 0", "cmyk 0 0 100 0", "rgb 0 0 255"], "{r}");
assert_eq!(r["objects"], 3);
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}], "colors": 2})).len(), 2, "at most `colors`");
assert!(pick_theme(&mut s, json!({"picks": [{"at": [300, 150]}]})).is_empty(), "empty canvas");
assert!(pick_theme(&mut s, json!({"picks": [{"at": [77, 17]}]})).is_empty(), "a hidden object");
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [97, 17]}]})), ["rgb 255 0 255"], "a locked object");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "the document stays as it was");
}
/// A marquee takes the part of an image inside it and every painted object it touches; several
/// picks (Shift) add up. A click on an image takes all its pixels.
#[test]
fn theme_picker_marquee_takes_the_area_and_picks_add_up() {
let mut s = session();
let (_, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]);
let (mid, y) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
let left = json!({"rect": [b.x0 + 1.0, b.y0 + 1.0, mid - 1.0, b.y1 - 1.0]});
assert_eq!(pick_theme(&mut s, json!({"picks": [left]})), ["rgb 255 0 0"], "the left half alone");
let right_backwards = json!({"rect": [b.x1 - 1.0, b.y1 - 1.0, mid + 1.0, b.y0 + 1.0]});
assert_eq!(pick_theme(&mut s, json!({"picks": [right_backwards]})), ["rgb 0 0 255"], "a marquee drawn backwards");
let both = pick_theme(&mut s, json!({"picks": [left, right_backwards]}));
assert_eq!(both.len(), 2, "Shift adds a second area: {both:?}");
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [mid, y]}]})).len(), 2, "a click takes the whole image");
// Two rectangles away from the image: a marquee touching both takes both.
let r1 = rect(&mut s, json!("#00ff00"));
let r2 = rect(&mut s, json!("#ffff00"));
let (b1, b2) = {
let d = &s.doc().unwrap().doc;
(d.node(r1).unwrap().visual_bounds().unwrap(), d.node(r2).unwrap().visual_bounds().unwrap())
};
let over = json!({"rect": [b1.x1 - 2.0, b1.y0 + 2.0, b2.x0 + 2.0, b1.y0 + 4.0]});
let mut got = pick_theme(&mut s, json!({"picks": [over]}));
got.sort();
assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]);
}
/// Pixels less than half opaque are left out, and so is an image whose pixels can't be read.
#[test]
fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() {
let mut s = session();
let (_, b) = halves_image(&mut s, 8, 8, [255, 0, 0, 255], [0, 0, 255, 100]);
let all = json!({"rect": [b.x0, b.y0, b.x1, b.y1]});
assert_eq!(pick_theme(&mut s, json!({"picks": [all]})), ["rgb 255 0 0"]);
let cut = super::menucmds::place_undecodable_png(&mut s);
let cb = s.doc().unwrap().doc.node(cut).unwrap().visual_bounds().unwrap();
let r = run(&mut s, "recolor.pickTheme", json!({"picks": [{"rect": [cb.x0, cb.y0, cb.x1, cb.y1]}]}));
assert!(r["colors"].as_array().unwrap().iter().all(|k| k == "rgb 255 0 0"), "the undecodable image adds nothing: {r}");
}
/// A large image is read through about 65,536 pixels: its palette still holds both halves.
#[test]
fn theme_picker_reads_a_large_image_within_its_pixel_budget() {
let mut s = session();
let (_, b) = halves_image(&mut s, 2000, 1000, [10, 200, 30, 255], [250, 240, 10, 255]);
let (mid, y) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
let mut got = pick_theme(&mut s, json!({"picks": [{"at": [mid, y]}]}));
got.sort();
assert_eq!(got, ["rgb 10 200 30", "rgb 250 240 10"]);
}
/// A symbol instance gives the colors of the art it shows, by a click or a marquee; a pattern fill
/// gives the colors of its tile and of the patterns the tile uses.
#[test]
fn theme_picker_reads_symbol_art_and_nested_patterns() {
let mut s = session();
let r = rect(&mut s, json!("#00ff00"));
run(&mut s, "select.set", json!({"ids": [r.0]}));
let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(inst).unwrap().visual_bounds().unwrap();
let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [cx, cy]}]})), ["rgb 0 255 0"], "a click on the instance");
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [cx, cy, cx + 1.0, cy + 1.0]}]})), ["rgb 0 255 0"], "a marquee");
select_all(&mut s);
run(&mut s, "edit.clear", json!({}));
// Pattern "inner" of a red square fills a square, which becomes pattern "outer".
let red = rect(&mut s, json!("#ff0000"));
let inner = run(&mut s, "object.pattern.make", json!({"ids": [red.0], "edit": false}))["name"].as_str().unwrap().to_string();
let tile = rect(&mut s, json!("#0000ff"));
run(&mut s, "paint.setFill", json!({"ids": [tile.0], "swatch": inner}));
let outer = run(&mut s, "object.pattern.make", json!({"ids": [tile.0], "edit": false}))["name"].as_str().unwrap().to_string();
let art = rect(&mut s, json!("#0000ff"));
run(&mut s, "paint.setFill", json!({"ids": [art.0], "swatch": outer}));
let b = s.doc().unwrap().doc.node(art).unwrap().visual_bounds().unwrap();
let got = pick_theme(&mut s, json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]}));
assert!(got.contains(&"rgb 255 0 0".to_string()), "the inner pattern's red: {got:?}");
}
/// A grayscale image that a fill color colorizes gives that color, not its grays.
#[test]
fn theme_picker_reads_the_color_of_a_colorized_image() {
let mut s = session();
let mut png = Vec::new();
image::GrayImage::from_pixel(8, 8, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let r = run(&mut s, "file.place", json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
let id = NodeId(r["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap();
let at = json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]});
assert_eq!(pick_theme(&mut s, at.clone()), ["rgb 90 90 90"], "uncolorized: its grays");
run(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"}));
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the fill colorizes the image");
assert_eq!(pick_theme(&mut s, at), ["rgb 255 0 0"]);
}
/// A hidden fill gives no color, and a marquee in a clip group reads only what the clipping path
/// lets through.
#[test]
fn theme_picker_leaves_out_hidden_fills_and_clipped_art() {
let mut s = session();
let shape = |s: &mut Session, x: f64, w: f64, fill: &str| {
let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": w, "height": 15}))["id"].as_u64().unwrap());
run(s, "paint.setFill", json!({"ids": [id.0], "color": fill}));
run(s, "paint.setStroke", json!({"ids": [id.0], "none": true}));
id
};
let hidden = shape(&mut s, 200.0, 15.0, "#ff00ff");
run(&mut s, "select.set", json!({"ids": [hidden.0]}));
run(&mut s, "appearance.setItem", json!({"index": 0, "visible": false}));
assert!(pick_theme(&mut s, json!({"picks": [{"rect": [205, 12, 210, 20]}]})).is_empty(), "a hidden fill");
// A marquee inside an outlined square without a fill misses it; inside a filled one it takes it.
let outline = shape(&mut s, 250.0, 40.0, "#00ffff");
run(&mut s, "paint.setFill", json!({"ids": [outline.0], "none": true}));
run(&mut s, "paint.setStroke", json!({"ids": [outline.0], "color": "#ffff00"}));
assert!(pick_theme(&mut s, json!({"picks": [{"rect": [260, 13, 270, 20]}]})).is_empty(), "inside the outline");
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [245, 13, 260, 20]}]})), ["rgb 255 255 0"], "across the outline");
run(&mut s, "paint.setFill", json!({"ids": [outline.0], "color": "#00ffff"}));
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [260, 13, 270, 20]}]})).len(), 2, "inside the fill");
// Red runs from x 10 to 110 and green from 50 to 60; the clipping path lets x 10 to 40 through.
let red = shape(&mut s, 10.0, 100.0, "#ff0000");
let green = shape(&mut s, 50.0, 10.0, "#00ff00");
let clip = shape(&mut s, 10.0, 30.0, "#0000ff");
run(&mut s, "select.set", json!({"ids": [red.0, green.0, clip.0]}));
run(&mut s, "object.clippingMask.make", json!({}));
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [30, 12, 55, 20]}]})), ["rgb 255 0 0"]);
}
/// An image in a clip group gives only the pixels inside its clipping path, by a click or a
/// marquee.
#[test]
fn theme_picker_reads_an_image_inside_its_clipping_path() {
let mut s = session();
// Red, with blue 6 × 3 px blocks in the corners, which an ellipse inscribed in the image leaves out.
let (w, h) = (64, 32);
let img = image::RgbaImage::from_fn(w, h, |x, y| {
let corner = (x < 6 || x >= w - 6) && (y < 3 || y >= h - 3);
image::Rgba(if corner { [0, 0, 255, 255] } else { [255, 0, 0, 255] })
});
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let r = run(&mut s, "file.place", json!({"name": "corners.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
let id = NodeId(r["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap();
let all = json!({"picks": [{"rect": [b.x0, b.y0, b.x1, b.y1]}]});
assert_eq!(pick_theme(&mut s, all.clone()).len(), 2, "unclipped: red and blue");
let e = NodeId(run(&mut s, "shape.ellipse", json!({"x": b.x0, "y": b.y0, "width": b.width(), "height": b.height()}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [id.0, e.0]}));
run(&mut s, "object.clippingMask.make", json!({}));
assert_eq!(pick_theme(&mut s, all), ["rgb 255 0 0"], "a marquee");
let center = json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]});
assert_eq!(pick_theme(&mut s, center), ["rgb 255 0 0"], "a click");
}
/// An object in a clip group that its clipping path hides gives no color, even inside the
/// clipping path's box.
#[test]
fn theme_picker_leaves_out_art_a_curved_clipping_path_hides() {
let mut s = session();
let shape = |s: &mut Session, x: f64, y: f64, w: f64, h: f64, fill: &str| {
let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap());
run(s, "paint.setFill", json!({"ids": [id.0], "color": fill}));
run(s, "paint.setStroke", json!({"ids": [id.0], "none": true}));
id
};
// A red square in the middle of a 100 × 100 ellipse, and a green one in its top left corner.
let red = shape(&mut s, 40.0, 40.0, 20.0, 20.0, "#ff0000");
let green = shape(&mut s, 0.0, 0.0, 8.0, 8.0, "#00ff00");
let e = NodeId(run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 100, "height": 100}))["id"].as_u64().unwrap());
let all = json!({"picks": [{"rect": [-5, -5, 105, 105]}]});
let mut both = pick_theme(&mut s, all.clone());
both.retain(|k| k == "rgb 255 0 0" || k == "rgb 0 255 0");
assert_eq!(both.len(), 2, "unclipped: both squares");
run(&mut s, "select.set", json!({"ids": [red.0, green.0, e.0]}));
run(&mut s, "object.clippingMask.make", json!({}));
assert_eq!(pick_theme(&mut s, all), ["rgb 255 0 0"], "the corner square is hidden");
}
/// In isolation mode a click and a marquee read only the isolated art.
#[test]
fn theme_picker_reads_only_the_isolated_art() {
let mut s = session();
let a = rect(&mut s, json!("#ff0000"));
let b = rect(&mut s, json!("#0000ff"));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
// Green on top of the blue square (x 30 to 45).
let green = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 10, "width": 15, "height": 15}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"ids": [green.0], "color": "#00ff00"}));
run(&mut s, "paint.setStroke", json!({"ids": [green.0], "none": true}));
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}]})), ["rgb 0 255 0"], "outside isolation: the top object");
run(&mut s, "object.isolate", json!({"id": g.0}));
let got = pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}]}));
assert_eq!(got, ["rgb 0 0 255"], "a click reaches the isolated blue square under the green one");
let mut got = pick_theme(&mut s, json!({"picks": [{"rect": [5, 5, 60, 30]}]}));
got.sort();
assert_eq!(got, ["rgb 0 0 255", "rgb 255 0 0"], "a marquee leaves out the green square");
}
/// Bad parameters are refused with an error naming them.
#[test]
fn theme_picker_refuses_bad_params() {
let mut s = session();
rect(&mut s, json!("#ff0000"));
let many: Vec<Value> = (0..257).map(|_| json!({"at": [0, 0]})).collect();
for (p, msg) in [
(json!({}), "missing `picks`"),
(json!({"picks": {"at": [0, 0]}}), "`picks` must be an array"),
(json!({"picks": []}), "`picks` must hold 1 to 256 picks (got 0)"),
(json!({"picks": many}), "`picks` must hold 1 to 256 picks (got 257)"),
(json!({"picks": [{"at": [0]}]}), "`at` must be [x, y]"),
(json!({"picks": [{"at": ["1", 2]}]}), "`at` must be [x, y]"),
(json!({"picks": [{"rect": [0, 0, 10]}]}), "`rect` must be [x0, y0, x1, y1]"),
(json!({"picks": [{"at": [0, 0], "rect": [0, 0, 1, 1]}]}), "each pick is"),
(json!({"picks": [{"point": [0, 0]}]}), "each pick is"),
(json!({"picks": [{"at": [0, 0]}], "colors": 0}), "`colors` must be between 1 and 64 (got 0)"),
(json!({"picks": [{"at": [0, 0]}], "colors": 65}), "`colors` must be between 1 and 64 (got 65)"),
(json!({"picks": [{"at": [0, 0]}], "colors": 2.5}), "`colors` must be a whole number"),
] {
let e = s.execute("recolor.pickTheme", &p).unwrap_err().to_string();
assert!(e.contains(msg), "{p}: {e}");
}
}
+10
View File
@@ -170,6 +170,16 @@ fn an_error_names_the_script_its_place_and_kind() {
assert_eq!(s.script_report().unwrap()["line"], 1);
}
/// An error raised where the run has no place for it, such as in code `eval` compiled, is named
/// with the script and its kind alone, with one colon after the script's name.
#[test]
fn an_error_without_a_place_names_the_script_and_kind() {
let mut s = two_docs();
let e = run(&mut s, "eval(\"throw new TypeError('no')\");").unwrap_err().to_string();
assert_eq!(s.script_report().unwrap()["line"], 0);
assert_eq!(e, "t.js: TypeError: no (thrown)");
}
#[test]
fn bad_parameters_are_refused_before_anything_runs() {
let mut s = two_docs();
+313 -13
View File
@@ -189,6 +189,111 @@ fn with_strokes(kind: &NodeKind) -> Option<NodeKind> {
Some(kind)
}
/// How far, in points, the sides of two boxes may lie apart and still count as the same side: the
/// glyphs' box (from type's ink) and the box of what type paints (from its outlines) measure one
/// outline two ways, and where they meet they differ by rounding only ([`painted_margin`],
/// [`same_box`]).
const PAINTED_SLACK: f64 = 1e-4;
/// The box of what the pieces of type's outlines `outlines` ([`vectorcraft_effects::outline_text`])
/// paint as an envelope with Distort Appearance bends them: each piece baked as the envelope bakes
/// it ([`vectorcraft_effects::bake_type_appearance`]: geometry effects on its fills and strokes
/// applied, so a stroke a Transform effect moves counts where it is moved to), measured by its
/// visual bounds. Those are exact for miter joins (a tip counts where the miter limit keeps it) and
/// round joins, and an upper bound for bevel joins, miters the limit cuts, width profiles and
/// square-capped dashes; a contour of zero length, which paints nothing, doesn't count. Effects on
/// the type object itself are left out: VectorCraft applies them after the envelope bends the type.
/// `None` when nothing in it has bounds.
fn painted_outlines(outlines: &Node) -> Option<Rect> {
outlines.children().into_iter().flatten().fold(None, |acc, piece| {
let baked = vectorcraft_effects::bake_type_appearance(None, piece);
vectorcraft_geom::union_opt(acc, baked.as_ref().unwrap_or(piece).visual_bounds())
})
}
/// The box of `content` an envelope of type with Distort Appearance may map from in a file besides
/// [`half_stroked_box`]: what it paints, type by its outlines ([`painted_outlines`]), groups by
/// their members grown by as far as their own strokes paint along a side, other objects by their
/// bounds with strokes. `None` when nothing in it has bounds.
fn painted_box(content: &[Arc<Node>]) -> Option<Rect> {
fn walk(n: &Arc<Node>, acc: Option<Rect>) -> Option<Rect> {
match &n.kind {
NodeKind::Text(_) => vectorcraft_geom::union_opt(acc, vectorcraft_effects::outline_text(n).as_ref().and_then(painted_outlines)),
NodeKind::Group { children, clip: false } => {
let along = n.appearance.painted_strokes().map(|s| s.side_reach(true)).fold(0.0, f64::max);
let members = children.iter().fold(None, |acc, c| walk(c, acc));
let grown = |r: Rect| if along.is_finite() && along > 0.0 { r.inflate(along, along) } else { r };
vectorcraft_geom::union_opt(acc, members.map(grown))
}
_ => vectorcraft_geom::union_opt(acc, envelope_content_boxes(std::slice::from_ref(n), Affine::IDENTITY).map(|(stroked, _)| stroked)),
}
}
content.iter().fold(None, |acc, c| walk(c, acc))
}
/// The bounds margin of `painted`, the box of what contents with geometric box `plain` paint, a side
/// within [`PAINTED_SLACK`] of the geometric box's counting as that side. `None` where it lies
/// inside the geometric box on a side, where it is that box, and for margins that don't fit.
fn painted_margin(painted: Rect, plain: Rect) -> Option<[f32; 4]> {
let side = |p: f64, g: f64| if (p - g).abs() <= PAINTED_SLACK { g } else { p };
let painted = Rect::new(side(painted.x0, plain.x0), side(painted.y0, plain.y0), side(painted.x1, plain.x1), side(painted.y1, plain.y1));
let margin = envelope_stroke_margin(painted, plain)?;
(margin.iter().all(|m| *m >= 0.0) && margin.iter().any(|m| *m > 0.0)).then_some(margin)
}
/// Do bounds margins `a` and `b` give contents with geometric box `plain` the same box, each side
/// within [`PAINTED_SLACK`]?
fn same_box(a: [f32; 4], b: [f32; 4], plain: Rect) -> bool {
let sizes = [plain.height(), plain.height(), plain.width(), plain.width()];
a.iter().zip(b).zip(sizes).all(|((a, b), size)| (f64::from(*a) - f64::from(b)).abs() * size <= PAINTED_SLACK)
}
/// What the contents of an envelope of type paint ([`painted_box`]): their geometric box and the
/// bounds margin of what they paint from it.
#[derive(Clone, Copy)]
struct Painted {
plain: Rect,
margin: [f32; 4],
}
/// [`Painted`] for envelope `kind` with Distort Appearance; `None` without it, and where
/// [`painted_margin`] gives none.
fn painted_of(kind: &NodeKind) -> Option<Painted> {
let NodeKind::Envelope { content, options, .. } = kind else { return None };
if !options.distort_appearance {
return None;
}
let (_, plain) = envelope_content_boxes(content, Affine::IDENTITY)?;
Some(Painted { plain, margin: painted_margin(painted_box(content)?, plain)? })
}
/// Envelope `kind` mapping from what its contents paint (`painted`, [`painted_of`]), for an
/// envelope with Distort Appearance where that box is neither the one it maps from already nor its
/// contents' glyphs grown by half their strokes' weight ([`with_strokes`]); `None` otherwise.
fn as_painted(kind: &NodeKind, painted: &Painted) -> Option<NodeKind> {
let NodeKind::Envelope { options, .. } = kind else { return None };
let half = match with_strokes(kind) {
Some(NodeKind::Envelope { options, .. }) => Some(options.bounds_margin),
_ => None,
};
let Painted { plain, margin } = *painted;
if !options.distort_appearance || same_box(margin, options.bounds_margin, plain) || half.is_some_and(|h| same_box(margin, h, plain)) {
return None;
}
let mut kind = kind.clone();
if let NodeKind::Envelope { options, .. } = &mut kind {
options.bounds_margin = margin;
}
Some(kind)
}
/// A way an envelope of type is tried: a kind, or a kind mapping from what its type paints
/// ([`as_painted`]), worked out when its turn comes.
enum Way {
As(NodeKind),
Painted(NodeKind),
}
/// The kind of `envelope`, a mesh or a top object in Edit Contents, with its grid moved onto
/// `drawn`, the drawn art the file saves for it, where what it draws is as large as that art (within
/// [`MOVED_SLACK`]) but lies elsewhere (further than that): moved by as far as the drawn art's box
@@ -593,7 +698,8 @@ impl WarpedType {
/// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays
/// editable in that shape, and the warp's style and bend are lost. With Distort Appearance, each
/// is also checked mapping from its type's glyphs grown by half their strokes' weight
/// ([`with_strokes`]). In Edit Contents, a mesh or top object whose grid draws the type
/// ([`with_strokes`]) and, after all of those, from what its type paints where that is another
/// box ([`as_painted`]). In Edit Contents, a mesh or top object whose grid draws the type
/// elsewhere than its drawn art is checked last moved onto that art ([`moved_onto`]). Each
/// check uses one of the import's checks and, for an envelope that shows, adds to what the page
/// check allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't
@@ -660,17 +766,16 @@ impl WarpedType {
// With Distort Appearance, a file's envelope may map its type from its glyphs grown by half
// their strokes' weight or from the glyphs alone, and for type the size the file saves for
// that box is often out of date (not the size of the type there now): each is checked.
let kinds: Vec<NodeKind> = live(&obj, before, inner)
.into_iter()
.chain(on_grid)
.flat_map(|k| {
let stroked = with_strokes(&k);
std::iter::once(k).chain(stroked)
})
.collect();
// After all of those, each is checked mapping from what its type paints, where that box is
// another: it is measured only when such a check comes and one is left.
let kinds: Vec<NodeKind> = live(&obj, before, inner).into_iter().chain(on_grid).collect();
if kinds.is_empty() {
return Err(TypeKept::Read);
}
let mut ways: Vec<Way> = kinds.iter().flat_map(|k| std::iter::once(Way::As(k.clone())).chain(with_strokes(k).map(Way::As))).collect();
ways.extend(kinds.into_iter().map(Way::Painted));
// What the type paints, measured once: the kinds share their contents.
let mut painted: Option<Option<Painted>> = None;
let (id, layer) = (doc.alloc_id(), doc.alloc_id());
let mut plain = art.clone();
(plain.visible, plain.opacity) = (true, 1.0);
@@ -678,9 +783,9 @@ impl WarpedType {
let mut alike = None;
// In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again
// moved onto that art ([`moved_onto`]), after every other way.
let (mut tries, mut moved, mut again, mut i) = (kinds.into_iter(), vec![], false, 0);
let (mut tries, mut moved, mut again, mut i) = (ways.into_iter(), vec![], false, 0);
loop {
let Some(kind) = tries.next() else {
let Some(way) = tries.next() else {
if again || moved.is_empty() {
break;
}
@@ -693,6 +798,13 @@ impl WarpedType {
if self.checks == 0 || (i > 0 && self.checks <= waiting + self.looks.len()) {
return Err(TypeKept::Budget);
}
let kind = match way {
Way::As(kind) => kind,
Way::Painted(base) => match painted.get_or_insert_with(|| painted_of(&base)).as_ref().and_then(|p| as_painted(&base, p)) {
Some(kind) => kind,
None => continue,
},
};
self.checks -= 1;
i += 1;
let mut envelope = art.clone();
@@ -705,7 +817,7 @@ impl WarpedType {
break;
}
if !again && let Some(kind) = moved_onto(&live_one, &plain) {
moved.push(kind);
moved.push(Way::As(kind));
}
}
let envelope = alike.ok_or(TypeKept::Differs)?;
@@ -867,7 +979,7 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, layer: NodeId, s
mod tests {
use super::*;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, CharStyle, LineJoin, StrokeLayer, TextObject};
use vectorcraft_doc::{AppearanceItem, CharStyle, LineCap, LineJoin, StrokeLayer, TextObject};
/// An envelope of `content` with Distort Appearance, on a flat one-patch mesh.
fn envelope_of(content: Vec<Arc<Node>>) -> NodeKind {
@@ -949,4 +1061,192 @@ mod tests {
let (_, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap();
assert_eq!(stroked_margin(content), envelope_stroke_margin(glyphs.inflate(2.0, 2.0), glyphs));
}
/// Is the font type takes by default installed? Type that must draw as itself is tested only
/// where it is: the tests below measure its glyphs.
fn default_font() -> bool {
vectorcraft_text::FontDb::global().has_family(&CharStyle::default().font_family)
}
/// The bounds margin of the candidate mapping from what `content` paints, for an envelope of it,
/// type measured by its glyphs as the import measures it; `None` where there is none.
fn painted_candidate(content: Vec<Arc<Node>>) -> Option<[f32; 4]> {
vectorcraft_text::register_envelope_ink();
let kind = envelope_of(content);
match as_painted(&kind, &painted_of(&kind)?) {
Some(NodeKind::Envelope { options, .. }) => Some(options.bounds_margin),
_ => None,
}
}
/// The box contents with geometric box `plain` map from with bounds margin `m`.
fn box_of(m: [f32; 4], plain: Rect) -> Rect {
let [top, bottom, left, right] = m.map(f64::from);
Rect::new(
plain.x0 - left * plain.width(),
plain.y0 - top * plain.height(),
plain.x1 + right * plain.width(),
plain.y1 + bottom * plain.height(),
)
}
/// Are the sides of `a` and `b` within `tol` of each other?
fn close(a: Rect, b: Rect, tol: f64) -> bool {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() <= tol)
}
/// The geometric box of `content`, type measured by its glyphs as the import measures it.
fn glyphs_of(content: &[Arc<Node>]) -> (Rect, Rect) {
vectorcraft_text::register_envelope_ink();
envelope_content_boxes(content, Affine::IDENTITY).unwrap()
}
/// What the type in `content` paints, measured apart from the import's own measure: each piece
/// of its outlines filled, and outlined by kurbo's stroker with each of its strokes' weight,
/// join and miter limit.
fn stroked_by_kurbo(content: &[Arc<Node>]) -> Rect {
use kurbo::Shape;
let mut out: Option<Rect> = None;
for n in content {
let outlines = vectorcraft_effects::outline_text(n).unwrap();
for piece in outlines.children().unwrap() {
let bp = piece.stroke_path().unwrap();
out = vectorcraft_geom::union_opt(out, Some(bp.bounding_box()));
for s in piece.appearance.painted_strokes() {
let join = match s.join {
LineJoin::Miter => kurbo::Join::Miter,
LineJoin::Round => kurbo::Join::Round,
LineJoin::Bevel => kurbo::Join::Bevel,
};
let stroke = kurbo::Stroke::new(s.width).with_join(join).with_miter_limit(s.miter_limit);
let outline = kurbo::stroke(bp.iter(), &stroke, &kurbo::StrokeOpts::default(), 1e-4);
out = vectorcraft_geom::union_opt(out, Some(outline.bounding_box()));
}
}
}
out.unwrap()
}
/// Type with Distort Appearance and a stroke with miter joins on its appearance is also tried
/// mapped from what that stroke paints: past half its weight where a miter tip pokes out at a
/// sharp corner (the feet of the A's), though not as far as its bounds with strokes, which allow
/// for a miter as long as the limit lets one be at every corner.
#[test]
fn mitred_type_is_also_tried_mapped_from_what_its_stroke_paints_miter_tips_included() {
if !default_font() {
return;
}
let mut text = type_node(1, CharStyle::default());
let mut appearance = (*text.appearance).clone();
appearance.items.push(AppearanceItem::Stroke(mitred()));
text.appearance = appearance.into();
let content = vec![Arc::new(text)];
let (with, glyphs) = glyphs_of(&content);
let (half, painted) = (glyphs.inflate(2.0, 2.0), stroked_by_kurbo(&content));
assert!(painted.x0 < half.x0 - 0.5 && painted.x1 > half.x1 + 0.5, "{painted:?} {half:?}");
assert!(painted.width() < with.width() - 0.5, "{painted:?} {with:?}");
let from = box_of(painted_candidate(content).unwrap(), glyphs);
assert!(close(from, painted, 0.01), "{from:?} {painted:?}");
}
/// Type stroked by its characters with miter joins is also tried mapped from what those strokes
/// paint, turned and stretched as well as upright.
#[test]
fn type_with_a_mitred_character_stroke_is_also_tried_mapped_from_what_it_paints() {
if !default_font() {
return;
}
let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, stroke_join: LineJoin::Miter, ..CharStyle::default() };
for xf in [
Affine::IDENTITY,
Affine::rotate(std::f64::consts::FRAC_PI_4),
Affine::scale_non_uniform(std::f64::consts::SQRT_2, std::f64::consts::FRAC_1_SQRT_2),
] {
let mut text = type_node(1, style.clone());
if let NodeKind::Text(t) = &mut text.kind {
t.xf = xf * t.xf;
}
let content = vec![Arc::new(text)];
let (_, glyphs) = glyphs_of(&content);
let painted = stroked_by_kurbo(&content);
let from = box_of(painted_candidate(content).unwrap(), glyphs);
assert!(close(from, painted, 0.01), "{xf:?}: {from:?} {painted:?}");
}
}
/// A stroke that a Transform effect moves paints where it is moved to: type filled over its
/// glyphs with a round 4 point stroke moved 10 points down is also tried mapped from its glyphs
/// grown by 2 points on the left and right and 12 at the bottom, and not at the top.
#[test]
fn a_stroke_moved_by_a_transform_effect_counts_where_it_paints() {
if !default_font() {
return;
}
let mut text = type_node(1, CharStyle::default());
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
(stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round);
stroke.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({ "moveV": 10.0 }), visible: true });
let mut appearance = (*text.appearance).clone();
appearance.items.push(AppearanceItem::Stroke(stroke));
text.appearance = appearance.into();
let content = vec![Arc::new(text)];
let (_, glyphs) = glyphs_of(&content);
let painted = Rect::new(glyphs.x0 - 2.0, glyphs.y0, glyphs.x1 + 2.0, glyphs.y1 + 12.0);
let from = box_of(painted_candidate(content).unwrap(), glyphs);
assert!(close(from, painted, 0.01), "{from:?} {painted:?}");
}
/// Type whose round-joined stroke paints half its weight past its glyphs everywhere is not tried
/// a second time mapped from what it paints: that is the box of its glyphs grown by half the
/// weight, already tried.
#[test]
fn round_joined_type_is_not_tried_twice_for_the_same_box() {
if !default_font() {
return;
}
let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, stroke_join: LineJoin::Round, ..CharStyle::default() };
let content = vec![Arc::new(type_node(1, style))];
vectorcraft_text::register_envelope_ink();
assert!(with_strokes(&envelope_of(content.clone())).is_some());
assert_eq!(painted_candidate(content), None);
}
/// A contour of zero length paints nothing, so it isn't part of what type's outlines paint: a
/// filled square with a round 2 point stroke and such a contour 5 points above it paints the
/// square grown by 1 point.
#[test]
fn a_contour_of_zero_length_paints_nothing() {
let mut bp = BezPath::new();
bp.move_to((10.0, 10.0));
bp.line_to((20.0, 10.0));
bp.line_to((20.0, 20.0));
bp.line_to((10.0, 20.0));
bp.close_path();
bp.move_to((15.0, 5.0));
bp.line_to((15.0, 5.0));
bp.close_path();
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round);
let mut appearance = Appearance::default();
appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))));
appearance.items.push(AppearanceItem::Stroke(stroke));
let piece = Node::path(NodeId(1), PathData::from_bezpath(&bp), appearance);
let outlines = Node::group(NodeId(2), vec![Arc::new(piece)]);
assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0)));
}
/// A side of what contents paint within a ten-thousandth of a point of their geometric box's is
/// that side, inside it or out: the two boxes measure the same outline two ways. Further inside,
/// there is no box; further out, it counts.
#[test]
fn a_side_within_the_slack_of_the_geometric_box_is_that_side() {
let plain = Rect::new(10.0, 20.0, 110.0, 70.0);
let painted = Rect::new(8.0, 20.0 + 1e-9, 112.0, 72.0);
assert_eq!(painted_margin(painted, plain), Some([0.0, 0.04, 0.02, 0.02]));
assert_eq!(painted_margin(Rect::new(8.0, 20.001, 112.0, 72.0), plain), None);
assert_eq!(painted_margin(plain, plain), None);
let half = [0.04_f32, 0.04, 0.02, 0.02];
assert!(same_box(half, [0.04 + 1e-7, 0.04, 0.02, 0.02], plain));
assert!(!same_box(half, [0.041, 0.04, 0.02, 0.02], plain));
}
}
+78
View File
@@ -5906,6 +5906,84 @@ fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_
assert_eq!(margin, Some(options.bounds_margin));
}
/// What the type in `content` paints, measured apart from the import: each piece of its outlines
/// filled, and outlined by kurbo's stroker with each of its strokes' weight, join and miter limit.
fn painted_by_kurbo(content: &[std::sync::Arc<Node>]) -> kurbo::Rect {
use kurbo::Shape;
let mut out: Option<kurbo::Rect> = None;
for n in content {
let outlines = vectorcraft_effects::outline_text(n).unwrap();
for piece in outlines.children().unwrap() {
let bp = piece.stroke_path().unwrap();
out = vectorcraft_geom::union_opt(out, Some(bp.bounding_box()));
for s in piece.appearance.painted_strokes() {
let join = match s.join {
vectorcraft_doc::LineJoin::Miter => kurbo::Join::Miter,
vectorcraft_doc::LineJoin::Round => kurbo::Join::Round,
vectorcraft_doc::LineJoin::Bevel => kurbo::Join::Bevel,
};
let stroke = kurbo::Stroke::new(s.width).with_join(join).with_miter_limit(s.miter_limit);
let outline = kurbo::stroke(bp.iter(), &stroke, &kurbo::StrokeOpts::default(), 1e-4);
out = vectorcraft_geom::union_opt(out, Some(outline.bounding_box()));
}
}
}
out.unwrap()
}
/// A warp of type stroked with miter joins, Distort Appearance on, whose drawn art maps the type from
/// what it paints, the miter tips at the sharp corners of its X past half the stroke's weight
/// included, as users' files map some such type, opens live as a mesh envelope on its saved grid
/// mapping from that box, where its glyphs grown by half the weight don't draw as that art (#6824).
#[test]
fn a_warp_of_mitred_type_maps_from_what_its_stroke_paints_where_its_drawn_art_does() {
use vectorcraft_doc::live::{envelope_content_boxes, envelope_stroke_margin};
let Some(family) = installed_family() else { return };
// "FLUX" stroked 4 points wide in black, with miter joins at a limit of 10.
let stroked = "/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> /54 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 0.0 0.0 1.0 ] >> >> /57 true /62 0 /63 4.0 /64 10.0";
let doc = type_envelope_text(&family, None).replace("/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >>", stroked);
let mut text = made_envelope_type(&doc);
text.visible = true;
assert!(
matches!(&text.kind, NodeKind::Text(t) if t.runs[0].style.stroke_join == vectorcraft_doc::LineJoin::Miter && t.runs[0].style.stroke_miter_limit == 10.0),
"{text:?}"
);
let content = vec![std::sync::Arc::new(text)];
let (half, glyphs) = envelope_content_boxes(&content, kurbo::Affine::IDENTITY).unwrap();
let painted = painted_by_kurbo(&content);
assert!(painted.x0 < half.x0 - 0.5 || painted.x1 > half.x1 + 0.5, "{painted:?} {half:?}");
let mut options = vectorcraft_doc::live::EnvelopeOptions::NEW;
options.bounds_margin = envelope_stroke_margin(painted, glyphs).unwrap();
let shaped = Node::new(
vectorcraft_doc::NodeId(1_000_000),
NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() },
);
let (drawn, page) = drawn_stroked_envelope(&shaped);
let art =
native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc);
let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap();
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
let (envelopes, loose) = envelopes_and_type(&r.document);
assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings);
assert!(loose.is_empty(), "{loose:?}");
// It maps from what the type paints, within a hundredth of a point on each side.
let mut margin = None;
r.document.walk(|n| {
if let NodeKind::Envelope { options, .. } = &n.kind {
margin = Some(options.bounds_margin);
}
});
let [top, bottom, left, right] = margin.unwrap().map(f64::from);
let from = kurbo::Rect::new(
glyphs.x0 - left * glyphs.width(),
glyphs.y0 - top * glyphs.height(),
glyphs.x1 + right * glyphs.width(),
glyphs.y1 + bottom * glyphs.height(),
);
let off = [from.x0 - painted.x0, from.y0 - painted.y0, from.x1 - painted.x1, from.y1 - painted.y1];
assert!(off.iter().all(|d| d.abs() < 0.01), "{from:?} {painted:?}");
}
/// The drawn art of `envelope` (on the page axes), an envelope of type stroked by its characters,
/// as the drawn art of `.ai` files strokes type in an envelope: the bent glyph outlines the envelope
/// draws of its type unstroked, each filled in its type's color, then each stroked with the type's
+21 -3
View File
@@ -6,20 +6,38 @@
use std::sync::Arc;
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Point, Rect, Shape};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
/// The largest distance between the edges of `a` and `b`.
fn off(a: Rect, b: Rect) -> f64 {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
}
/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or
/// system fonts.
fn type_in_test_face() -> TextObject {
assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads");
TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() })
}
/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph.
fn outline_box(t: &TextObject) -> Rect {
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let outlines: Vec<Rect> = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect();
assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline");
outlines.into_iter().reduce(|a, b| a.union(b)).unwrap()
}
#[test]
fn reading_an_ai_file_measures_type_in_envelopes_by_its_glyphs() {
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
let t = type_in_test_face();
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
let laid = n.geometric_bounds().unwrap();
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
let ink = outline_box(&t);
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap();
assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {ink:?}");
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
+8 -2
View File
@@ -1242,13 +1242,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorPanel",
"Color Panel Options",
"",
"{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool, recentColors?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), Show Options (true) or Hide Options (false), and check (true) or uncheck (false) Show Recent Colors, which shows or hides the panel's Recent Colors row (applied colors still join the list while it is hidden; the Swatches panel keeps its row); all three are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options, ui.color_show_recent_colors) → {mode (null: none picked yet), options, recentColors, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}",
"{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool, recentColors?: bool, rgbPercent?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), Show Options (true) or Hide Options (false), check (true) or uncheck (false) Show Recent Colors, which shows or hides the panel's Recent Colors row (applied colors still join the list while it is hidden; the Swatches panel keeps its row), and show the RGB mode's R, G and B in percent (true) or from 0 to 255 (false), as a double-click right of an RGB field switches them (the color does not change; Web Safe RGB and the hex field stay in 0 to 255); all four are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options, ui.color_show_recent_colors, ui.color_rgb_percent) → {mode (null: none picked yet), options, recentColors, rgbPercent, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}",
),
(
"ui.colorRgbPercent",
"Toggle RGB Percent",
"",
"{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent",
),
(
"ui.savePdfDialog",
"Save PDF Dialog",
"",
"{path?, preset?, range?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; OK writes path, else asks)",
"{path?, preset?, range?, useArtboards?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; OK writes path, else asks); useArtboards: false: one page of the visible art's bounds, with no Artboards section",
),
(
"file.exportAs",
+10 -2
View File
@@ -579,6 +579,11 @@ fn unit(v: f32) -> f32 {
v.clamp(0.0, 1.0)
}
/// Process plate `v` in 0..1: NaN is 0, infinities go to the nearest end.
fn plate(v: f32) -> f32 {
if v.is_nan() { 0.0 } else { unit(v) }
}
/// `c` with its components in range.
pub(crate) fn clamp_color(c: Color) -> Color {
match c {
@@ -589,8 +594,8 @@ pub(crate) fn clamp_color(c: Color) -> Color {
}
}
/// A paint from plug-in output (`null`: none), with colours, opacities and offsets clamped and
/// gradient and pattern placements checked.
/// A paint from plug-in output (`null`: none), with colors, process plates, opacities and
/// offsets clamped and gradient and pattern placements checked.
fn decode_paint(v: &Value, at: &str) -> Result<Paint> {
if v.is_null() {
return Ok(Paint::None);
@@ -613,6 +618,9 @@ fn decode_paint(v: &Value, at: &str) -> Result<Paint> {
s.midpoint = s.midpoint.clamp(0.13, 0.87);
s.tint = unit(s.tint);
s.color = clamp_color(s.color);
if let Some(plates) = &mut s.plates {
*plates = plates.map(plate);
}
}
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
g.angle = g.angle.rem_euclid(360.0);
+27
View File
@@ -109,6 +109,33 @@ fn only_a_radial_keeps_a_focal_point_through_a_plug_in() {
}
}
/// A gradient stop's process plates handed back out of range are clamped to 0..1, each in its
/// place, in a fill and in a stroke (a JSON number too large for `f32` is infinite); plates in range
/// and a stop without plates are kept.
#[test]
fn gradient_stop_plates_are_clamped_through_a_plug_in() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let (mut d, ids, _) = doc();
let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(0.5, Color::gray(0.5)), GradientStop::new(1.0, Color::BLACK)];
let mut p = serde_json::to_value(Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))))).unwrap();
p["gradient"]["stops"][0]["plates"] = json!([-0.5, 1.5, -1e300, 1e300]);
p["gradient"]["stops"][1]["plates"] = json!([0.25, 2.0, 0.75, -3.0]);
let out = json!({"objects": [{"id": ids[0].0, "fills": [p.clone()], "strokes": [{"paint": p}]}]});
apply_output(&mut d, &ids, decode_json(out).unwrap(), None, &keep).unwrap();
let ap = &d.node(ids[0]).unwrap().appearance;
for (what, paint) in [("fill", ap.fill_paint()), ("stroke", ap.stroke_paint())] {
let Paint::Gradient(g) = paint else { panic!("a gradient {what}") };
let plates: Vec<_> = g.gradient.stops.iter().map(|s| s.plates).collect();
assert_eq!(plates, [Some([0.0, 1.0, 0.0, 1.0]), Some([0.25, 1.0, 0.75, 0.0]), None], "{what}");
}
}
/// A plate that is not a number is 0; infinities go to the nearest end of 0..1.
#[test]
fn plates_that_are_not_finite_are_in_range() {
assert_eq!([f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.5].map(plate), [0.0, 1.0, 0.0, 0.5]);
}
/// A path handed back as it was stays the live shape it was (a rectangle keeps its corner
/// widgets); a path that changed is a plain path.
#[test]
+21 -3
View File
@@ -7,20 +7,38 @@
use std::sync::Arc;
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Point, Rect, Shape};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
/// The largest distance between the edges of `a` and `b`.
fn off(a: Rect, b: Rect) -> f64 {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
}
/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or
/// system fonts.
fn type_in_test_face() -> TextObject {
assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads");
TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() })
}
/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph.
fn outline_box(t: &TextObject) -> Rect {
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let outlines: Vec<Rect> = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect();
assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline");
outlines.into_iter().reduce(|a, b| a.union(b)).unwrap()
}
#[test]
fn a_new_renderer_measures_type_in_envelopes_by_its_glyphs() {
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
let t = type_in_test_face();
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
let laid = n.geometric_bounds().unwrap();
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
let ink = outline_box(&t);
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap();
assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {ink:?}");
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
+15 -4
View File
@@ -272,6 +272,12 @@ impl Writer<'_> {
self.warn("type on a path with space before a character after a line break is outlined to keep its look");
return self.text_outlines(n, t);
}
// A `<textPath>` places its characters one after the other: Insert Aki keeps its look as
// outlines.
if t.runs.iter().any(|r| r.style.aki_left != 0.0 || r.style.aki_right != 0.0) {
self.warn("type on a path with Insert Aki is outlined to keep its look");
return self.text_outlines(n, t);
}
// A `<textPath>` holds the characters of the text, not the bullets or numbers drawn
// before them.
if !lay.markers.is_empty() {
@@ -703,11 +709,14 @@ const PLACE_TOLERANCE: f64 = 1e-6;
/// caps are upper case. Unless `fewer`, a line that is justified or composed with Mojikumi also
/// starts a new segment at each character the layout draws elsewhere than a reader continuing
/// the segment would ([`reader_advances`]): a Justify All line's letter gaps, the gaps between
/// the characters of a justified Japanese line, and the spacing Mojikumi changes.
/// the characters of a justified Japanese line, and the spacing Mojikumi changes. Text with Insert
/// Aki does so on every line, with `fewer` too.
fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) -> Vec<Line> {
let plain = t.plain_text();
let mut lines = Vec::with_capacity(lay.lines.len());
let (mut kerned, mut unkerned) = (None, None);
// Insert Aki moves characters from where a reader draws them, with `fewer` too.
let aki = t.runs.iter().any(|r| r.style.aki_left != 0.0 || r.style.aki_right != 0.0);
for line in &lay.lines {
let para = plain.as_bytes().get(..line.start).map_or(0, |b| b.iter().filter(|&&c| c == b'\n').count());
let style = t.para_at(para);
@@ -716,7 +725,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) -
// Justification…'s Desired word and letter spacing and glyph scaling move characters from
// where a reader draws them, on every line (Block's word gap among them).
let spaced = !fewer && !t.layout_justification(style).desired_is_default();
let reader = if split_words || spaced || (!fewer && !style.mojikumi.is_none()) {
let reader = if aki || split_words || spaced || (!fewer && !style.mojikumi.is_none()) {
Some(&*kerned.get_or_insert_with(|| reader_advances(t, lay, true)))
} else {
None
@@ -871,9 +880,11 @@ fn reader_advances(t: &TextObject, lay: &vectorcraft_text::TextLayout, kerning:
if !kerning {
r.style.kerning.get_or_insert(0.0);
}
// A reader puts no space before a line's first character (`kerningBefore`): the segment
// starts that much further along instead.
// A reader puts no space before a line's first character (`kerningBefore`) and no Insert
// Aki: the segment starts that much further along instead.
r.style.kerning_before = 0.0;
r.style.aki_left = 0.0;
r.style.aki_right = 0.0;
}
let relaid;
let glyphs = if set == *t {
+33
View File
@@ -163,6 +163,39 @@ fn the_space_before_the_first_character_on_a_path_is_its_dx() {
assert!(!out.svg.contains("<textPath") && out.warnings.iter().any(|w| w.contains("line break")), "{:?}", out.warnings);
}
/// Insert Aki: each character the layout moves by its Aki starts a `<tspan>` where the character is
/// drawn, so a reader draws the text where the canvas does, on left-aligned, centered and
/// right-aligned lines and with fewer `<tspan>`s asked for too. On a path the type is outlined.
#[test]
fn insert_aki_places_each_moved_character() {
// 250/1000 em of 12 pt before the O (3 pt) and 500/1000 after it (6 pt), then a run with Aki
// after every character, and a second line.
let spaced = CharStyle { aki_left: 250.0, aki_right: 500.0, ..style(12.0) };
let runs = vec![run("H", style(12.0)), run("O", spaced), run("H ", style(12.0)), run("OHO\nHO", CharStyle { aki_right: 500.0, ..style(12.0) })];
// A centered or right-aligned line whose characters the Aki moves is placed segment by
// segment, not anchored.
for justify in [Justify::Center, Justify::Right] {
assert_drawn_in_place(&area_doc(runs.clone(), 200.0, justify));
}
let d = area_doc(runs, 200.0, Justify::Left);
assert_drawn_in_place(&d);
let plain = tspans(&export(&area_doc(vec![run("HOH OHO\nHO", style(12.0))], 200.0, Justify::Left), &ExportOptions::default())).len();
let fewer = tspans(&export(&d, &ExportOptions { fewer_tspans: true, ..Default::default() })).len();
assert!(fewer > plain, "each moved character is placed with fewer tspans too: {plain} {fewer}");
let mut t = TextObject::point(Point::ZERO, "", style(12.0));
t.runs = vec![run("HO", CharStyle { aki_left: 250.0, ..style(12.0) })];
let mut line = BezPath::new();
line.move_to((20.0, 100.0));
line.line_to((280.0, 100.0));
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
let mut d = Document::new(300.0, 200.0);
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
let l = d.layers[0].id;
d.insert(Some(l), 0, n).unwrap();
let out = vectorcraft_svg::export_full(&d, &ExportOptions::default(), None);
assert!(!out.svg.contains("<textPath") && out.warnings.iter().any(|w| w.contains("Insert Aki")), "{:?}", out.warnings);
}
/// Proportional Metrics (#966) is written as the `palt` feature, beside the character's own.
#[test]
fn proportional_metrics_write_palt() {
+1
View File
@@ -15,6 +15,7 @@ pub(super) struct SysFallback {
/// The most characters searched for in the font files themselves between two scans of the font
/// folders. Real text has a few uncovered characters; a document of thousands of distinct
/// private-use code points would reread the whole catalog for each.
#[cfg(not(target_arch = "wasm32"))]
pub(super) const MAX_FILE_SEARCHES: u32 = 1024;
/// Fonts made for Thai, tried first (when installed) for Thai the font in use lacks: Windows
+2
View File
@@ -54,6 +54,8 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool {
tracking,
kerning,
kerning_before: _,
aki_left: _,
aki_right: _,
optical_kerning,
baseline_shift,
h_scale,
+8 -6
View File
@@ -148,25 +148,27 @@ pub(crate) fn apply_desired(sg: &mut [SGlyph], j: &JustificationOptions, scale_g
}
continue;
}
// Insert Aki keeps its width: only the rest of the advance is spaced or scaled.
let aki = if g.aki.is_finite() { g.aki } else { 0.0 };
if is_word_space(g) {
// The font's word space (with its tracking), set at Desired.
let base = g.adv;
g.adv = base * w_des;
let base = g.adv - aki;
g.adv = base * w_des + aki;
f.word = (base * (w_max - w_des).max(0.0), base * (w_des - w_min).max(0.0));
continue;
}
if g.is_space() || g.inline.is_some() || g.ch == '\u{2028}' {
continue;
}
let base = g.adv;
let base = g.adv - aki;
if g_des != 1.0 {
g.adv *= g_des;
g.adv = base * g_des + aki;
g.tracking *= g_des;
g.sx *= g_des;
g.dx *= g_des;
g.kern_shift *= g_des;
g.kern_shift = (g.kern_shift - g.aki_shift) * g_des + g.aki_shift;
}
f.width = g.adv;
f.width = g.adv - aki;
f.scale = g_des;
f.glyph = (base * (g_max - g_des).max(0.0), base * (g_des - g_min).max(0.0));
if gap {
+23 -2
View File
@@ -241,7 +241,7 @@ impl Ctx<'_> {
/// Layout on or Fractional Widths off, whole-point advances.
fn finish_shaping<'s>(&self, v: &mut [SGlyph], style: impl Fn(&SGlyph) -> &'s CharStyle) {
if self.vertical {
tate_chu_yoko(v, |g| {
tate_chu_yoko(v, self.system_layout || !self.fractional_widths, |g| {
let st = style(g);
TcyStyle { size: st.size, marked: st.tate_chu_yoko, up: st.tcy_up_down, right: st.tcy_left_right }
});
@@ -318,6 +318,8 @@ impl Ctx<'_> {
tab.dx = 0.0;
tab.dy = 0.0;
tab.kern_shift = 0.0;
tab.aki_shift = 0.0;
tab.aki = 0.0;
tab.tcy = None;
tab.vpal = None;
let left = para.laid_out_left_indent();
@@ -335,6 +337,19 @@ impl Ctx<'_> {
n
}
/// Does glyph `g`'s own width start where its placement sets it ([`PositionedGlyph::width_start`])?
/// Not for an inline graphic, nor in vertical type for an upright or tate-chu-yoko glyph, which
/// start their cell at the start of their advance.
fn places_own_width(&self, g: &SGlyph) -> bool {
g.inline.is_none() && !(self.vertical && (g.tcy.is_some() || (takes_cell(g) && stands_upright(g))))
}
/// How far glyph `g`'s own width moves when the glyph is drawn `shift` further along its
/// advance: `shift` when its placement sets where that width starts, otherwise 0.
fn own_width_shift(&self, g: &SGlyph, shift: f64) -> f64 {
if self.places_own_width(g) { shift } else { 0.0 }
}
fn emit(&mut self, g: &SGlyph, pre: Affine, origin: Point, angle: f64, advance: f64, line: usize) {
// Only the glyph right after an upright glyph can continue its cluster.
let cluster = self.upright_cluster.take();
@@ -538,7 +553,7 @@ impl Ctx<'_> {
let [a, b, ..] = pre.as_coeffs();
a.hypot(b)
};
let width_start = if g.inline.is_none() && !upright && !(self.vertical && g.tcy.is_some()) {
let width_start = if self.places_own_width(g) {
Some((g.kern_shift + g.dx - g.lead) * along).filter(|s| s.is_finite()).unwrap_or(0.0)
} else if upright {
Some(g.kern_shift * along).filter(|s| s.is_finite()).unwrap_or(0.0)
@@ -617,6 +632,8 @@ impl Ctx<'_> {
k.dx = 0.0;
k.dy = 0.0;
k.kern_shift = 0.0;
k.aki_shift = 0.0;
k.aki = 0.0;
k.len = 0;
k.lead = 0.0;
k.ch = kashida::TATWEEL;
@@ -674,6 +691,8 @@ mod emit_kashida_mark_last {
dx: 0.0,
dy: 0.0,
kern_shift: 0.0,
aki_shift: 0.0,
aki: 0.0,
sx: face.upem.recip() * 48.0,
sy: face.upem.recip() * 48.0,
bshift: 0.0,
@@ -737,6 +756,8 @@ mod emit_kashida_mark_last {
dx: 0.0,
dy: 0.0,
kern_shift: 0.0,
aki_shift: 0.0,
aki: 0.0,
sx: face.upem.recip() * 48.0,
sy: face.upem.recip() * 48.0,
bshift: 0.0,
+7 -1
View File
@@ -1030,7 +1030,10 @@ fn emit_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, paragraph: &ParagraphData
.map(|item| item.1);
advance += kashida.unwrap_or(0.0);
let y = line.position.baseline - align_shift(glyph, cx.style_at(glyph.byte).char_align, line_em, cx.vertical);
let transform = if scale != 1.0 { Affine::translate((x, y)) * Affine::scale_non_uniform(scale, 1.0) } else { Affine::translate((x, y)) };
// A glyph scaled to fill the line keeps its Insert Aki before it at its width.
let aki = if scale != 1.0 && glyph.aki_shift.is_finite() { glyph.aki_shift * (1.0 - scale) } else { 0.0 };
let transform =
if scale != 1.0 { Affine::translate((x + aki, y)) * Affine::scale_non_uniform(scale, 1.0) } else { Affine::translate((x, y)) };
if glyph_index < paragraph.marker {
let at = cx.out.glyphs.len();
marker_glyphs = Some(marker_glyphs.map_or(at..at + 1, |range: Range<usize>| range.start.min(at)..range.end.max(at + 1)));
@@ -1039,8 +1042,11 @@ fn emit_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, paragraph: &ParagraphData
}
}
cx.emit(glyph, transform, Point::new(x, y), 0.0, advance, line_index);
// Its own width starts where the glyph is drawn, with the Aki kept at its width.
let own_shift = cx.own_width_shift(glyph, aki);
if let Some(out) = cx.out.glyphs.last_mut() {
out.scale = paragraph.flex.get(glyph_index).map_or(1.0, |flex| flex.scale) * scale;
out.width_start += own_shift;
}
if !leader.is_empty() {
// The leader belongs to the tab's glyph: the gap stays one character for the
+44 -16
View File
@@ -7,18 +7,23 @@ use super::{Affine, Ctx, Punct, Range, Rect, SGlyph, Tcy, TextLayout, TextObject
/// tate-chu-yoko continuation, a zero-width mark) stays zero. Right to left, a cluster with manual
/// kerning moves by the difference the kerning makes to its rounded advance, so the rounding
/// changes the space before the next character in reading order and not the space after the one
/// before it.
/// before it. Each side of the Insert Aki is rounded to whole points on its own and added to the
/// rounded advance, so justification keeps it at that width.
pub(super) fn whole_character_widths(glyphs: &mut [SGlyph]) {
let whole = |adv: f64| if adv.is_finite() && adv > 0.0 { adv.round().max(1.0) } else { adv };
let points = |aki: f64| if aki.is_finite() { aki.round() } else { 0.0 };
for cluster in glyphs.chunk_by_mut(|a, b| continues_cluster(Some(a), Some(b))) {
// The cluster's last glyph carries the manual kerning in its advance.
let (adv, shift) = cluster.last().map_or((0.0, 0.0), |g| (g.adv, g.kern_shift));
// The cluster's last glyph carries the manual kerning and the Insert Aki in its advance.
let (adv, shift) = cluster.last().map_or((0.0, 0.0), |g| (g.adv - g.aki, g.kern_shift - g.aki_shift));
let rounded_shift = Some(whole(adv) - whole(adv - shift)).filter(|s| s.is_finite()).unwrap_or(shift);
for g in cluster {
g.adv = whole(g.adv);
if shift != 0.0 {
g.kern_shift = rounded_shift;
}
// The space before the character and the space after it are each rounded.
let aki_shift = points(g.aki_shift);
let aki = if g.aki == 0.0 { 0.0 } else { aki_shift + points(g.aki - g.aki_shift) };
g.adv = whole(g.adv - g.aki) + aki;
g.kern_shift = if shift != 0.0 { rounded_shift } else { g.kern_shift - g.aki_shift } + aki_shift;
g.aki = aki;
g.aki_shift = aki_shift;
}
}
}
@@ -33,7 +38,10 @@ pub(super) fn whole_character_widths(glyphs: &mut [SGlyph]) {
/// before the automatic digit rule. A marked block moves by the Tate-chu-yoko Settings Up/Down
/// and Left/Right of its first character; an automatic block does not move.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
pub(super) fn tate_chu_yoko(g: &mut [SGlyph], style: impl Fn(&SGlyph) -> TcyStyle) {
///
/// With `whole` (System Layout on or Fractional Widths off), each side of a block's Insert Aki is
/// set in whole points ([`whole_character_widths`]).
pub(super) fn tate_chu_yoko(g: &mut [SGlyph], whole: bool, style: impl Fn(&SGlyph) -> TcyStyle) {
let manual: Vec<bool> = g.iter().map(|gl| gl.ch != '\u{2028}' && style(gl).marked).collect();
let digits: Vec<bool> = g.iter().map(|gl| gl.inline.is_none() && gl.ch.is_ascii_digit()).collect();
let mut i = 0;
@@ -44,7 +52,7 @@ pub(super) fn tate_chu_yoko(g: &mut [SGlyph], style: impl Fn(&SGlyph) -> TcyStyl
end += 1;
}
let first = style(&g[i]);
place_tcy_block(&mut g[i..end], first.size, (first.up, first.right));
place_tcy_block(&mut g[i..end], first.size, (first.up, first.right), whole);
i = end;
continue;
}
@@ -58,7 +66,7 @@ pub(super) fn tate_chu_yoko(g: &mut [SGlyph], style: impl Fn(&SGlyph) -> TcyStyl
}
if (2..=3).contains(&(end - i)) {
let em = style(&g[i]).size;
place_tcy_block(&mut g[i..end], em, (0.0, 0.0));
place_tcy_block(&mut g[i..end], em, (0.0, 0.0), whole);
}
i = end;
}
@@ -74,15 +82,35 @@ pub(super) struct TcyStyle {
}
/// Lay `g` across one em of the column, moved by `(up, right)` points. The first glyph takes the
/// em; the rest share its cell.
fn place_tcy_block(g: &mut [SGlyph], em: f64, (up, right): (f64, f64)) {
let width: f64 = g.iter().map(|gl| gl.adv).sum();
/// em; the rest share its cell. The Insert Aki of the block's first character is space above and
/// below the block, and the Insert Aki of its other characters is left out: the block is set
/// down the column that much further, and its last glyph carries the space in its advance. With
/// `whole`, the space above and the space below are each rounded to whole points.
fn place_tcy_block(g: &mut [SGlyph], em: f64, (up, right): (f64, f64), whole: bool) {
let Some(first) = g.first() else { return };
let (byte, before) = (first.byte, first.aki_shift);
let aki: f64 = g.iter().filter(|gl| gl.byte == byte).map(|gl| gl.aki).sum();
let points = |v: f64| {
if !whole {
v
} else if v.is_finite() {
v.round()
} else {
0.0
}
};
let (before, aki) = (points(before), points(before) + points(aki - before));
let width: f64 = g.iter().map(|gl| gl.adv - gl.aki).sum();
let squeeze = if width > em && width > 0.0 { em / width } else { 1.0 };
let last = g.len() - 1;
let mut ink = 0.0;
for (k, gl) in g.iter_mut().enumerate() {
let adv = gl.adv;
gl.tcy = Some(Tcy { pen: if k == 0 { 0.0 } else { em }, ink, width, squeeze, up, right });
gl.adv = if k == 0 { em } else { 0.0 };
let adv = gl.adv - gl.aki;
gl.tcy = Some(Tcy { pen: if k == 0 { 0.0 } else { em }, ink, width, squeeze, up: up - before, right });
gl.kern_shift -= gl.aki_shift;
gl.aki_shift = 0.0;
gl.aki = if k == last { aki } else { 0.0 };
gl.adv = if k == 0 { em } else { 0.0 } + gl.aki;
ink += adv;
}
}
+2
View File
@@ -20,6 +20,8 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec<SGlyph> {
dx: 0.0,
dy: 0.0,
kern_shift: 0.0,
aki_shift: 0.0,
aki: 0.0,
sx: 1.0,
sy: 1.0,
bshift: 0.0,
+1 -1
View File
@@ -54,7 +54,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader};
pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout};
use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};
pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled};
pub use shape::{inseparable, line_start_space, spacing_scale};
pub use shape::{aki_space, inseparable, line_start_space, spacing_scale};
pub use vectorcraft_doc::TextObject;
pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign};
+66 -20
View File
@@ -13,7 +13,7 @@ use kurbo::Shape;
use skrifa::MetadataProvider;
use skrifa::charmap::Charmap;
use skrifa::instance::Size;
use vectorcraft_doc::text::INLINE_CHAR;
use vectorcraft_doc::text::{INLINE_CHAR, MAX_AKI};
use vectorcraft_doc::{CharStyle, Digits, InlineArt};
use crate::features::{OtFeatures, ligatures_suppressed_by};
@@ -41,8 +41,14 @@ pub(crate) struct SGlyph {
/// outside its Character Rotation; with whole-point advances, the difference the kerning makes
/// to the cluster's rounded advance. Left to right and in vertical type: the space before a
/// line's first character ([`CharStyle::kerning_before`]), which moves it along the line the
/// same way. 0 otherwise.
/// same way. Insert Aki ([`aki`]) adds the space before the cluster in reading order: left to
/// right and in vertical type the Aki Left, right to left the Aki Right. 0 otherwise.
pub kern_shift: f64,
/// The Insert Aki `kern_shift` holds, in points, on every glyph of its cluster.
pub aki_shift: f64,
/// The Insert Aki Left and Right `adv` holds, in points: on the last glyph of its cluster, 0
/// on the others. Justification does not stretch or narrow it.
pub aki: f64,
/// Outline scale (font units -> points).
pub sx: f64,
pub sy: f64,
@@ -193,6 +199,8 @@ pub(crate) fn hyphen_glyph(g: &SGlyph) -> SGlyph {
h.dx = 0.0;
h.dy = 0.0;
h.kern_shift = 0.0;
h.aki_shift = 0.0;
h.aki = 0.0;
h.byte = g.byte + g.len;
h.len = 0;
h.ch = '-';
@@ -606,6 +614,22 @@ pub fn line_start_space(text: &str, byte: usize, st: &CharStyle, vertical: bool)
space_before(text, byte, st, glyph_size(st, small) * spacing_scale(st, vertical))
}
/// Insert Aki Left and Right ([`CharStyle::aki_left`], [`CharStyle::aki_right`]) of characters in
/// style `st`, in points of `spacing_em`: the space before and after each cluster in reading order,
/// each from 0 to [`MAX_AKI`] thousandths of it. Its cluster takes both in its advance.
fn aki(st: &CharStyle, spacing_em: f64) -> (f64, f64) {
let side = |v: f64| Some(v.clamp(0.0, MAX_AKI) / 1000.0 * spacing_em).filter(|s| s.is_finite()).unwrap_or(0.0);
(side(st.aki_left), side(st.aki_right))
}
/// The Insert Aki before and after the character at `byte` of `text` in style `st`, in points, as
/// the layout sets it ([`CharStyle::aki_left`]): its thousandths of the em the character is set in.
/// For writers that place characters themselves.
pub fn aki_space(text: &str, byte: usize, st: &CharStyle, vertical: bool) -> (f64, f64) {
let small = st.small_caps.is_some() && !st.all_caps && text.get(byte..).and_then(|s| s.chars().next()).is_some_and(char::is_lowercase);
aki(st, glyph_size(st, small) * spacing_scale(st, vertical))
}
/// The size characters in style `st` are shaped at: Superscript, Subscript and synthesized Small
/// Caps (`small`: a lowercase letter in them) shrink the glyphs; line metrics keep the full size.
fn glyph_size(st: &CharStyle, small: bool) -> f64 {
@@ -783,7 +807,8 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range<
let mut cache = HashMap::new();
let mut corrections: HashMap<[u64; 15], Option<f64>> = HashMap::new();
let mut references: HashMap<u32, Option<f64>> = HashMap::new();
let shaped_advances: Vec<f64> = glyphs.iter().map(|g| g.adv).collect();
// The Insert Aki a cluster's last glyph holds does not make a mark its base.
let shaped_advances: Vec<f64> = glyphs.iter().map(|g| g.adv - g.aki).collect();
for i in 0..glyphs.len().saturating_sub(1) {
let Some((a, b)) = glyphs.get(i).zip(glyphs.get(i + 1)) else { continue };
if a.level != b.level {
@@ -841,8 +866,10 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range<
continue;
}
// Neither glyph is rotated, so a right-to-left manual kerning shift adds to the offset.
let left_x = left.dx + left.kern_shift;
let right_x = right.dx + right.kern_shift;
// Insert Aki is measured as no space: the pair is spaced as it would be without it, and
// the Aki stays on top of that.
let left_x = left.dx + left.kern_shift - left.aki_shift;
let right_x = right.dx + right.kern_shift - right.aki_shift;
let left_y = left.dy - left.bshift;
let right_y = right.dy - right.bshift;
let Some(left_style) = runs.get(left.run).map(|(_, s)| *s) else { continue };
@@ -851,7 +878,7 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range<
let tracking = left_style.tracking / 1000.0 * em * spacing_scale(left_style, false);
// A manual kerning value on the left glyph is part of its advance and, right to left, of
// its offset too (it spaces the left glyph from its left neighbor): it is not taken off.
let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv).sum::<f64>() - tracking;
let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv - g.aki).sum::<f64>() - tracking;
let key = [
u64::from(left.face.id()),
u64::from(left.gid),
@@ -911,8 +938,9 @@ fn source_run_at(runs: &[(Range<usize>, &CharStyle)], span: &Range<usize>, byte:
/// Can one glyph draw characters in styles `a` and `b`? OpenType features already apply to their
/// own character ranges during shaping, so feature-only differences do not split a cluster.
/// Horizontal type does not read Standard Vertical Roman Alignment or the tate-chu-yoko offsets.
/// The space before a line's first character ([`space_before`]) comes from the cluster's first
/// character, so it does not split a ligature either.
/// The space before a line's first character ([`space_before`]) and Insert Aki ([`aki`]) come
/// from the cluster's first character, so they do not split a ligature or a letter from its marks
/// either.
fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool {
// Exhaustive, like `shapes_alike`: compare borrowed fields without copying feature lists.
let CharStyle {
@@ -925,6 +953,8 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool {
tracking,
kerning,
kerning_before,
aki_left,
aki_right,
optical_kerning,
baseline_shift,
h_scale,
@@ -965,6 +995,8 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool {
let offsets = (standard_vertical_roman, tcy_up_down, tcy_left_right);
let other_offsets = if vertical { (&b.standard_vertical_roman, &b.tcy_up_down, &b.tcy_left_right) } else { offsets };
kerning_before == &a.kerning_before
&& aki_left == &a.aki_left
&& aki_right == &a.aki_right
&& offsets == other_offsets
&& font_family == &b.font_family
&& font_style == &b.font_style
@@ -1012,9 +1044,9 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool {
/// character style's name, leading, baseline shift, rotation, Character Alignment, Character
/// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its
/// run's, see [`shape_segment`]), the space before a line's first character ([`space_before`]),
/// the OpenType features (each run's apply to its own characters, as features over a range of the
/// one buffer) and the tracking, as long as the tracking keeps or drops standard ligatures alike
/// ([`crate::features::ligatures_suppressed_by`]).
/// Insert Aki ([`aki`]), the OpenType features (each run's apply to its own characters, as features
/// over a range of the one buffer) and the tracking, as long as the tracking keeps or drops
/// standard ligatures alike ([`crate::features::ligatures_suppressed_by`]).
fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
// Every field is named, so that a new attribute has to be sorted into one group or the other.
let CharStyle {
@@ -1027,6 +1059,8 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
tracking,
kerning: _,
kerning_before: _,
aki_left: _,
aki_right: _,
optical_kerning: _,
baseline_shift: _,
h_scale,
@@ -1128,9 +1162,9 @@ fn shaping_script(c: char) -> Script {
/// The art is scaled uniformly to `scale` x the font size tall, its left edge on the pen and its
/// vertical centre on the middle of the cap height raised by the inline's shift (see
/// [`InlineArt`]). Its advance is the scaled art width plus tracking, its character's manual
/// kerning and the space before it at a line's start ([`space_before`]). Right to left in
/// horizontal type the manual kerning also moves the art right by the value, as it
/// moves a letter's glyph. The art doesn't take the run's Horizontal Scale; the tracking and the
/// kerning, the space before it at a line's start ([`space_before`]) and its Insert Aki ([`aki`]).
/// Right to left in horizontal type the manual kerning also moves the art right by the value, as it
/// moves a letter's glyph, and Insert Aki moves it as it moves a letter's glyph. The art doesn't take the run's Horizontal Scale; the tracking and the
/// kerning do, as after a letter ([`spacing_scale`]). The glyph's ascent and descent grow to the
/// art's extent so a tall graphic opens up its line. A missing symbol takes a square of the same
/// height and draws nothing.
@@ -1164,7 +1198,9 @@ fn inline_glyph(
let tracking = Some(st.tracking / 1000.0 * spacing_em).filter(|t| t.is_finite()).unwrap_or(0.0);
let manual_kern = st.kerning.map(|v| v / 1000.0 * spacing_em).filter(|k| k.is_finite()).unwrap_or(0.0);
let before = space_before(text, range.start, st, spacing_em);
let adv = width + tracking + manual_kern + before;
let (aki_left, aki_right) = aki(st, spacing_em);
let adv = width + tracking + manual_kern + before + aki_left + aki_right;
let aki_shift = if level.is_rtl() && !vertical { aki_right } else { aki_left };
SGlyph {
face: face.clone(),
gid: 0,
@@ -1175,7 +1211,9 @@ fn inline_glyph(
tracking: if adv.is_finite() { tracking } else { 0.0 },
dx: 0.0,
dy: 0.0,
kern_shift: if level.is_rtl() && !vertical { manual_kern } else { before },
kern_shift: if level.is_rtl() && !vertical { manual_kern } else { before } + aki_shift,
aki_shift,
aki: if adv.is_finite() { aki_left + aki_right } else { 0.0 },
// Not used to draw (the art has its own transform), but they make the glyph's em box
// its run's em: Character Alignment and Top-to-Top leading treat an inline graphic as a
// character of its run's size, whatever its scale (see `layout::glyph_em`).
@@ -1624,23 +1662,29 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
};
let mut kern_shift = 0.0;
let mut tracked = 0.0;
let (mut aki_shift, mut aki_in_adv) = (0.0, 0.0);
if ch == SOFT_HYPHEN || ch == '\u{2028}' {
adv = 0.0;
} else {
let manual_kern = gst.kerning.map(|v| v / 1000.0 * spacing_em).unwrap_or(0.0);
let before = space_before(text, cl, gst, spacing_em);
let (aki_left, aki_right) = aki(gst, spacing_em);
// Manual kerning spaces a character from the next one in reading order. Right to left,
// that one is drawn to its left: the cluster's glyphs move right along the baseline by
// the value, so that the space its last glyph's advance gains is at the cluster's left.
// The space before a line's first character moves them the other way.
// The space before a line's first character moves them the other way. Insert Aki moves
// them past the space before them in reading order: Aki Left, or right to left Aki Right.
if level.is_rtl() && !feats.vertical {
kern_shift = manual_kern;
aki_shift = aki_right;
kern_shift = manual_kern + aki_shift;
} else {
kern_shift = before;
aki_shift = aki_left;
kern_shift = before + aki_shift;
}
if last_in_cluster {
tracked = gst.tracking / 1000.0 * spacing_em;
adv += tracked + manual_kern + before;
aki_in_adv = aki_left + aki_right;
adv += tracked + manual_kern + before + aki_in_adv;
}
}
out.push(SGlyph {
@@ -1654,6 +1698,8 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
dx: xo as f64 * k * hs,
dy: -(yo as f64) * k * vs,
kern_shift,
aki_shift,
aki: aki_in_adv,
sx: k * hs,
sy: k * vs,
bshift: gst.baseline_shift + pos_shift,
+1
View File
@@ -3,6 +3,7 @@ use kurbo::{Affine, Shape};
use vectorcraft_doc::{CharStyle, Justify, TextKind, TextRun};
use vectorcraft_geom::PathData;
mod aki;
mod alternates;
mod axes;
mod bidi;
+258
View File
@@ -0,0 +1,258 @@
//! Insert Aki Left and Right (`CharStyle::aki_left`, `CharStyle::aki_right`): space before and
//! after a character in reading order, in thousandths of its em, that wrapping counts, alignment
//! keeps at a line's end and justification does not stretch.
use super::{area, db, point, serif, style};
use crate::*;
use kurbo::Shape;
use vectorcraft_doc::{CharStyle, Justify};
/// Where glyph `byte` is drawn along a horizontal line.
fn drawn_x(l: &TextLayout, byte: usize) -> f64 {
l.glyphs.iter().find(|g| g.byte == byte).map(|g| g.xf.as_coeffs()[4]).unwrap()
}
/// `t` with `f` applied to the style of the character at `byte`.
fn with(t: &TextObject, byte: usize, f: impl Fn(&mut CharStyle)) -> TextObject {
let mut t = t.clone();
let end = edit::next_char(&t.plain_text(), byte);
edit::style_range(&mut t.runs, byte, end, f);
t
}
/// How far each of `bytes` moved along the line from `a` to `b`, laid out in `fonts`.
fn moves_in(fonts: &FontDb, a: &TextObject, b: &TextObject, bytes: &[usize]) -> Vec<f64> {
let (la, lb) = (layout(fonts, a), layout(fonts, b));
bytes.iter().map(|&i| drawn_x(&lb, i) - drawn_x(&la, i)).collect()
}
fn moves(a: &TextObject, b: &TextObject, bytes: &[usize]) -> Vec<f64> {
moves_in(db(), a, b, bytes)
}
fn near(values: &[f64], expected: &[f64]) -> bool {
values.len() == expected.len() && values.iter().zip(expected).all(|(v, e)| (v - e).abs() < 1e-6)
}
#[test]
fn aki_left_spaces_before_a_character_and_aki_right_after_it() {
let plain = point("HOH", style(100.0));
// 250/1000 em of 100 pt before the O: 25 pt, the O and the H after it move.
let left = moves(&plain, &with(&plain, 1, |s| s.aki_left = 250.0), &[0, 1, 2]);
assert!(near(&left, &[0.0, 25.0, 25.0]), "{left:?}");
// After the O: only the H after it moves.
let right = moves(&plain, &with(&plain, 1, |s| s.aki_right = 250.0), &[0, 1, 2]);
assert!(near(&right, &[0.0, 0.0, 25.0]), "{right:?}");
// Both sides add up, and a value above one em is kept to one em.
let both = moves(&plain, &with(&plain, 1, |s| (s.aki_left, s.aki_right) = (250.0, 500.0)), &[0, 1, 2]);
assert!(near(&both, &[0.0, 25.0, 75.0]), "{both:?}");
let most = moves(&plain, &with(&plain, 1, |s| s.aki_right = 5000.0), &[2]);
assert!(near(&most, &[100.0]), "{most:?}");
let not_a_number = moves(&plain, &with(&plain, 1, |s| s.aki_left = f64::NAN), &[1, 2]);
assert!(near(&not_a_number, &[0.0, 0.0]), "{not_a_number:?}");
assert_eq!(aki_space("HOH", 1, &with(&plain, 1, |s| s.aki_left = 500.0).runs[1].style, false), (50.0, 0.0));
}
#[test]
fn aki_takes_the_em_of_the_character_as_tracking_does() {
let narrow = point("HOH", CharStyle { h_scale: 50.0, ..style(100.0) });
let moved = moves(&narrow, &with(&narrow, 1, |s| s.aki_left = 250.0), &[1, 2]);
assert!(near(&moved, &[12.5, 12.5]), "{moved:?}");
}
#[test]
fn optical_kerning_spaces_the_pair_as_without_the_aki() {
let optical = point("AVA", CharStyle { optical_kerning: true, ..style(100.0) });
let moved = moves(&optical, &with(&optical, 1, |s| s.aki_left = 250.0), &[0, 1, 2]);
assert!(near(&moved, &[0.0, 25.0, 25.0]), "{moved:?}");
let moved = moves(&optical, &with(&optical, 0, |s| s.aki_right = 250.0), &[0, 1, 2]);
assert!(near(&moved, &[0.0, 25.0, 25.0]), "{moved:?}");
// A letter with a combining mark: the pair is measured from the letter, not from the mark
// whose advance holds the cluster's Aki.
let marked = point("H\u{301}V", CharStyle { optical_kerning: true, ..style(100.0) });
let after = "H\u{301}".len();
let moved = moves(&marked, &with(&marked, 0, |s| s.aki_right = 1000.0), &[0, after]);
assert!(near(&moved, &[0.0, 100.0]), "{moved:?}");
}
#[test]
fn a_right_aligned_line_keeps_the_aki_after_its_last_character() {
let mut right = point("HOH", style(100.0));
right.para.justify = Justify::Right;
// Unlike the tracking after a line's last character, the Aki is part of the line.
let moved = moves(&right, &with(&right, 2, |s| s.aki_right = 250.0), &[0, 1, 2]);
assert!(near(&moved, &[-25.0, -25.0, -25.0]), "{moved:?}");
let tracked = moves(&right, &with(&right, 2, |s| s.tracking = 250.0), &[0, 2]);
assert!(near(&tracked, &[0.0, 0.0]), "{tracked:?}");
// At the line's start the Aki Left is kept too.
let mut left = point("HOH", style(100.0));
left.para.justify = Justify::Left;
let moved = moves(&left, &with(&left, 0, |s| s.aki_left = 250.0), &[0, 2]);
assert!(near(&moved, &[25.0, 25.0]), "{moved:?}");
}
#[test]
fn a_line_too_wide_with_its_aki_wraps() {
let one = layout(db(), &point("HOH HOH", style(50.0)));
let wide = one.lines[0].x1 - one.lines[0].x0;
let line_of = |t: &TextObject, byte: usize| layout(db(), t).glyphs.iter().find(|g| g.byte == byte).unwrap().line;
let fits = area("HOH HOH", style(50.0), Rect::new(0.0, 0.0, wide + 5.0, 400.0), Justify::Left);
assert_eq!(line_of(&fits, 4), 0, "both words fit");
// 250/1000 em of 50 pt is 12.5 pt, more than the 5 pt the frame has left.
assert_eq!(line_of(&with(&fits, 1, |s| s.aki_right = 250.0), 4), 1, "the second word wraps");
// The Aki after the last letter of a wrapped line stays on that line: the next line starts
// where it did.
let narrow = area("HOH HOH", style(50.0), Rect::new(0.0, 0.0, wide * 0.6, 400.0), Justify::Left);
let spaced = with(&narrow, 2, |s| s.aki_right = 250.0);
assert_eq!((line_of(&narrow, 4), line_of(&spaced, 4)), (1, 1));
let moved = moves(&narrow, &spaced, &[0, 4, 5]);
assert!(near(&moved, &[0.0, 0.0, 0.0]), "{moved:?}");
}
#[test]
fn justification_does_not_stretch_or_narrow_the_aki() {
// Desired Glyph Scaling 150% widens every glyph, and Word Spacing 200% every word space; the Aki
// stays 25 pt wide.
let mut scaled = point("HOH", style(100.0));
scaled.para.justification.glyph_scaling = [150.0, 150.0, 150.0];
let moved = moves(&scaled, &with(&scaled, 0, |s| s.aki_right = 250.0), &[0, 1, 2]);
assert!(near(&moved, &[0.0, 25.0, 25.0]), "{moved:?}");
let moved = moves(&scaled, &with(&scaled, 1, |s| s.aki_left = 250.0), &[1, 2]);
assert!(near(&moved, &[25.0, 25.0]), "{moved:?}");
// A glyph that justification widens to fill the line keeps the Aki before it at its width,
// and its own width, which ligature carets stand in, starts where the glyph is drawn.
let mut filled = area("HOH", style(100.0), Rect::new(0.0, 0.0, 600.0, 400.0), Justify::JustifyAll);
filled.para.justification.glyph_scaling = [100.0, 100.0, 300.0];
let l = layout(db(), &with(&filled, 1, |s| s.aki_left = 250.0));
let g = l.glyphs.iter().find(|g| g.byte == 1).unwrap();
assert!(g.scale > 1.0 + 1e-6, "the glyph is widened: {}", g.scale);
let drawn = g.xf.as_coeffs()[4];
assert!((g.origin.x + g.width_start - drawn).abs() < 1e-6, "{} {} {drawn}", g.origin.x, g.width_start);
let mut spaced = point("H H", style(100.0));
spaced.para.justification.word_spacing = [200.0, 200.0, 200.0];
let moved = moves(&spaced, &with(&spaced, 1, |s| s.aki_right = 250.0), &[0, 2]);
assert!(near(&moved, &[0.0, 25.0]), "{moved:?}");
}
#[test]
fn with_whole_point_widths_the_aki_is_whole_points_and_justification_keeps_it() {
// 250/1000 em of 10 pt is 2.5 pt, set as 3 pt with Fractional Widths off, with or without
// Desired Glyph Scaling 150%.
for scaling in [100.0, 150.0] {
let mut plain = point("HOH", style(10.0));
plain.fractional_widths = false;
plain.para.justification.glyph_scaling = [scaling; 3];
let left = moves(&plain, &with(&plain, 1, |s| s.aki_left = 250.0), &[0, 1, 2]);
assert!(near(&left, &[0.0, 3.0, 3.0]), "Glyph Scaling {scaling}: {left:?}");
let right = moves(&plain, &with(&plain, 1, |s| s.aki_right = 250.0), &[0, 1, 2]);
assert!(near(&right, &[0.0, 0.0, 3.0]), "Glyph Scaling {scaling}: {right:?}");
// 1.5 pt on each side: each side is set as 2 pt.
let both = moves(&plain, &with(&plain, 1, |s| (s.aki_left, s.aki_right) = (150.0, 150.0)), &[0, 1, 2]);
assert!(near(&both, &[0.0, 2.0, 4.0]), "Glyph Scaling {scaling}: {both:?}");
}
}
#[test]
fn a_ligature_and_a_letter_with_its_mark_take_the_aki_of_their_first_character() {
let plain = point("fit", serif(100.0));
let glyphs = |t: &TextObject| layout(db(), t).glyphs.len();
assert_eq!(glyphs(&plain), 2, "the font joins fi");
let spaced = with(&plain, 0, |s| (s.aki_left, s.aki_right) = (250.0, 250.0));
assert_eq!(glyphs(&spaced), 2, "still joined");
let moved = moves(&plain, &spaced, &[0, 2]);
assert!(near(&moved, &[25.0, 50.0]), "{moved:?}");
// On the i alone it is not read: the ligature's first character is the f.
let on_i = with(&plain, 1, |s| s.aki_right = 250.0);
assert_eq!(glyphs(&on_i), 2);
let moved = moves(&plain, &on_i, &[0, 2]);
assert!(near(&moved, &[0.0, 0.0]), "{moved:?}");
// A combining acute after e: the letter's Aki spaces the pair, the mark's own is not read.
let marked = point("e\u{301}a", style(100.0));
let after = "e\u{301}".len();
let moved = moves(&marked, &with(&marked, 0, |s| s.aki_right = 250.0), &[0, after]);
assert!(near(&moved, &[0.0, 25.0]), "{moved:?}");
let moved = moves(&marked, &with(&marked, 1, |s| s.aki_right = 250.0), &[0, after]);
assert!(near(&moved, &[0.0, 0.0]), "{moved:?}");
}
#[test]
fn right_to_left_aki_left_is_on_the_right_of_the_character() {
// Reading order א ב ג is drawn right to left: Aki Left on ב widens the gap between א and ב,
// Aki Right the gap between ב and ג.
let fonts = FontDb::global();
let plain = point("אבג", style(100.0));
let (a, b, c) = (0, "א".len(), "אב".len());
let gaps = |t: &TextObject| {
let l = layout(fonts, t);
(drawn_x(&l, a) - drawn_x(&l, b), drawn_x(&l, b) - drawn_x(&l, c))
};
let base = gaps(&plain);
let left = gaps(&with(&plain, b, |s| s.aki_left = 250.0));
assert!((left.0 - base.0 - 25.0).abs() < 1e-6 && (left.1 - base.1).abs() < 1e-6, "{base:?} {left:?}");
let right = gaps(&with(&plain, b, |s| s.aki_right = 250.0));
assert!((right.0 - base.0).abs() < 1e-6 && (right.1 - base.1 - 25.0).abs() < 1e-6, "{base:?} {right:?}");
}
#[test]
fn in_vertical_type_aki_left_is_above_the_character_and_aki_right_below() {
// An upright glyph (§) and letters lying on their side: 250/1000 em of 20 pt is 5 pt down the
// column.
for text in ["§§", "ab"] {
let mut plain = point(text, style(20.0));
plain.xf = Affine::IDENTITY;
plain.vertical = true;
let centers = |t: &TextObject| layout(db(), t).glyphs.iter().map(|g| g.outline.bounding_box().center()).collect::<Vec<_>>();
let base = centers(&plain);
let second = edit::next_char(text, 0);
// [first, second] glyph moved down the column, for Aki on one character.
for (spaced, down) in [
(with(&plain, 0, |s| s.aki_left = 250.0), [5.0, 5.0]),
(with(&plain, 0, |s| s.aki_right = 250.0), [0.0, 5.0]),
(with(&plain, second, |s| s.aki_left = 250.0), [0.0, 5.0]),
(with(&plain, second, |s| s.aki_right = 250.0), [0.0, 0.0]),
] {
let moved = centers(&spaced);
for i in 0..2 {
assert!((moved[i].y - base[i].y - down[i]).abs() < 1e-6, "{text} {i}: {base:?} {moved:?}");
assert!((moved[i].x - base[i].x).abs() < 1e-6, "{text} {i}: {base:?} {moved:?}");
}
}
}
}
/// A tate-chu-yoko block takes the Insert Aki of its first character above and below it, and
/// keeps its characters across the column as without it.
#[test]
fn a_tate_chu_yoko_block_is_spaced_by_the_aki_of_its_first_character() {
let mut plain = point("a12b", style(20.0));
plain.xf = Affine::IDENTITY;
plain.vertical = true;
let centers = |t: &TextObject| layout(db(), t).glyphs.iter().map(|g| g.outline.bounding_box().center()).collect::<Vec<_>>();
let base = centers(&plain);
assert_eq!(base.len(), 4);
// [a, 1, 2, b] moved down the column: 250/1000 em of 20 pt is 5 pt.
for (spaced, down) in [
(with(&plain, 1, |s| s.aki_left = 250.0), [0.0, 5.0, 5.0, 5.0]),
(with(&plain, 1, |s| s.aki_right = 250.0), [0.0, 0.0, 0.0, 5.0]),
(with(&plain, 1, |s| (s.aki_left, s.aki_right) = (250.0, 500.0)), [0.0, 5.0, 5.0, 15.0]),
(with(&plain, 2, |s| (s.aki_left, s.aki_right) = (250.0, 500.0)), [0.0; 4]),
] {
let moved = centers(&spaced);
for i in 0..4 {
assert!((moved[i].y - base[i].y - down[i]).abs() < 1e-6, "{i}: {base:?} {moved:?}");
assert!((moved[i].x - base[i].x).abs() < 1e-6, "{i}: {base:?} {moved:?}");
}
}
// With Fractional Widths off, 150/1000 em of 10 pt on each side (1.5 pt) is set as 2 pt above
// the block and 2 pt below it.
let mut whole = point("a12b", style(10.0));
whole.xf = Affine::IDENTITY;
whole.vertical = true;
whole.fractional_widths = false;
let base = centers(&whole);
let moved = centers(&with(&whole, 1, |s| (s.aki_left, s.aki_right) = (150.0, 150.0)));
let down = [0.0, 2.0, 2.0, 4.0];
for i in 0..4 {
assert!((moved[i].y - base[i].y - down[i]).abs() < 1e-6, "{i}: {base:?} {moved:?}");
assert!((moved[i].x - base[i].x).abs() < 1e-6, "{i}: {base:?} {moved:?}");
}
}
+4 -3
View File
@@ -283,8 +283,9 @@ fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize
}
/// Draws the Control bar's Align group after the artboard controls, with the Artboard tool in use:
/// the Align buttons, the Align To menu and, for two or more selected artboards, the Distribute
/// buttons. They align and distribute the selected artboards
/// the Align buttons, the Align To menu and, while they can space the selected artboards
/// ([`crate::panels::align::artboards_distribute`]), the Distribute buttons. They align and
/// distribute the selected artboards
/// ([`crate::panels::align::run_button`]). Each shows only while the bar has room for it, and none
/// while the panel menu has the group off.
fn artboard_align_group(app: &mut VectorcraftApp, ui: &mut Ui) {
@@ -295,7 +296,7 @@ fn artboard_align_group(app: &mut VectorcraftApp, ui: &mut Ui) {
crate::panels::align::align_buttons(app, ui, BUTTON);
if ui.available_width() >= crate::panels::align::align_to_menu_width(BUTTON) + ui.spacing().item_spacing.x {
crate::panels::align::align_to_menu(app, ui, BUTTON);
if crate::panels::align::artboards_selected(app) > 1 && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) {
if crate::panels::align::artboards_distribute(app) && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) {
ui.add_space(GROUP_GAP);
crate::panels::align::distribute_buttons(app, ui, BUTTON);
}
+6 -2
View File
@@ -2670,7 +2670,8 @@ fn menus_stop_above_a_control_bar_docked_at_the_bottom() {
}
/// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard
/// controls while it has room, and the Distribute buttons for two or more selected artboards. A
/// controls while it has room, and the Distribute buttons for two or more selected artboards with
/// Align to Artboard and three or more with Align to Selection. A
/// click aligns the selected artboards as the Align panel's button does. The group is left out
/// while the panel menu has it off.
#[test]
@@ -2699,7 +2700,10 @@ fn the_control_bar_aligns_the_selected_artboards_with_the_artboard_tool() {
assert!(button(&mut app, "Vertical Align Top").is_some(), "one artboard: the Align buttons");
assert!(button(&mut app, "Horizontal Distribute Left").is_none(), "one artboard: no Distribute buttons");
app.session.set_tool_option("selected", &json!([1, 0]));
assert!(button(&mut app, "Horizontal Distribute Left").is_some(), "two artboards: the Distribute buttons");
assert!(button(&mut app, "Horizontal Distribute Left").is_none(), "two artboards, Align to Selection: no Distribute buttons");
app.ui.align_to = crate::panels::align::AlignTo::Artboard;
assert!(button(&mut app, "Horizontal Distribute Left").is_some(), "two artboards, Align to Artboard: the Distribute buttons");
app.ui.align_to = crate::panels::align::AlignTo::Selection;
let r = button(&mut app, "Vertical Align Top").expect("Vertical Align Top");
let press =
|pressed| egui::Event::PointerButton { pos: r.center(), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
@@ -26,9 +26,12 @@ const NUMBERS: &[&str] = &["size", "leading", "kerning", "tracking"];
/// The on, off or unset checkboxes.
const SWITCHES: &[&str] = &["underline", "strikethrough", "standardVerticalRoman"];
/// The attributes of Advanced Character Formats, in the order the section shows them.
const ADVANCED: &[&str] = &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation", "language"];
const ADVANCED: &[&str] = &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation", "akiLeft", "akiRight", "language"];
/// The number fields of Advanced Character Formats.
const ADVANCED_NUMBERS: &[&str] = &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation"];
const ADVANCED_NUMBERS: &[&str] = &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation", "akiLeft", "akiRight"];
/// The Insert Aki Left and Right fields, which take the Character panel's presets and stop at
/// [`vectorcraft_doc::text::MAX_AKI`].
const AKI: [&str; 2] = ["akiLeft", "akiRight"];
/// The attributes of Character Color.
const COLOR: &[&str] = &["fill", "stroke", "stroke_width", "overprint_fill", "overprint_stroke"];
/// The fields of Character Color: the fill and stroke paints, their tints in percent, the stroke
@@ -81,6 +84,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
"tcyUpDown",
"tcyLeftRight",
"rotation",
"akiLeft",
"akiRight",
"language",
"fill",
"fill_tint",
@@ -268,6 +273,8 @@ fn optional_number(d: &Dialog, key: &str) -> Result<Option<Value>, String> {
"tcyUpDown" => tl!("Tate-chu-yoko Up/Down"),
"tcyLeftRight" => tl!("Tate-chu-yoko Left/Right"),
"rotation" => tl!("Character Rotation"),
"akiLeft" => tl!("Insert Aki Left"),
"akiRight" => tl!("Insert Aki Right"),
"fill_tint" => tl!("Fill Tint"),
"stroke_tint" => tl!("Stroke Tint"),
"stroke_width" => tl!("Weight"),
@@ -312,6 +319,9 @@ fn optional_number(d: &Dialog, key: &str) -> Result<Option<Value>, String> {
}
// An angle from -180 to 180 degrees, as text.setFormat stores it.
let n = if key == "rotation" { (n + 180.0).rem_euclid(360.0) - 180.0 } else { n };
// Insert Aki stops at 0 and at the largest value the style takes, as the Character
// panel's fields do.
let n = if AKI.contains(&key) { n.clamp(0.0, vectorcraft_doc::text::MAX_AKI) } else { n };
Ok(Some(json!(n)))
}
}
@@ -590,7 +600,7 @@ pub(crate) fn reset_basic(d: &mut Dialog) {
}
}
/// Reset Panel in Advanced Character Formats: its seven attributes become unset.
/// Reset Panel in Advanced Character Formats: its nine attributes become unset.
pub(crate) fn reset_advanced(d: &mut Dialog) {
d.fields.insert("__resetAdvanced".into(), json!(true));
for key in ADVANCED_NUMBERS {
@@ -745,7 +755,8 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) {
}
/// Advanced Character Formats: Horizontal Scale, Vertical Scale, Baseline Shift, the Tate-chu-yoko
/// Up/Down and Left/Right, Character Rotation and Language, each empty (unset) or set.
/// Up/Down and Left/Right, Character Rotation, Insert Aki Left and Right (with the Character
/// panel's presets) and Language, each empty (unset) or set.
pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) {
egui::Grid::new("character-style-advanced").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| {
for (key, caption, unit) in [
@@ -766,6 +777,16 @@ pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) {
});
ui.end_row();
}
let presets: Vec<String> = crate::panels::character::AKI_PRESETS.iter().map(f64::to_string).collect();
let presets: Vec<&str> = presets.iter().map(String::as_str).collect();
for (key, caption) in [("akiLeft", tl!("Insert Aki Left")), ("akiRight", tl!("Insert Aki Right"))] {
let row = ui.label(caption);
let value = if d.fields.get(key).is_none_or(Value::is_null) { String::new() } else { d.str(key) };
if let Some(v) = ui.label_inputs_by(row.id, |ui| crate::widgets::text_presets(ui, (KIND, key), &value, &presets, 160.0)) {
d.fields.insert(key.into(), json!(v));
}
ui.end_row();
}
let row = ui.label(tl!("Language:"));
let names: Vec<&str> = std::iter::once(" ").chain(vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, _, _)| *name)).collect();
let current = d.fields.get("language").and_then(Value::as_str).unwrap_or("").to_string();
@@ -1684,6 +1705,60 @@ mod tests {
assert_eq!(def.attrs["tcyLeftRight"], json!(6.0));
}
#[test]
fn insert_aki_fields_show_set_reset_and_stop_at_the_character_panel_limits() {
let d = dialog_for(json!({"akiLeft": 250.0, "size": 12.0}));
assert_eq!((d.fields["akiLeft"].clone(), d.fields["akiRight"].clone()), (json!(250.0), json!("")));
assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"akiLeft": 250.0, "size": 12.0})));
let mut d = dialog_for(json!({"akiLeft": 250.0}));
d.fields.insert("akiLeft".into(), json!(""));
d.fields.insert("akiRight".into(), json!("500"));
assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"akiRight": 500.0})));
// A typed value stops at 0 and at 1000, as in the Character panel's fields.
for (typed, kept) in [("5000", 1000.0), ("-5", 0.0), ("1000", 1000.0)] {
d.fields.insert("akiRight".into(), json!(typed));
assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"akiRight": kept})), "{typed}");
}
d.fields.insert("akiLeft".into(), json!("wide"));
assert_eq!(edited_attrs(&d).unwrap_err(), "Insert Aki Left must be a number");
let mut d = dialog_for(json!({"akiLeft": 250.0, "akiRight": 500.0, "size": 12.0}));
d.fields.insert("section".into(), json!("advanced"));
reset_section(&mut d);
assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"size": 12.0})));
}
#[test]
fn insert_aki_fields_are_drawn_and_commit_to_the_style_and_its_text() {
let mut app = app();
app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap();
let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap();
app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap();
open(&mut app, "Body").unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 900.0));
let mut d = app.ui.dialog.clone().unwrap();
let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| advanced_body(ui, &mut d));
let texts = texts_of(&out);
out.textures_delta.clear();
for label in ["Insert Aki Left", "Insert Aki Right"] {
assert!(texts.iter().any(|(text, _)| text == label), "{label} is drawn: {texts:?}");
}
{
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("akiLeft".into(), json!("250"));
d.fields.insert("akiRight".into(), json!("2000"));
}
super::super::confirm(&mut app).unwrap();
let state = app.session.doc().unwrap();
assert_eq!(state.doc.char_styles[0].attrs, attrs(json!({"size": 24.0, "akiLeft": 250.0, "akiRight": 1000.0})));
let vectorcraft_doc::NodeKind::Text(t) = &state.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") };
assert!(t.runs.iter().all(|r| (r.style.aki_left, r.style.aki_right) == (250.0, 1000.0)));
}
/// The negated tags of the twenty stylistic sets: an explicit empty Stylistic Sets choice.
fn no_sets() -> Vec<String> {
vectorcraft_text::EXTRA_FEATURES[..20].iter().map(|s| format!("-{s}")).collect()
+3 -2
View File
@@ -2,7 +2,7 @@
//! artboard, after a central file of the whole document for EPS with two or more when art shows,
//! or one page each in a PDF); without artboards the export covers the visible art. OK
//! picks the file, then the format's options dialog follows (PNG/JPEG/WebP/PNG-8/GIF Options, SVG
//! Options, Text Export Options, DXF Options, EPS Options, and Save PDF for artboards as pages),
//! Options, Text Export Options, DXF Options, EPS Options, and Save PDF),
//! else the file is written. DWG is listed, greyed out, with what to use instead. The formats of
//! installed exporter plug-ins come after the built-in ones: they write the whole document, and one
//! with parameters asks for them before writing (`plugin::open_export`).
@@ -169,8 +169,9 @@ fn options_or_write(
}
Ok(Value::Null)
}
// Artboards as pages go on in Save PDF; the art's bounds are written straight away.
// Save PDF writes the artboards as pages, or one page of the art's bounds.
"pdf" if use_artboards => save_pdf::open(app, &json!({ "path": path, "range": (!all).then_some(range) })),
"pdf" => save_pdf::open(app, &json!({ "path": path, "useArtboards": false })),
"txt" => {
text_export::open(app, &path);
Ok(Value::Null)
+248 -2
View File
@@ -25,6 +25,13 @@
//! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new
//! colours as a colour group named `groupName`.
//!
//! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an
//! object takes the palette of the object a Selection tool click takes, a drag takes the palette
//! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The
//! rows that aren't excluded take the picked colors as their new colors, the most used color first
//! and repeating when the rows outnumber them, and the art previews them; OK keeps them as one
//! undo step. A new count of Colors keeps the picks: the new rows take them again.
//!
//! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot
//! color}]), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`,
//! `preserveGrays`, `limitTo` (library id, "document" for the document's swatches, "" for none),
@@ -33,7 +40,9 @@
//! a gray and Tint for a spot color; `global`: Global Adjust, on the Edit tab), `globalAdjust`
//! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s
//! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`;
//! unset: `smooth`). Changing `colors`, a preserve flag or `limitTo` reduces the rows again.
//! unset: `smooth`), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as
//! `recolor.pickTheme`'s `picks`; a new list recolors the rows). Changing `colors`, a preserve
//! flag or `limitTo` reduces the rows again.
use egui::{Rect, Sense, Ui, pos2, vec2};
use serde_json::{Value, json};
@@ -142,7 +151,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
"preserveWhite": kept("preserveWhite", true), "preserveBlack": kept("preserveBlack", true),
"preserveGrays": kept("preserveGrays", false), "limitTo": limit,
"group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true,
"preview": true, "__art": art, "__assign": assign, "__newGroup": new_group,
"preview": true, THEME_PICKER: false, THEME_PICKS: [], "__art": art, "__assign": assign, "__newGroup": new_group,
});
let mut d = Dialog::new(KIND, fields);
// Without art the rows are there from the start: limit them now (art's rows snap as they reduce).
@@ -203,6 +212,99 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) {
Err(e) => app.status(e.to_string()),
}
d.fields.insert(DONE.into(), sig);
// New rows take the colors picked with the Color Theme Picker again.
d.fields.remove(THEME_DONE);
}
/// The fields of the Color Theme Picker: whether a click or drag on the canvas picks colors, and
/// the picks so far (`recolor.pickTheme`'s `picks`); the picks the rows last took them from.
const THEME_PICKER: &str = "themePicker";
const THEME_PICKS: &str = "themePicks";
const THEME_DONE: &str = "__themePicked";
/// When the picks of the Color Theme Picker changed, give the rows that aren't excluded the
/// palette of the art picked (`recolor.pickTheme`, as many colors as those rows), in row order;
/// with fewer colors than rows, the colors repeat. Picks that touch no art leave the rows as they
/// are.
fn sync_theme(app: &mut VectorcraftApp, d: &mut Dialog) {
let picks = d.fields.get(THEME_PICKS).cloned().unwrap_or(Value::Null);
if !picks.as_array().is_some_and(|a| !a.is_empty()) || d.fields.get(THEME_DONE) == Some(&picks) {
return;
}
d.fields.insert(THEME_DONE.into(), picks.clone());
let mut rs = rows(d);
let active = active_rows(&rs);
if active.is_empty() {
return;
}
// The art as it is, not as the preview shows it; the preview runs again afterwards.
if d.fields.remove(super::form::PREVIEWED).is_some() {
let _ = app.session.cancel_interaction();
}
let colors = match app.session.execute("recolor.pickTheme", &json!({"picks": picks, "colors": active.len().min(64)})) {
Ok(r) => r["colors"].as_array().map(|a| a.iter().filter_map(color_value).collect::<Vec<_>>()).unwrap_or_default(),
Err(e) => return app.status(e.to_string()),
};
if colors.is_empty() {
return;
}
for (n, &i) in active.iter().enumerate() {
set_to(&mut rs[i], &colors[n % colors.len()]);
}
snap(app, d, &mut rs);
d.fields.insert("rows".into(), Value::Array(rs));
// The rows hold no slider edit.
d.fields.remove(COMPS);
}
/// The picks recolor.pickTheme takes at most; the oldest go first.
const MAX_PICKS: usize = 256;
/// While the Color Theme Picker is on: a layer over the canvas, under the dialog, takes the clicks
/// and drags there as picks (with Shift they add to the picks so far, else they replace them) and
/// draws a drag's marquee, whose sides follow the document's axes.
fn theme_overlay(app: &VectorcraftApp, ctx: &egui::Context, d: &mut Dialog) {
let (Some(rect), Some(view)) = (app.canvas_rect, app.view()) else { return };
let xf = crate::canvas::Xf::at(rect, view, app.canvas_ui_zoom);
let accent = Tokens::get(ctx).accent;
let id = egui::Id::unique("recolor-theme-picker");
let shown = egui::Area::new(id).order(egui::Order::Middle).fixed_pos(rect.min).movable(false).show(ctx, |ui| {
let resp = ui.allocate_rect(rect, Sense::click_and_drag()).on_hover_cursor(egui::CursorIcon::Crosshair);
let shift = ui.input(|i| i.modifiers.shift);
// Where a press on the canvas began, kept from the first frame that sees it for the frame
// that releases it (the pointer forgets it then).
let from = egui::Id::unique("recolor-theme-drag");
if let Some(o) = ui.input(|i| i.pointer.press_origin()).filter(|o| rect.contains(*o)) {
ui.data_mut(|m| m.insert_temp(from, o));
}
if resp.clicked() {
ui.data_mut(|m| m.remove::<egui::Pos2>(from));
let p = xf.to_doc(resp.interact_pointer_pos().or(ui.input(|i| i.pointer.latest_pos()))?);
return Some((json!({"at": [p.x, p.y]}), shift));
}
if !(resp.dragged() || resp.drag_stopped()) {
return None;
}
let a = ui.data(|m| m.get_temp::<egui::Pos2>(from))?;
let b = ui.input(|i| i.pointer.latest_pos());
let (a, b) = (xf.to_doc(a), xf.to_doc(b?));
if resp.drag_stopped() {
ui.data_mut(|m| m.remove::<egui::Pos2>(from));
return Some((json!({"rect": [a.x, a.y, b.x, b.y]}), shift));
}
let corners = [(a.x, a.y), (b.x, a.y), (b.x, b.y), (a.x, b.y), (a.x, a.y)];
let pts: Vec<egui::Pos2> = corners.iter().map(|&(x, y)| xf.to_screen(vectorcraft_geom::Point::new(x, y))).collect();
ui.painter().with_clip_rect(rect).extend(egui::Shape::dashed_line(&pts, egui::Stroke::new(1.0, accent), 4.0, 3.0));
None
});
// Above the backdrop of the dialog (which a click elsewhere raises), still under its window.
ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id));
let Some((pick, add)) = shown.inner else { return };
let mut picks = if add { d.fields.get(THEME_PICKS).and_then(Value::as_array).cloned().unwrap_or_default() } else { vec![] };
picks.push(pick);
let extra = picks.len().saturating_sub(MAX_PICKS);
picks.drain(..extra);
d.fields.insert(THEME_PICKS.into(), Value::Array(picks));
}
/// With Limit to Library, the rows' new colours snap to the library's nearest colours.
@@ -298,7 +400,9 @@ fn apply_params(d: &Dialog) -> Value {
fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
sync(app, d);
sync_theme(app, d);
let t = Tokens::get(ui.ctx());
let picking = d.bool(THEME_PICKER);
ui.horizontal(|ui| {
let tab = d.str("tab");
for (id, label) in [("assign", tl!("Assign")), ("edit", tl!("Edit"))] {
@@ -306,6 +410,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
d.fields.insert("tab".into(), json!(id));
}
}
ui.add_space(8.0);
if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() {
d.fields.insert(THEME_PICKER.into(), json!(!picking));
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// The label is drawn after the menu (right-to-left), so it cannot name it by adjacency.
if let Some(i) = widgets::dropdown_named(ui, "recolor-preset", Some(tl!("Preset:")), PRESETS[preset_of(d)], &PRESETS, 130.0) {
@@ -316,6 +424,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
});
widgets::divider(ui);
ui.add_space(4.0);
if d.bool(THEME_PICKER) {
widgets::dim_label(ui, tl!("Click or drag across the art to pick its colors; Shift adds more"));
ui.add_space(4.0);
theme_overlay(app, ui.ctx(), d);
sync_theme(app, d);
}
let mut rs = rows(d);
let top = ui.cursor().top();
let (changed, pick) = if d.str("tab") == "edit" { (edit_tab(app, ui, d, &mut rs), None) } else { assign_tab(app, ui, d, &mut rs) };
@@ -364,6 +478,7 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let mut d = d.clone();
sync(app, &mut d);
sync_theme(app, &mut d);
if d.bool("__newGroup") {
// The new colors with the Global Adjust, snapped to Limit to Library, as `recolor.apply`
// gives them to a group.
@@ -1433,6 +1548,137 @@ mod tests {
assert!(to.as_str().is_some_and(|k| k.starts_with("cmyk ")), "a color picked as RGB is CMYK in a CMYK document: {to}");
}
/// A 15 pt square at (`x`, 10) filled with `fill`, without a stroke.
fn square(app: &mut VectorcraftApp, x: f64, fill: &str) -> u64 {
let id = app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 15, "height": 15})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"ids": [id], "color": fill})).unwrap();
app.run("paint.setStroke", json!({"ids": [id], "none": true})).unwrap();
id
}
fn fill_hex(app: &VectorcraftApp, id: u64) -> String {
let doc = &app.session.doc().unwrap().doc;
doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill().and_then(|f| f.paint.color()).unwrap().to_hex()
}
/// Red and blue squares selected, and green and yellow squares beside them; Recolor Artwork
/// open on the selection with the Exact method, one frame drawn.
fn theme_setup(app: &mut VectorcraftApp, ctx: &egui::Context) -> [u64; 2] {
app.run("file.new", json!({"width": 300, "height": 100})).unwrap();
let art = [square(app, 10.0, "#ff0000"), square(app, 40.0, "#0000ff")];
square(app, 100.0, "#00ff00");
square(app, 130.0, "#ffff00");
app.run("select.set", json!({"ids": art})).unwrap();
app.run("ui.recolorDialog", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id()));
crate::theme::install_fonts(ctx);
frame(app, ctx, 0.0, vec![], 0);
art
}
fn new_colors(app: &VectorcraftApp) -> Vec<Value> {
super::rows(app.ui.dialog.as_ref().unwrap()).iter().map(|r| r["to"].clone()).collect()
}
/// The Color Theme Picker's picks (the `themePicks` field) give the rows that aren't excluded
/// the palette of the art picked, in row order, repeating it when the rows outnumber its
/// colors, and the art previews them. Picks that touch no art leave the rows as they are, and
/// OK keeps the recolor as one undo step.
#[test]
fn theme_picks_give_the_rows_the_palette_of_the_art_picked() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let ctx = egui::Context::default();
let [red, blue] = theme_setup(&mut app, &ctx);
let mut start = new_colors(&app);
start.sort_by_key(Value::to_string);
assert_eq!(start, [json!("rgb 0 0 255"), json!("rgb 255 0 0")]);
// The red art's row and the blue art's row.
let row_of = |app: &VectorcraftApp, key: &str| super::rows(app.ui.dialog.as_ref().unwrap()).iter().position(|r| r["from"][0] == key).unwrap();
let (r, b) = (row_of(&app, "rgb 255 0 0"), row_of(&app, "rgb 0 0 255"));
let undo = app.session.doc().unwrap().history.undo.len();
let set = |app: &mut VectorcraftApp, picks: Value| {
app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks);
};
set(&mut app, json!([{"at": [107, 17]}]));
frame(&mut app, &ctx, 0.1, vec![], 0);
assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")], "one color for both rows");
assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#00ff00".into(), "#00ff00".into()), "the art previews it");
set(&mut app, json!([{"at": [107, 17]}, {"rect": [125, 5, 150, 30]}]));
frame(&mut app, &ctx, 0.2, vec![], 0);
assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 255 255 0")], "a pick added: two colors");
// An excluded row (the red art's) keeps its new color.
let d = app.ui.dialog.as_mut().unwrap();
let mut rs = super::rows(d);
rs[r]["exclude"] = json!(true);
d.fields.insert("rows".into(), Value::Array(rs));
let kept = new_colors(&app)[r].clone();
set(&mut app, json!([{"at": [47, 17]}]));
frame(&mut app, &ctx, 0.3, vec![], 0);
let after = new_colors(&app);
assert_eq!((&after[r], &after[b]), (&kept, &json!("rgb 0 0 255")));
set(&mut app, json!([{"at": [250, 80]}]));
frame(&mut app, &ctx, 0.4, vec![], 0);
assert_eq!(new_colors(&app), after, "empty canvas: the rows stay");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing is committed before OK");
crate::dialogs::confirm(&mut app).unwrap();
assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#0000ff".into()), "the excluded row kept red");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
}
/// One frame with `modifiers` held.
fn frame_with(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec<egui::Event>, modifiers: egui::Modifiers) {
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
let input = egui::RawInput { time: Some(time), events, ..Default::default() };
let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx()));
out.textures_delta.clear();
}
/// With the Color Theme Picker on, a click on the canvas picks the object there and a Shift-drag
/// adds the art inside its marquee; with it off the dialog takes no picks from the canvas.
#[test]
fn the_theme_picker_takes_clicks_and_shift_drags_on_the_canvas() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let ctx = egui::Context::default();
let [red, _] = theme_setup(&mut app, &ctx);
// Clear of the dialog, which centers itself in the screen.
let canvas = Rect::from_min_size(pos2(-1000.0, -1000.0), vec2(3000.0, 3000.0));
app.canvas_rect = Some(canvas);
let xf = crate::canvas::Xf::new(canvas, app.view().unwrap());
let at = |x: f64, y: f64| xf.to_screen(vectorcraft_geom::Point::new(x, y));
let button = |pos, pressed, modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers };
let none = egui::Modifiers::NONE;
let click = |app: &mut VectorcraftApp, pos: egui::Pos2, t: f64| {
frame_with(app, &ctx, t, vec![egui::Event::PointerMoved(pos), button(pos, true, none)], none);
frame_with(app, &ctx, t + 0.05, vec![button(pos, false, none)], none);
frame_with(app, &ctx, t + 0.1, vec![], none);
};
let green = at(107.0, 17.0);
assert!(canvas.contains(green), "{green:?}");
click(&mut app, green, 1.0);
assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get(THEME_PICKS), Some(&json!([])), "off: no picks");
assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get(THEME_PICKER), Some(&json!(false)), "the fields `ui.dialog.set` can set");
app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKER.into(), json!(true));
for n in 0..5 {
frame_with(&mut app, &ctx, 2.0 + f64::from(n) * 0.01, vec![], none);
}
click(&mut app, green, 3.0);
assert_eq!(app.ui.dialog.as_ref().unwrap().fields[THEME_PICKS].as_array().map(Vec::len), Some(1));
assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]);
assert_eq!(fill_hex(&app, red), "#00ff00", "the art previews the picked color");
// A Shift-drag around the yellow square.
let shift = egui::Modifiers::SHIFT;
let (a, b) = (at(125.0, 5.0), at(150.0, 30.0));
frame_with(&mut app, &ctx, 4.0, vec![egui::Event::PointerMoved(a), button(a, true, shift)], shift);
frame_with(&mut app, &ctx, 4.05, vec![egui::Event::PointerMoved(a + (b - a) * 0.5)], shift);
frame_with(&mut app, &ctx, 4.1, vec![egui::Event::PointerMoved(b)], shift);
frame_with(&mut app, &ctx, 4.15, vec![button(b, false, shift)], shift);
frame_with(&mut app, &ctx, 4.2, vec![], none);
let picks = app.ui.dialog.as_ref().unwrap().fields[THEME_PICKS].clone();
assert_eq!(picks.as_array().map(Vec::len), Some(2), "{picks}");
assert!(picks[1].get("rect").is_some(), "{picks}");
assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 255 255 0")]);
}
/// In a CMYK document colors opened alone are saved as a new color group in their own model.
#[test]
fn a_new_group_from_colors_keeps_their_model_in_a_cmyk_document() {
+37 -6
View File
@@ -5,6 +5,8 @@
//! plus `preset`, `range`, `path?` and UI-only `__` keys, so agents fill the dialog with
//! `ui.dialog.set`. OK runs `document.exportPdf` through [`io::export_pdf`]; the Summary is
//! `document.pdfSettings`. Save Preset… names the settings as a preset (`pdf.preset.save`).
//! Opened from Export As with Use Artboards off (`__artBounds`), the dialog has no Artboards
//! section, and OK writes one page of the visible art's bounds through [`io::export`].
//!
//! The same dialog edits a preset (kind `pdfPreset`, from Edit → PDF Presets): a `name` and
//! `description` instead of the preset and artboards, and OK saves the preset.
@@ -45,6 +47,9 @@ pub(super) const PRESET_SPEC: DialogSpec = DialogSpec {
const EDITING: &str = "__editing";
/// Save PDF's field holding the name typed for Save Preset… (present while that row shows).
const SAVE_AS: &str = "__savePresetAs";
/// Save PDF's field that is true when the page is the bounds of the visible art (Export As with
/// Use Artboards off) instead of the artboards.
const ART_BOUNDS: &str = "__artBounds";
pub(super) const SECTIONS: [&str; 7] = ["General", "Compression", "Marks and Bleeds", "Output", "Advanced", "Security", "Summary"];
@@ -76,8 +81,13 @@ pub(super) const LIST_WIDTH: f32 = 150.0;
pub(super) const TOP_LABEL_WIDTH: f32 = LIST_WIDTH + 26.0;
/// Open the dialog with `params` (`document.exportPdf` options and `path?`) applied over their
/// preset.
/// preset. `useArtboards: false` makes the page the bounds of the visible art.
pub fn open(app: &mut VectorcraftApp, params: &Value) -> Result<Value, String> {
let art_bounds = match params.get("useArtboards") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => !b,
Some(v) => return Err(format!("useArtboards must be true or false, not {v}")),
};
let mut fields = settings_fields(app, params)?;
let s = |k: &str| params.get(k).and_then(Value::as_str);
fields.insert("preset".into(), json!(s("preset").unwrap_or(pdf::DEFAULT_PRESET)));
@@ -88,6 +98,9 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Result<Value, String> {
if let Some(path) = s("path") {
fields.insert("path".into(), json!(path));
}
if art_bounds {
fields.insert(ART_BOUNDS.into(), json!(true));
}
app.ui.dialog = Some(Dialog { kind: KIND.into(), fields });
Ok(Value::Null)
}
@@ -117,10 +130,14 @@ fn settings_fields(app: &VectorcraftApp, params: &Value) -> Result<Map<String, V
/// The `document.exportPdf` params the dialog stands for.
fn params(d: &Dialog) -> Value {
let mut p = form::params(d);
if (d.bool("__allArtboards") || d.str("range").trim().is_empty())
&& let Some(o) = p.as_object_mut()
{
o.remove("range");
let art = d.bool(ART_BOUNDS);
if let Some(o) = p.as_object_mut() {
if art || d.bool("__allArtboards") || d.str("range").trim().is_empty() {
o.remove("range");
}
if art {
o.insert("useArtboards".into(), json!(false));
}
}
p
}
@@ -137,14 +154,24 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
}
let r = match SaveMode::of(&d.str("__save")) {
Some(mode) => io::save_pdf(app, mode, params(d)),
None if d.bool(ART_BOUNDS) => export_art(app, params(d)),
None => io::export_pdf(app, params(d)),
};
if r.is_ok() {
// A question the write asked (replace the file the document was opened from?) stays open.
if r.is_ok() && app.ui.dialog.as_ref().is_some_and(|o| o.kind == KIND) {
app.ui.dialog = None;
}
r
}
/// A page of the art's bounds (Export As with Use Artboards off): written as Export As writes
/// other formats ([`io::export`]), with the dialog's options and a saved preset written out.
fn export_art(app: &mut VectorcraftApp, mut p: Value) -> Result<Value, String> {
let path = p.as_object_mut().and_then(|o| o.remove("path")).and_then(|v| v.as_str().map(str::to_string));
let p = pdf::expand_preset(&app.session, "file.exportAs", &p).map_err(|e| e.to_string())?.into_owned();
io::export(app, Some("pdf"), path, &p)
}
/// The settings as `pdf.preset.save` params (without the artboards and path).
fn preset_params(d: &Dialog) -> Value {
let mut p = form::params(d);
@@ -490,6 +517,10 @@ fn general(ui: &mut egui::Ui, d: &mut Dialog, editor: bool) {
}
return;
}
// A page of the art's bounds has no artboards to choose.
if d.bool(ART_BOUNDS) {
return;
}
heading(ui, tl!("Artboards"));
let mut all = d.bool("__allArtboards");
ui.horizontal(|ui| {
@@ -92,6 +92,112 @@ fn confirm_runs_export_pdf_with_the_dialog_options() {
assert!(app.ui.status.starts_with("Saved /tmp/out.pdf"), "{}", app.ui.status);
}
/// Opened for a page of the art's bounds (Export As with Use Artboards off), the dialog has no
/// Artboards section, and OK writes one page of the art's bounds with its options, a saved preset
/// and View PDF after Saving included.
#[test]
fn a_page_of_the_arts_bounds_has_no_artboards_section_and_takes_the_options() {
let (mut app, written, opened) = app();
app.run("pdf.preset.save", json!({"name": "Mine", "compatibility": "1.5"})).unwrap();
let ctx = egui::Context::default();
ctx.enable_accesskit();
theme::install_fonts(&ctx);
let has_range = |app: &mut VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx()));
out.textures_delta.clear();
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
nodes.iter().any(|(_, n)| n.label() == Some("Range:") && n.role() == egui::accesskit::Role::RadioButton)
};
app.run("ui.savePdfDialog", json!({"path": "/tmp/artboards.pdf"})).unwrap();
has_range(&mut app);
assert!(has_range(&mut app), "the artboards' dialog has the section");
app.run("ui.savePdfDialog", json!({"path": "/tmp/art.pdf", "preset": "Mine", "useArtboards": false})).unwrap();
assert!(app.ui.dialog.as_ref().unwrap().bool(ART_BOUNDS));
has_range(&mut app);
assert!(!has_range(&mut app), "no artboards to choose");
set_field(&mut app, "viewAfterSaving", json!(true));
let r = super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none(), "closes after saving");
assert_eq!(r["path"], "/tmp/art.pdf");
let w = written.borrow();
assert_eq!(w.len(), 1);
assert!(w[0].1.starts_with(b"%PDF-1.5"), "the saved preset reaches the writer");
let pdf = vectorcraft_pdf::import(&w[0].1).unwrap();
assert_eq!(pdf.artboards.len(), 1);
let size = pdf.artboards[0].rect.size();
assert!((50.0..52.0).contains(&size.width) && (40.0..42.0).contains(&size.height), "the rectangle's bounds with its stroke: {size:?}");
assert_eq!(opened.borrow().len(), 1, "View PDF after Saving opens the file");
assert!(opened.borrow()[0].0.ends_with("/tmp/art.pdf"));
}
/// `useArtboards` other than true, false or null is refused, as `document.exportPdf` refuses it,
/// and no dialog opens.
#[test]
fn a_use_artboards_that_is_not_true_or_false_is_refused() {
let (mut app, _, _) = app();
for bad in [json!("false"), json!(0), json!({})] {
let e = app.run("ui.savePdfDialog", json!({"path": "/tmp/x.pdf", "useArtboards": bad})).unwrap_err();
assert!(e.contains("useArtboards must be true or false"), "{bad}: {e}");
assert!(app.ui.dialog.is_none(), "{bad}: no dialog opens");
}
for ok in [json!(true), json!(null)] {
app.run("ui.savePdfDialog", json!({"path": "/tmp/x.pdf", "useArtboards": ok})).unwrap();
assert!(!app.ui.dialog.take().unwrap().bool(ART_BOUNDS), "{ok}: the artboards' dialog");
}
}
/// With Background Export on, a page of the art's bounds is written in the background, as Export
/// As writes its other formats.
#[test]
fn a_page_of_the_arts_bounds_is_written_in_the_background() {
let written = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(String, Vec<u8>)>::new()));
let w = written.clone();
let services = Services {
write_shared: Some(std::sync::Arc::new(move |p: &str, b: &[u8]| {
w.lock().unwrap().push((p.to_string(), b.to_vec()));
Ok(())
})),
..Default::default()
};
let mut app = VectorcraftApp::new(Session::new(), services);
app.session.prefs.background_export = true;
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
app.run("ui.savePdfDialog", json!({"path": "/tmp/bg.pdf", "useArtboards": false})).unwrap();
let r = super::super::confirm(&mut app).unwrap();
assert_eq!(r["background"], true, "{r}");
assert!(app.ui.dialog.is_none());
crate::background::wait_all(&mut app);
let w = written.lock().unwrap();
assert_eq!(w.len(), 1);
assert_eq!(w[0].0, "/tmp/bg.pdf");
assert_eq!(vectorcraft_pdf::import(&w[0].1).unwrap().artboards.len(), 1);
}
/// A document without a title of its own, saved to a file, is titled after that file in the PDF,
/// and viewers show the file name, with or without Use Artboards; one with its own title shows
/// that title.
#[test]
fn a_page_of_the_arts_bounds_shows_the_title_only_when_it_is_the_documents_own() {
let (mut app, written, _) = app();
app.session.doc_mut().unwrap().path = Some("/docs/Poster.vectorcraft".into());
for artboards in [true, false] {
app.run("ui.savePdfDialog", json!({"path": "/tmp/t.pdf", "useArtboards": artboards, "compression": {"compressText": false}})).unwrap();
super::super::confirm(&mut app).unwrap();
}
std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc).title = "Spring Sale".into();
app.run("ui.savePdfDialog", json!({"path": "/tmp/t.pdf", "useArtboards": false, "compression": {"compressText": false}})).unwrap();
super::super::confirm(&mut app).unwrap();
let w = written.borrow();
assert_eq!(w.len(), 3);
let texts: Vec<String> = w.iter().map(|(_, b)| String::from_utf8_lossy(b).into_owned()).collect();
for (pdf, artboards) in texts[..2].iter().zip([true, false]) {
assert!(pdf.contains("/Title(Poster)"), "useArtboards {artboards}");
assert!(!pdf.contains("/DisplayDocTitle true"), "useArtboards {artboards}");
}
assert!(texts[2].contains("/Title(Spring Sale)") && texts[2].contains("/DisplayDocTitle true"));
}
#[test]
fn warnings_reach_the_status_and_errors_keep_the_dialog_open() {
let (mut app, written, opened) = app();
+39 -7
View File
@@ -190,7 +190,7 @@ fn an_empty_export_as_range_shows_an_example() {
}
#[test]
fn svg_continues_in_svg_options_and_pdf_art_is_written_directly() {
fn svg_continues_in_svg_options() {
let (mut app, written) = app(2);
app.run("file.exportAs", json!({"format": "svg", "useArtboards": true})).unwrap();
confirm(&mut app).unwrap();
@@ -201,12 +201,35 @@ fn svg_continues_in_svg_options_and_pdf_art_is_written_directly() {
confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(names(&written), ["/out/Untitled-1-Artboard-1.svg", "/out/Untitled-1-Artboard-2.svg"]);
// Without artboards: one file of the art's bounds, with no options dialog for a PDF.
}
/// Without Use Artboards, a PDF continues in Save PDF too, without its artboard choice, and the
/// file is one page of the art's bounds. Its options apply: a drawing 10 m long is written at
/// full size in points with "Write pages longer than 200 in at full size in points".
#[test]
fn pdf_art_continues_in_the_save_pdf_dialog() {
let (mut app, written) = app(2);
app.run("file.exportAs", json!({"format": "pdf"})).unwrap();
let r = confirm(&mut app).unwrap();
assert_eq!(r["path"], "/out/Untitled-1.pdf");
let pdf = vectorcraft_pdf::import(&written.borrow()[2].1).unwrap();
confirm(&mut app).unwrap();
assert_eq!(kind(&app), Some("savePdf"), "the PDF options follow");
assert_eq!(app.ui.dialog.as_ref().unwrap().str("path"), "/out/Untitled-1.pdf");
assert!(written.borrow().is_empty());
frame(&mut app);
assert_eq!(confirm(&mut app).unwrap()["path"], "/out/Untitled-1.pdf");
let pdf = vectorcraft_pdf::import(&written.borrow()[0].1).unwrap();
assert_eq!(pdf.artboards.len(), 1);
assert_eq!((pdf.artboards[0].rect.width().round(), pdf.artboards[0].rect.height().round()), (30.0, 20.0), "the ellipse's bounds");
app.run("shape.rectangle", json!({"x": 0, "y": 100, "width": 28_346.46, "height": 50})).unwrap();
app.run("file.exportAs", json!({"format": "pdf"})).unwrap();
confirm(&mut app).unwrap();
set(&mut app, "longPagesInPoints", json!(true));
frame(&mut app);
confirm(&mut app).unwrap();
let bytes = written.borrow()[1].1.clone();
assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit"));
let width = vectorcraft_pdf::import(&bytes).unwrap().artboards[0].rect.width();
assert!((28_346.0..28_350.0).contains(&width), "{width}");
}
#[test]
@@ -330,8 +353,17 @@ fn the_enter_that_closed_the_save_panel_does_not_confirm_the_options() {
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui.ctx()));
out.textures_delta.clear();
};
// Each format whose options follow the panel (PDF's with Use Artboards: Save PDF).
let formats = [("png", false), ("svg", false), ("pdf", true), ("txt", false), ("dxf", false), ("eps", false), ("plugin.test.ui.held", false)];
// Each format whose options follow the panel (PDF's: Save PDF, with Use Artboards on or off).
let formats = [
("png", false),
("svg", false),
("pdf", true),
("pdf", false),
("txt", false),
("dxf", false),
("eps", false),
("plugin.test.ui.held", false),
];
for (format, artboards) in formats {
let (mut app, written) = app(1);
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
+5
View File
@@ -2543,6 +2543,8 @@ font-technology Variable Променливи
Proof Setup Настройка на пробен печат
Properties Свойства
Proportional Metrics Пропорционални метрики
Insert Aki Left Вмъкване на аки отляво
Insert Aki Right Вмъкване на аки отдясно
Character Direction Посока на знаците
Digits Цифри
Arabic Арабски
@@ -2815,6 +2817,8 @@ digits Malayalam Малаялам
Reset Rotate View Нулиране на изгледа на завъртане
Rotate View to Selection Завъртане на изгледа спрямо селекцията
Reset the rows to the artwork's colors Нулиране на редовете към цветовете на илюстрацията
Color Theme Picker Избор на цветова тема
Click or drag across the art to pick its colors; Shift adds more Щракнете или плъзнете през илюстрацията, за да вземете цветовете ѝ; Shift добавя още
Reset to Default Връщане към стандартните
Reset to White, Black Нулиране към бяло, черно
Reset with Mesh Нулиране с мрежа
@@ -3210,6 +3214,7 @@ digits Malayalam Малаялам
Show Note Показване на бележка
Show Options Показване на опциите
Show Recent Colors Показване на скорошните цветове
Toggle RGB Percent Превключване на RGB в проценти
Show Original Path Показване на оригиналния път
Open this dialog with these settings next time Отваряне на този прозорец с тези настройки следващия път
Auto-Simplify Автоматично опростяване
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -1558,6 +1558,8 @@ lighting Light Svjetlo
Leading Prored
No Break Bez preloma
Proportional Metrics Proporcionalna metrika
Insert Aki Left Umetni aki lijevo
Insert Aki Right Umetni aki desno
Character Direction Smjer znakova
Digits Cifre
Arabic Arapski
@@ -1577,6 +1579,7 @@ digits Malayalam Malajalam
Select a text object to edit its character attributes. Odaberite tekstualni objekat da uredite njegove atribute znakova.
Show Options Prikaži opcije
Show Recent Colors Prikaži nedavne boje
Toggle RGB Percent Uključi/isključi RGB u postocima
Color Panel Options Opcije panela boja
Small Caps Mala velika slova
Small Caps (on the roadmap) Mala velika slova (u planu)
@@ -2838,6 +2841,8 @@ digits Malayalam Malajalam
Randomly change saturation and brightness Nasumično promijeni zasićenje i svjetlinu
Recolor this row Ponovo oboji ovaj red
Reset the rows to the artwork's colors Vrati redove na boje crteža
Color Theme Picker Birač teme boja
Click or drag across the art to pick its colors; Shift adds more Kliknite ili prevucite preko crteža da uzmete njegove boje; Shift dodaje još
Separate colors into rows Razdvoji boje u redove
Unlink harmony colors Prekini vezu boja harmonije
1 Color Job Posao s 1 bojom
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -3305,6 +3305,8 @@ digits Malayalam Malaiàlam
Proof Setup Configuració de prova
Properties Propietats
Proportional Metrics Mètriques proporcionals
Insert Aki Left Insereix aki a l'esquerra
Insert Aki Right Insereix aki a la dreta
Proportional Lining Xifres proporcionals alineades
Position: Posició:
Default Position Posició predeterminada
@@ -3597,6 +3599,8 @@ digits Malayalam Malaiàlam
Reset Rotate View Restableix la rotació de la vista
Reset Ruler Origin Restableix l’origen de les regles
Reset the rows to the artwork's colors Restableix les files als colors de l’obra
Color Theme Picker Selector de tema de colors
Click or drag across the art to pick its colors; Shift adds more Feu clic o arrossegueu sobre l’obra per agafar-ne els colors; Maj n’afegeix més
Reset to Default Restableix el valor predeterminat
Reset to default Restableix el valor predeterminat
Reset to Defaults Restableix els valors predeterminats
@@ -4173,6 +4177,7 @@ digits Malayalam Malaiàlam
Show Note Mostra la nota
Show Options Mostra les opcions
Show Recent Colors Mostra els colors recents
Toggle RGB Percent Commuta RGB en percentatge
Show Original Path Mostra el traçat original
Show Package Mostra el paquet
Show Panel Mostra el panell
@@ -5373,6 +5378,85 @@ digits Malayalam Malaiàlam
@msg the script's run is no longer available l'execució de l'script ja no està disponible
@msg a failed command changed undo steps that could not be put back, so the script was stopped una ordre fallida ha canviat passos de desfer que no s'han pogut restaurar, així que l'script s'ha aturat
@msg a recovery copy could not be written, so the script was not run no s'ha pogut escriure una còpia de recuperació, per tant l'script no s'ha executat
@msg Script file access denied S'ha denegat l'accés al fitxer de l'script
@msg Script file exceeds 8 MiB El fitxer de l'script supera els 8 MiB
@msg Script file is not open El fitxer de l'script no està obert
@msg Script file cannot be decoded No es pot descodificar el fitxer de l'script
@msg Script file is not a regular file El fitxer de l'script no és un fitxer normal
@msg Script file does not exist El fitxer de l'script no existeix
@msg Script file could not be read No s'ha pogut llegir el fitxer de l'script
@msg Script folder has more than 2,048 entries La carpeta de l'script té més de 2.048 entrades
@msg Script file open mode must be r, w, e or a El mode d'obertura del fitxer de l'script ha de ser r, w, e o a
@msg Script file writing is not available L'escriptura de fitxers de l'script no està disponible
@msg Script file dialogs are not available Els quadres de diàleg de fitxers de l'script no estan disponibles
@msg Script files cannot be opened in another application Els fitxers de l'script no es poden obrir en una altra aplicació
@msg Script file access is unavailable on the web L'accés als fitxers de l'script no està disponible al web
@msg Script has 256 files open L'script té 256 fitxers oberts
@msg Script file path exceeds 32,767 characters El camí del fitxer de l'script supera els 32.767 caràcters
@msg Script folder mask takes too many steps to match La màscara de carpeta de l'script requereix massa passos per coincidir
@msg the script opened more file data than one run may open (32 MiB) l'script ha obert més dades de fitxer de les que pot obrir una execució (32 MiB)
@msg File.seek: takes a position and a mode File.seek: rep una posició i un mode
@msg vc.run: give a command id, as a string vc.run: indiqueu un id d'ordre, com a cadena
@msg vc.run: takes a command id and an object of parameters vc.run: rep un id d'ordre i un objecte de paràmetres
@msg vc.run: the parameters must be an object vc.run: els paràmetres han de ser un objecte
@msg vc.run: the result{place} is too large for a script vc.run: el resultat{place} és massa gran per a un script
@msg $.evalFile requires a file path $.evalFile requereix un camí de fitxer
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: el temps d'espera ha de ser un nombre finit de mil·lisegons, 0 o més
@msg $.evalFile: takes a file path and a timeout $.evalFile: rep un camí de fitxer i un temps d'espera
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: línia {line}, columna {column} de {file}: {e} (llançat)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: línia {line}, columna {column}: {e} (llançat)
@msg {name}: {e} (thrown) {name}: {e} (llançat)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: línia {line}, columna {column} de {file}: {e} (límit)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: línia {line}, columna {column}: {e} (límit)
@msg {name}: {e} (limit) {name}: {e} (límit)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: línia {line}, columna {column} de {file}: {e} (error de sintaxi)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: línia {line}, columna {column}: {e} (error de sintaxi)
@msg {name}: {e} (syntax) {name}: {e} (error de sintaxi)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: línia {line}, columna {column} de {file}: {e} (aturat)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: línia {line}, columna {column}: {e} (aturat)
@msg {name}: {e} (stopped) {name}: {e} (aturat)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: línia {line}, columna {column} de {file}: {e} (error intern)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: línia {line}, columna {column}: {e} (error intern)
@msg {name}: {e} (internal) {name}: {e} (error intern)
@msg {e} (these files stay written: {paths}) {e} (aquests fitxers continuen escrits: {paths})
@msg $.{name}: give a name, as a string $.{name}: indiqueu un nom, com a cadena
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: indiqueu una configuració regional com "en" o "de_DE", o null per a la de la interfície
@msg $.localize: give true or false $.localize: indiqueu true o false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: només es pot establir 512, que activa la localització, o 0
@msg $.flags: give a number $.flags: indiqueu un nombre
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: aquí els scripts només llegeixen i escriuen UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: indiqueu el nom d'una codificació, com a cadena
@msg $.memCache: the memory cache size cannot be set $.memCache: no es pot establir la mida de la memòria cau
@msg $.setenv: give a value, as a string $.setenv: indiqueu un valor, com a cadena
@msg $.setenv: only {_1} can be set $.setenv: només es poden establir {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: un valor té com a màxim {MAX_ENV_BYTES} lletres, xifres i _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: indiqueu un nombre de mil·lisegons de 0 a {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: indiqueu un nombre de mil·lisegons
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: una execució no pot esperar dins d'una crida de retorn d'una funció integrada, un getter, una conversió o un fitxer que executa $.evalFile; crideu-la des del codi propi de l'script
@msg $.bp: scripts here have no debugger $.bp: aquí els scripts no tenen depurador
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: els scripts encara no poden mostrar un quadre de diàleg
@msg {name}: give a message {name}: indiqueu un missatge
@msg {name}: give the text the field starts with {name}: indiqueu el text amb què comença el camp
@msg {name}: the message is longer than 16 KiB {name}: el missatge ocupa més de 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: el títol ocupa més de 256 bytes
@msg {name}: the text the field starts with is longer than 16 KiB {name}: el text amb què comença el camp ocupa més de 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un quadre de diàleg no es pot obrir dins d'una crida de retorn d'una funció integrada, un getter, una conversió o un fitxer que executa $.evalFile; crideu-lo des del codi propi de l'script
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la resposta següent d'`answers` és per a {_1}, no per a {name}
@msg {name}: `answers` has no answer left for this dialog {name}: a `answers` no queden respostes per a aquest quadre de diàleg
@msg vc.document{place} is too large for a script vc.document{place} és massa gran per a un script
@msg vc.log: the log of this run is full vc.log: el registre d'aquesta execució és ple
@msg this function's script run has ended l'execució de l'script d'aquesta funció ha acabat
@msg the script made more host calls than one run may make l'script ha fet més crides a l'amfitrió de les que pot fer una execució
@msg the script passed more data to and from commands than one run may pass l'script ha passat més dades a les ordres i des de les ordres de les que pot passar una execució
@msg the script added more objects and data to the documents than one run may add l'script ha afegit als documents més objectes i dades dels que pot afegir una execució
@msg {what}: the object is not a File or a Folder {what}: l'objecte no és un File ni un Folder
@msg {what}: the count must be a finite number, 0 or more {what}: el recompte ha de ser un nombre finit, 0 o més
@msg File.seek: the position must be a finite number File.seek: la posició ha de ser un nombre finit
@msg File.seek: the mode must be 0, 1 or 2 File.seek: el mode ha de ser 0, 1 o 2
@msg script file is compiled: {value} el fitxer de l'script està compilat: {value}
@msg `name` must be the name of a script engine `name` ha de ser el nom d'un motor d'scripts
@msg the main script engine is new for each run and is never kept, so it cannot be dropped el motor d'scripts principal és nou a cada execució i no es conserva mai, per tant no es pot descartar
@msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name}
@msg Running a script S'està executant un script
@msg Copied the script report S’ha copiat l’informe de l’script
@msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4 -2
View File
@@ -77,13 +77,15 @@ impl Template {
}
/// Match `s` against `pieces`, a placeholder taking the shortest non-empty text that lets the
/// rest match (the last one takes what remains). With `counted`, `{n}` takes only a count.
/// rest match (the last one takes what remains). With `counted`, `{n}` takes only a count. A
/// placeholder that occurs twice takes the same text both times.
fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mut Vec<(&'p str, &'a str)>) -> bool {
let Some((first, rest)) = pieces.split_first() else { return s.is_empty() };
match first {
Piece::Text(t) => s.strip_prefix(t.as_str()).is_some_and(|tail| match_pieces(rest, tail, counted, out)),
Piece::Hole(name) => {
let fits = |value: &str| !(counted && name == "n") || value.parse::<u64>().is_ok();
let earlier = out.iter().find(|(n, _)| *n == name.as_str()).map(|&(_, v)| v);
let fits = |value: &str| (!(counted && name == "n") || value.parse::<u64>().is_ok()) && earlier.is_none_or(|e| e == value);
let Some((next, after)) = rest.split_first() else {
if s.is_empty() || !fits(s) {
return false;
+84
View File
@@ -1586,6 +1586,8 @@ lighting Light Světlo
Leading Proklad
No Break Nezalamovat
Proportional Metrics Proporcionální metrika
Insert Aki Left Vložit aki vlevo
Insert Aki Right Vložit aki vpravo
Character Direction Směr znaků
Digits Číslice
Arabic Arabské
@@ -1606,6 +1608,7 @@ digits Malayalam Malajálamské
Select a text object to edit its character attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho znaků.
Show Options Zobrazit možnosti
Show Recent Colors Zobrazit nedávné barvy
Toggle RGB Percent Přepnout RGB v procentech
Color Panel Options Možnosti panelu Barva
Small Caps Kapitálky
Small Caps (on the roadmap) Kapitálky (v plánu)
@@ -2874,6 +2877,8 @@ digits Malayalam Malajálamské
Randomly change saturation and brightness Náhodně změnit sytost a jas
Recolor this row Přebarvit tento řádek
Reset the rows to the artwork's colors Obnovit řádky na barvy kresby
Color Theme Picker Výběr barevného motivu
Click or drag across the art to pick its colors; Shift adds more Klepnutím nebo tažením přes kresbu převezmete její barvy; Shift přidá další
Separate colors into rows Rozdělit barvy do řádků
Unlink harmony colors Zrušit propojení barev harmonie
1 Color Job Zakázka s 1 barvou
@@ -4521,6 +4526,85 @@ imageTrace Outline Obrys
@msg the script's run is no longer available běh skriptu již není k dispozici
@msg a failed command changed undo steps that could not be put back, so the script was stopped neúspěšný příkaz změnil kroky zpět, které nebylo možné obnovit, proto byl skript zastaven
@msg a recovery copy could not be written, so the script was not run záložní kopii se nepodařilo zapsat, proto skript nebyl spuštěn
@msg Script file access denied Přístup k souboru skriptu byl odepřen
@msg Script file exceeds 8 MiB Soubor skriptu je větší než 8 MiB
@msg Script file is not open Soubor skriptu není otevřen
@msg Script file cannot be decoded Soubor skriptu nelze dekódovat
@msg Script file is not a regular file Soubor skriptu není běžný soubor
@msg Script file does not exist Soubor skriptu neexistuje
@msg Script file could not be read Soubor skriptu se nepodařilo přečíst
@msg Script folder has more than 2,048 entries Složka skriptu má více než 2 048 položek
@msg Script file open mode must be r, w, e or a Režim otevření souboru skriptu musí být r, w, e nebo a
@msg Script file writing is not available Zápis souborů skriptu není k dispozici
@msg Script file dialogs are not available Dialogy souborů skriptu nejsou k dispozici
@msg Script files cannot be opened in another application Soubory skriptu nelze otevřít v jiné aplikaci
@msg Script file access is unavailable on the web Přístup k souborům skriptu není na webu k dispozici
@msg Script has 256 files open Skript má otevřeno 256 souborů
@msg Script file path exceeds 32,767 characters Cesta k souboru skriptu je delší než 32 767 znaků
@msg Script folder mask takes too many steps to match Porovnání masky složky skriptu vyžaduje příliš mnoho kroků
@msg the script opened more file data than one run may open (32 MiB) skript otevřel více dat ze souborů, než smí otevřít jeden běh (32 MiB)
@msg File.seek: takes a position and a mode File.seek: přijímá pozici a režim
@msg vc.run: give a command id, as a string vc.run: zadejte ID příkazu jako řetězec
@msg vc.run: takes a command id and an object of parameters vc.run: přijímá ID příkazu a objekt s parametry
@msg vc.run: the parameters must be an object vc.run: parametry musí být objekt
@msg vc.run: the result{place} is too large for a script vc.run: výsledek{place} je pro skript příliš velký
@msg $.evalFile requires a file path $.evalFile vyžaduje cestu k souboru
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: časový limit musí být konečný počet milisekund, 0 nebo více
@msg $.evalFile: takes a file path and a timeout $.evalFile: přijímá cestu k souboru a časový limit
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: řádek {line}, sloupec {column} v {file}: {e} (vyvolána výjimka)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: řádek {line}, sloupec {column}: {e} (vyvolána výjimka)
@msg {name}: {e} (thrown) {name}: {e} (vyvolána výjimka)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: řádek {line}, sloupec {column} v {file}: {e} (omezení)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: řádek {line}, sloupec {column}: {e} (omezení)
@msg {name}: {e} (limit) {name}: {e} (omezení)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: řádek {line}, sloupec {column} v {file}: {e} (syntaktická chyba)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: řádek {line}, sloupec {column}: {e} (syntaktická chyba)
@msg {name}: {e} (syntax) {name}: {e} (syntaktická chyba)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: řádek {line}, sloupec {column} v {file}: {e} (zastaveno)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: řádek {line}, sloupec {column}: {e} (zastaveno)
@msg {name}: {e} (stopped) {name}: {e} (zastaveno)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: řádek {line}, sloupec {column} v {file}: {e} (interní chyba)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: řádek {line}, sloupec {column}: {e} (interní chyba)
@msg {name}: {e} (internal) {name}: {e} (interní chyba)
@msg {e} (these files stay written: {paths}) {e} (tyto soubory zůstávají zapsané: {paths})
@msg $.{name}: give a name, as a string $.{name}: zadejte název jako řetězec
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: zadejte národní prostředí, například "en" nebo "de_DE", nebo null pro prostředí rozhraní
@msg $.localize: give true or false $.localize: zadejte true nebo false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: lze nastavit jen 512, které zapíná lokalizaci, nebo 0
@msg $.flags: give a number $.flags: zadejte číslo
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: skripty zde čtou a zapisují pouze UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: zadejte název kódování jako řetězec
@msg $.memCache: the memory cache size cannot be set $.memCache: velikost mezipaměti nelze nastavit
@msg $.setenv: give a value, as a string $.setenv: zadejte hodnotu jako řetězec
@msg $.setenv: only {_1} can be set $.setenv: lze nastavit pouze {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: hodnota má nejvýše {MAX_ENV_BYTES} písmen, číslic a znaků _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: zadejte počet milisekund od 0 do {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: zadejte počet milisekund
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: běh nemůže čekat uvnitř zpětného volání vestavěné funkce, getteru, převodu ani souboru, který spouští $.evalFile; zavolejte jej z vlastního kódu skriptu
@msg $.bp: scripts here have no debugger $.bp: skripty zde nemají ladicí program
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: skripty zatím nemohou zobrazit dialog
@msg {name}: give a message {name}: zadejte zprávu
@msg {name}: give the text the field starts with {name}: zadejte text, kterým pole začíná
@msg {name}: the message is longer than 16 KiB {name}: zpráva je delší než 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: titulek je delší než 256 bajtů
@msg {name}: the text the field starts with is longer than 16 KiB {name}: text, kterým pole začíná, je delší než 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dialog se nemůže otevřít uvnitř zpětného volání vestavěné funkce, getteru, převodu ani souboru, který spouští $.evalFile; zavolejte jej z vlastního kódu skriptu
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: další odpověď v `answers` je pro {_1}, ne pro {name}
@msg {name}: `answers` has no answer left for this dialog {name}: `answers` už nemá pro tento dialog žádnou odpověď
@msg vc.document{place} is too large for a script vc.document{place} je pro skript příliš velký
@msg vc.log: the log of this run is full vc.log: protokol tohoto běhu je plný
@msg this function's script run has ended běh skriptu této funkce skončil
@msg the script made more host calls than one run may make skript provedl více volání hostitele, než smí provést jeden běh
@msg the script passed more data to and from commands than one run may pass skript předal příkazům a z příkazů více dat, než smí předat jeden běh
@msg the script added more objects and data to the documents than one run may add skript přidal do dokumentů více objektů a dat, než smí přidat jeden běh
@msg {what}: the object is not a File or a Folder {what}: objekt není File ani Folder
@msg {what}: the count must be a finite number, 0 or more {what}: počet musí být konečné číslo, 0 nebo více
@msg File.seek: the position must be a finite number File.seek: pozice musí být konečné číslo
@msg File.seek: the mode must be 0, 1 or 2 File.seek: režim musí být 0, 1 nebo 2
@msg script file is compiled: {value} soubor skriptu je zkompilovaný: {value}
@msg `name` must be the name of a script engine `name` musí být název skriptovacího jádra
@msg the main script engine is new for each run and is never kept, so it cannot be dropped hlavní skriptovací jádro je pro každý běh nové a nikdy se neuchovává, proto je nelze zahodit
@msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje
@msg Running a script Běží skript
@msg Copied the script report Zpráva o skriptu zkopírována
@msg Corners edits the corners of a path Rohy upravuje rohy cesty
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -1494,6 +1494,8 @@ lighting Light Lys
Leading Linjeafstand
No Break Ingen ombrydning
Proportional Metrics Proportionale metrikker
Insert Aki Left Indsæt aki til venstre
Insert Aki Right Indsæt aki til højre
Character Direction Tegnretning
Digits Cifre
Arabic Arabisk
@@ -1513,6 +1515,7 @@ digits Malayalam Malayalam
Select a text object to edit its character attributes. Markér et tekstobjekt for at redigere dets tegnattributter.
Show Options Vis indstillinger
Show Recent Colors Vis seneste farver
Toggle RGB Percent Skift RGB i procent
Small Caps Kapitæler
Small Caps (on the roadmap) Kapitæler (på vejkortet)
Standard Vertical Roman Alignment Standard lodret romersk justering
@@ -2658,6 +2661,8 @@ digits Malayalam Malayalam
Randomly change saturation and brightness Ændr mætning og lysstyrke tilfældigt
Recolor this row Omfarv denne række
Reset the rows to the artwork's colors Nulstil rækkerne til grafikkens farver
Color Theme Picker Farvetemavælger
Click or drag across the art to pick its colors; Shift adds more Klik eller træk hen over grafikken for at hente dens farver; Skift tilføjer flere
Separate colors into rows Opdel farver i rækker
Unlink harmony colors Fjern sammenkædning af harmonifarver
1 Color Job 1-farvejob
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -2587,6 +2587,8 @@ mark-style Japanese Japanisch
Proof Setup Proof einrichten
Properties Eigenschaften
Proportional Metrics Proportionale Metrik
Insert Aki Left Aki links einfügen
Insert Aki Right Aki rechts einfügen
Character Direction Zeichenrichtung
Digits Ziffern
Arabic Arabisch
@@ -2861,6 +2863,8 @@ digits Malayalam Malayalam
Reset Rotate View Ansichtsdrehung zurücksetzen
Rotate View to Selection Ansicht nach Auswahl drehen
Reset the rows to the artwork's colors Zeilen auf die Farben der Grafik zurücksetzen
Color Theme Picker Farbthema-Auswahl
Click or drag across the art to pick its colors; Shift adds more Klicken oder ziehen Sie über die Grafik, um ihre Farben aufzunehmen; Umschalt fügt weitere hinzu
Reset to Default Auf Standard zurücksetzen
Reset to White, Black Auf Weiß, Schwarz zurücksetzen
Reset with Mesh Mit Gitter zurücksetzen
@@ -3270,6 +3274,7 @@ digits Malayalam Malayalam
Show Note Notiz einblenden
Show Options Optionen einblenden
Show Recent Colors Zuletzt verwendete Farben einblenden
Toggle RGB Percent RGB in Prozent umschalten
Show Original Path Originalpfad einblenden
Open this dialog with these settings next time Dieses Dialogfeld nächstes Mal mit diesen Einstellungen öffnen
Auto-Simplify Automatisch vereinfachen
@@ -4135,6 +4140,85 @@ theme Appearance Erscheinungsbild
@msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar
@msg a failed command changed undo steps that could not be put back, so the script was stopped ein fehlgeschlagener Befehl hat Rückgängig-Schritte geändert, die nicht wiederhergestellt werden konnten, daher wurde das Skript angehalten
@msg a recovery copy could not be written, so the script was not run eine Wiederherstellungskopie konnte nicht geschrieben werden, daher wurde das Skript nicht ausgeführt
@msg Script file access denied Zugriff auf die Skriptdatei verweigert
@msg Script file exceeds 8 MiB Die Skriptdatei ist größer als 8 MiB
@msg Script file is not open Die Skriptdatei ist nicht geöffnet
@msg Script file cannot be decoded Die Skriptdatei kann nicht dekodiert werden
@msg Script file is not a regular file Die Skriptdatei ist keine reguläre Datei
@msg Script file does not exist Die Skriptdatei existiert nicht
@msg Script file could not be read Die Skriptdatei konnte nicht gelesen werden
@msg Script folder has more than 2,048 entries Der Skriptordner hat mehr als 2.048 Einträge
@msg Script file open mode must be r, w, e or a Der Öffnungsmodus der Skriptdatei muss r, w, e oder a sein
@msg Script file writing is not available Das Schreiben von Skriptdateien ist nicht verfügbar
@msg Script file dialogs are not available Dateidialoge für Skripte sind nicht verfügbar
@msg Script files cannot be opened in another application Skriptdateien können nicht in einer anderen Anwendung geöffnet werden
@msg Script file access is unavailable on the web Der Zugriff auf Skriptdateien ist im Web nicht verfügbar
@msg Script has 256 files open Das Skript hat 256 Dateien geöffnet
@msg Script file path exceeds 32,767 characters Der Pfad der Skriptdatei ist länger als 32.767 Zeichen
@msg Script folder mask takes too many steps to match Der Abgleich der Maske des Skriptordners braucht zu viele Schritte
@msg the script opened more file data than one run may open (32 MiB) das Skript hat mehr Dateidaten geöffnet, als ein Lauf öffnen darf (32 MiB)
@msg File.seek: takes a position and a mode File.seek: nimmt eine Position und einen Modus
@msg vc.run: give a command id, as a string vc.run: Geben Sie eine Befehls-ID als Zeichenfolge an
@msg vc.run: takes a command id and an object of parameters vc.run: nimmt eine Befehls-ID und ein Objekt mit Parametern
@msg vc.run: the parameters must be an object vc.run: Die Parameter müssen ein Objekt sein
@msg vc.run: the result{place} is too large for a script vc.run: Das Ergebnis{place} ist zu groß für ein Skript
@msg $.evalFile requires a file path $.evalFile erfordert einen Dateipfad
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: Die Zeitüberschreitung muss eine endliche Anzahl von Millisekunden sein, 0 oder mehr
@msg $.evalFile: takes a file path and a timeout $.evalFile: nimmt einen Dateipfad und eine Zeitüberschreitung
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: Zeile {line}, Spalte {column} in {file}: {e} (ausgelöst)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: Zeile {line}, Spalte {column}: {e} (ausgelöst)
@msg {name}: {e} (thrown) {name}: {e} (ausgelöst)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: Zeile {line}, Spalte {column} in {file}: {e} (Grenze)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: Zeile {line}, Spalte {column}: {e} (Grenze)
@msg {name}: {e} (limit) {name}: {e} (Grenze)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: Zeile {line}, Spalte {column} in {file}: {e} (Syntaxfehler)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: Zeile {line}, Spalte {column}: {e} (Syntaxfehler)
@msg {name}: {e} (syntax) {name}: {e} (Syntaxfehler)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: Zeile {line}, Spalte {column} in {file}: {e} (gestoppt)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: Zeile {line}, Spalte {column}: {e} (gestoppt)
@msg {name}: {e} (stopped) {name}: {e} (gestoppt)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: Zeile {line}, Spalte {column} in {file}: {e} (interner Fehler)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: Zeile {line}, Spalte {column}: {e} (interner Fehler)
@msg {name}: {e} (internal) {name}: {e} (interner Fehler)
@msg {e} (these files stay written: {paths}) {e} (diese Dateien bleiben geschrieben: {paths})
@msg $.{name}: give a name, as a string $.{name}: Geben Sie einen Namen als Zeichenfolge an
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: Geben Sie ein Gebietsschema wie "en" oder "de_DE" an, oder null für das der Oberfläche
@msg $.localize: give true or false $.localize: Geben Sie true oder false an
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: Nur 512, das die Lokalisierung einschaltet, oder 0 kann gesetzt werden
@msg $.flags: give a number $.flags: Geben Sie eine Zahl an
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: Skripte lesen und schreiben hier nur UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: Geben Sie den Namen einer Kodierung als Zeichenfolge an
@msg $.memCache: the memory cache size cannot be set $.memCache: Die Größe des Speichercaches kann nicht gesetzt werden
@msg $.setenv: give a value, as a string $.setenv: Geben Sie einen Wert als Zeichenfolge an
@msg $.setenv: only {_1} can be set $.setenv: Nur {_1} können gesetzt werden
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: Ein Wert hat höchstens {MAX_ENV_BYTES} Buchstaben, Ziffern und _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: Geben Sie eine Anzahl von Millisekunden von 0 bis {MAX_SLEEP_MS} an
@msg $.sleep: give a number of milliseconds $.sleep: Geben Sie eine Anzahl von Millisekunden an
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: Ein Lauf kann nicht in einem Callback einer integrierten Funktion, einem Getter, einer Umwandlung oder einer Datei warten, die $.evalFile ausführt; rufen Sie es aus dem eigenen Code des Skripts auf
@msg $.bp: scripts here have no debugger $.bp: Skripte haben hier keinen Debugger
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: Skripte können noch keinen Dialog anzeigen
@msg {name}: give a message {name}: Geben Sie eine Meldung an
@msg {name}: give the text the field starts with {name}: Geben Sie den Text an, mit dem das Feld beginnt
@msg {name}: the message is longer than 16 KiB {name}: Die Meldung ist länger als 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: Der Titel ist länger als 256 Byte
@msg {name}: the text the field starts with is longer than 16 KiB {name}: Der Text, mit dem das Feld beginnt, ist länger als 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: Ein Dialog kann sich nicht in einem Callback einer integrierten Funktion, einem Getter, einer Umwandlung oder einer Datei öffnen, die $.evalFile ausführt; rufen Sie ihn aus dem eigenen Code des Skripts auf
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: Die nächste Antwort in `answers` ist für {_1}, nicht für {name}
@msg {name}: `answers` has no answer left for this dialog {name}: `answers` hat keine Antwort mehr für diesen Dialog
@msg vc.document{place} is too large for a script vc.document{place} ist zu groß für ein Skript
@msg vc.log: the log of this run is full vc.log: Das Protokoll dieses Laufs ist voll
@msg this function's script run has ended der Skriptlauf dieser Funktion ist beendet
@msg the script made more host calls than one run may make das Skript hat mehr Host-Aufrufe ausgeführt, als ein Lauf ausführen darf
@msg the script passed more data to and from commands than one run may pass das Skript hat mehr Daten an Befehle und von Befehlen übergeben, als ein Lauf übergeben darf
@msg the script added more objects and data to the documents than one run may add das Skript hat den Dokumenten mehr Objekte und Daten hinzugefügt, als ein Lauf hinzufügen darf
@msg {what}: the object is not a File or a Folder {what}: Das Objekt ist weder ein File noch ein Folder
@msg {what}: the count must be a finite number, 0 or more {what}: Die Anzahl muss eine endliche Zahl sein, 0 oder mehr
@msg File.seek: the position must be a finite number File.seek: Die Position muss eine endliche Zahl sein
@msg File.seek: the mode must be 0, 1 or 2 File.seek: Der Modus muss 0, 1 oder 2 sein
@msg script file is compiled: {value} die Skriptdatei ist kompiliert: {value}
@msg `name` must be the name of a script engine `name` muss der Name einer Skript-Engine sein
@msg the main script engine is new for each run and is never kept, so it cannot be dropped die Hauptskript-Engine ist für jeden Lauf neu und wird nie behalten, daher kann sie nicht verworfen werden
@msg there is no script engine named {name} es gibt keine Skript-Engine namens {name}
@msg Running a script Skript wird ausgeführt
@msg Copied the script report Skriptbericht kopiert
@msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -2320,6 +2320,85 @@ axis Both Και τα δύο
@msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη
@msg a failed command changed undo steps that could not be put back, so the script was stopped μια εντολή που απέτυχε άλλαξε βήματα αναίρεσης που δεν ήταν δυνατό να επαναφερθούν, οπότε το σενάριο σταμάτησε
@msg a recovery copy could not be written, so the script was not run δεν ήταν δυνατή η εγγραφή αντιγράφου ανάκτησης, οπότε το σενάριο δεν εκτελέστηκε
@msg Script file access denied Η πρόσβαση στο αρχείο σεναρίου απορρίφθηκε
@msg Script file exceeds 8 MiB Το αρχείο σεναρίου υπερβαίνει τα 8 MiB
@msg Script file is not open Το αρχείο σεναρίου δεν είναι ανοιχτό
@msg Script file cannot be decoded Δεν είναι δυνατή η αποκωδικοποίηση του αρχείου σεναρίου
@msg Script file is not a regular file Το αρχείο σεναρίου δεν είναι κανονικό αρχείο
@msg Script file does not exist Το αρχείο σεναρίου δεν υπάρχει
@msg Script file could not be read Δεν ήταν δυνατή η ανάγνωση του αρχείου σεναρίου
@msg Script folder has more than 2,048 entries Ο φάκελος σεναρίου έχει περισσότερες από 2.048 καταχωρίσεις
@msg Script file open mode must be r, w, e or a Ο τρόπος ανοίγματος του αρχείου σεναρίου πρέπει να είναι r, w, e ή a
@msg Script file writing is not available Η εγγραφή αρχείων σεναρίου δεν είναι διαθέσιμη
@msg Script file dialogs are not available Τα παράθυρα διαλόγου αρχείων σεναρίου δεν είναι διαθέσιμα
@msg Script files cannot be opened in another application Τα αρχεία σεναρίου δεν μπορούν να ανοίξουν σε άλλη εφαρμογή
@msg Script file access is unavailable on the web Η πρόσβαση σε αρχεία σεναρίου δεν είναι διαθέσιμη στο web
@msg Script has 256 files open Το σενάριο έχει 256 ανοιχτά αρχεία
@msg Script file path exceeds 32,767 characters Η διαδρομή του αρχείου σεναρίου υπερβαίνει τους 32.767 χαρακτήρες
@msg Script folder mask takes too many steps to match Η αντιστοίχιση της μάσκας φακέλου σεναρίου χρειάζεται πάρα πολλά βήματα
@msg the script opened more file data than one run may open (32 MiB) το σενάριο άνοιξε περισσότερα δεδομένα αρχείων από όσα επιτρέπεται να ανοίξει μία εκτέλεση (32 MiB)
@msg File.seek: takes a position and a mode File.seek: δέχεται μια θέση και έναν τρόπο
@msg vc.run: give a command id, as a string vc.run: δώστε ένα αναγνωριστικό εντολής, ως συμβολοσειρά
@msg vc.run: takes a command id and an object of parameters vc.run: δέχεται ένα αναγνωριστικό εντολής και ένα αντικείμενο παραμέτρων
@msg vc.run: the parameters must be an object vc.run: οι παράμετροι πρέπει να είναι αντικείμενο
@msg vc.run: the result{place} is too large for a script vc.run: το αποτέλεσμα{place} είναι πολύ μεγάλο για σενάριο
@msg $.evalFile requires a file path Το $.evalFile απαιτεί διαδρομή αρχείου
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: το χρονικό όριο πρέπει να είναι πεπερασμένος αριθμός χιλιοστών του δευτερολέπτου, 0 ή περισσότερο
@msg $.evalFile: takes a file path and a timeout $.evalFile: δέχεται μια διαδρομή αρχείου και ένα χρονικό όριο
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: γραμμή {line}, στήλη {column} στο {file}: {e} (εξαίρεση)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: γραμμή {line}, στήλη {column}: {e} (εξαίρεση)
@msg {name}: {e} (thrown) {name}: {e} (εξαίρεση)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: γραμμή {line}, στήλη {column} στο {file}: {e} (όριο)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: γραμμή {line}, στήλη {column}: {e} (όριο)
@msg {name}: {e} (limit) {name}: {e} (όριο)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: γραμμή {line}, στήλη {column} στο {file}: {e} (συντακτικό σφάλμα)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: γραμμή {line}, στήλη {column}: {e} (συντακτικό σφάλμα)
@msg {name}: {e} (syntax) {name}: {e} (συντακτικό σφάλμα)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: γραμμή {line}, στήλη {column} στο {file}: {e} (διακόπηκε)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: γραμμή {line}, στήλη {column}: {e} (διακόπηκε)
@msg {name}: {e} (stopped) {name}: {e} (διακόπηκε)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: γραμμή {line}, στήλη {column} στο {file}: {e} (εσωτερικό σφάλμα)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: γραμμή {line}, στήλη {column}: {e} (εσωτερικό σφάλμα)
@msg {name}: {e} (internal) {name}: {e} (εσωτερικό σφάλμα)
@msg {e} (these files stay written: {paths}) {e} (αυτά τα αρχεία παραμένουν γραμμένα: {paths})
@msg $.{name}: give a name, as a string $.{name}: δώστε ένα όνομα, ως συμβολοσειρά
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: δώστε μια τοπική ρύθμιση όπως "en" ή "de_DE", ή null για αυτή της διεπαφής
@msg $.localize: give true or false $.localize: δώστε true ή false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: μπορεί να οριστεί μόνο το 512, που ενεργοποιεί την τοπικοποίηση, ή το 0
@msg $.flags: give a number $.flags: δώστε έναν αριθμό
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: τα σενάρια εδώ διαβάζουν και γράφουν μόνο UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: δώστε το όνομα μιας κωδικοποίησης, ως συμβολοσειρά
@msg $.memCache: the memory cache size cannot be set $.memCache: το μέγεθος της κρυφής μνήμης δεν μπορεί να οριστεί
@msg $.setenv: give a value, as a string $.setenv: δώστε μια τιμή, ως συμβολοσειρά
@msg $.setenv: only {_1} can be set $.setenv: μπορούν να οριστούν μόνο τα {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: μια τιμή έχει το πολύ {MAX_ENV_BYTES} γράμματα, ψηφία και _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: δώστε έναν αριθμό χιλιοστών του δευτερολέπτου από 0 έως {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: δώστε έναν αριθμό χιλιοστών του δευτερολέπτου
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: μια εκτέλεση δεν μπορεί να περιμένει μέσα σε επανάκληση ενσωματωμένης συνάρτησης, getter, μετατροπή ή αρχείο που εκτελεί το $.evalFile· καλέστε το από τον κώδικα του ίδιου του σεναρίου
@msg $.bp: scripts here have no debugger $.bp: τα σενάρια εδώ δεν έχουν πρόγραμμα εντοπισμού σφαλμάτων
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: τα σενάρια δεν μπορούν ακόμη να εμφανίσουν παράθυρο διαλόγου
@msg {name}: give a message {name}: δώστε ένα μήνυμα
@msg {name}: give the text the field starts with {name}: δώστε το κείμενο με το οποίο ξεκινά το πεδίο
@msg {name}: the message is longer than 16 KiB {name}: το μήνυμα είναι μεγαλύτερο από 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: ο τίτλος είναι μεγαλύτερος από 256 byte
@msg {name}: the text the field starts with is longer than 16 KiB {name}: το κείμενο με το οποίο ξεκινά το πεδίο είναι μεγαλύτερο από 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ένα παράθυρο διαλόγου δεν μπορεί να ανοίξει μέσα σε επανάκληση ενσωματωμένης συνάρτησης, getter, μετατροπή ή αρχείο που εκτελεί το $.evalFile· καλέστε το από τον κώδικα του ίδιου του σεναρίου
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: η επόμενη απάντηση στο `answers` είναι για το {_1}, όχι για το {name}
@msg {name}: `answers` has no answer left for this dialog {name}: το `answers` δεν έχει άλλη απάντηση για αυτό το παράθυρο διαλόγου
@msg vc.document{place} is too large for a script το vc.document{place} είναι πολύ μεγάλο για σενάριο
@msg vc.log: the log of this run is full vc.log: το αρχείο καταγραφής αυτής της εκτέλεσης είναι γεμάτο
@msg this function's script run has ended η εκτέλεση σεναρίου αυτής της συνάρτησης έχει τελειώσει
@msg the script made more host calls than one run may make το σενάριο έκανε περισσότερες κλήσεις στον κεντρικό υπολογιστή από όσες επιτρέπονται σε μία εκτέλεση
@msg the script passed more data to and from commands than one run may pass το σενάριο μετέφερε περισσότερα δεδομένα προς και από εντολές από όσα επιτρέπονται σε μία εκτέλεση
@msg the script added more objects and data to the documents than one run may add το σενάριο πρόσθεσε στα έγγραφα περισσότερα αντικείμενα και δεδομένα από όσα επιτρέπονται σε μία εκτέλεση
@msg {what}: the object is not a File or a Folder {what}: το αντικείμενο δεν είναι File ούτε Folder
@msg {what}: the count must be a finite number, 0 or more {what}: το πλήθος πρέπει να είναι πεπερασμένος αριθμός, 0 ή περισσότερο
@msg File.seek: the position must be a finite number File.seek: η θέση πρέπει να είναι πεπερασμένος αριθμός
@msg File.seek: the mode must be 0, 1 or 2 File.seek: ο τρόπος πρέπει να είναι 0, 1 ή 2
@msg script file is compiled: {value} το αρχείο σεναρίου είναι μεταγλωττισμένο: {value}
@msg `name` must be the name of a script engine το `name` πρέπει να είναι το όνομα μιας μηχανής σεναρίων
@msg the main script engine is new for each run and is never kept, so it cannot be dropped η κύρια μηχανή σεναρίων είναι νέα σε κάθε εκτέλεση και δεν διατηρείται ποτέ, οπότε δεν μπορεί να απορριφθεί
@msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name}
@msg Running a script Εκτελείται σενάριο
@msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε
@msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής
@@ -3285,6 +3364,8 @@ theme Appearance Εμφάνιση
Profile inclusion: Συμπερίληψη προφίλ:
Projecting Cap Προεξέχον άκρο
Proportional Metrics Αναλογικές μετρικές
Insert Aki Left Εισαγωγή aki αριστερά
Insert Aki Right Εισαγωγή aki δεξιά
Arabic Αραβικά
Hindi Χίντι
Farsi Περσικά
@@ -3500,6 +3581,8 @@ digits Malayalam Μαλαγιάλαμ
Reset Rotate View Επαναφορά περιστροφής προβολής
Rotate View to Selection Περιστροφή προβολής ως προς την επιλογή
Reset the rows to the artwork's colors Επαναφορά γραμμών στα χρώματα του σχεδίου
Color Theme Picker Επιλογέας χρωματικού θέματος
Click or drag across the art to pick its colors; Shift adds more Κάντε κλικ ή σύρετε πάνω στο σχέδιο για να πάρετε τα χρώματά του· το Shift προσθέτει κι άλλα
Reset to White, Black Επαναφορά σε λευκό και μαύρο
Reset with Mesh Επαναφορά με πλέγμα
Reset with Mesh… Επαναφορά με πλέγμα…
@@ -3764,6 +3847,7 @@ digits Malayalam Μαλαγιάλαμ
Show Note Εμφάνιση σημείωσης
Show Options Εμφάνιση επιλογών
Show Recent Colors Εμφάνιση πρόσφατων χρωμάτων
Toggle RGB Percent Εναλλαγή RGB σε ποσοστό
Show Original Path Εμφάνιση αρχικής διαδρομής
Open this dialog with these settings next time Άνοιγμα αυτού του παραθύρου με αυτές τις ρυθμίσεις την επόμενη φορά
Auto-Simplify Αυτόματη απλοποίηση
Can't render this file because it is too large.
+84
View File
@@ -2621,6 +2621,8 @@ font-technology Variable Variables
Proof Setup Ajuste de prueba
Properties Propiedades
Proportional Metrics Métrica proporcional
Insert Aki Left Insertar aki a la izquierda
Insert Aki Right Insertar aki a la derecha
Character Direction Dirección de caracteres
Digits Dígitos
Arabic Árabes
@@ -2894,6 +2896,8 @@ digits Malayalam Malayálam
Reset Rotate View Restablecer rotación de vista
Rotate View to Selection Rotar vista según la selección
Reset the rows to the artwork's colors Restablecer las filas a los colores de la ilustración
Color Theme Picker Selector de tema de color
Click or drag across the art to pick its colors; Shift adds more Haga clic o arrastre sobre la ilustración para tomar sus colores; Mayús añade más
Reset to Default Restablecer valores predeterminados
Reset to White, Black Restablecer a blanco, negro
Reset with Mesh Restablecer con malla
@@ -3301,6 +3305,7 @@ digits Malayalam Malayálam
Show Note Mostrar nota
Show Options Mostrar opciones
Show Recent Colors Mostrar colores recientes
Toggle RGB Percent Alternar RGB en porcentaje
Show Original Path Mostrar trazado original
Open this dialog with these settings next time Abrir este cuadro de diálogo con estos ajustes la próxima vez
Auto-Simplify Simplificar automáticamente
@@ -4211,6 +4216,85 @@ axis Both Ambos
@msg the script's run is no longer available la ejecución del script ya no está disponible
@msg a failed command changed undo steps that could not be put back, so the script was stopped un comando fallido cambió pasos de deshacer que no se pudieron restaurar, así que el script se detuvo
@msg a recovery copy could not be written, so the script was not run no se pudo escribir una copia de recuperación, así que el script no se ejecutó
@msg Script file access denied Acceso denegado al archivo de script
@msg Script file exceeds 8 MiB El archivo de script supera los 8 MiB
@msg Script file is not open El archivo de script no está abierto
@msg Script file cannot be decoded No se puede descodificar el archivo de script
@msg Script file is not a regular file El archivo de script no es un archivo normal
@msg Script file does not exist El archivo de script no existe
@msg Script file could not be read No se pudo leer el archivo de script
@msg Script folder has more than 2,048 entries La carpeta de script tiene más de 2048 entradas
@msg Script file open mode must be r, w, e or a El modo de apertura del archivo de script debe ser r, w, e o a
@msg Script file writing is not available La escritura de archivos de script no está disponible
@msg Script file dialogs are not available Los cuadros de diálogo de archivos de script no están disponibles
@msg Script files cannot be opened in another application Los archivos de script no se pueden abrir en otra aplicación
@msg Script file access is unavailable on the web El acceso a archivos de script no está disponible en la web
@msg Script has 256 files open El script tiene 256 archivos abiertos
@msg Script file path exceeds 32,767 characters La ruta del archivo de script supera los 32 767 caracteres
@msg Script folder mask takes too many steps to match La máscara de carpeta de script requiere demasiados pasos para coincidir
@msg the script opened more file data than one run may open (32 MiB) el script abrió más datos de archivo de los que puede abrir una ejecución (32 MiB)
@msg File.seek: takes a position and a mode File.seek: recibe una posición y un modo
@msg vc.run: give a command id, as a string vc.run: indique un id de comando, como cadena
@msg vc.run: takes a command id and an object of parameters vc.run: recibe un id de comando y un objeto de parámetros
@msg vc.run: the parameters must be an object vc.run: los parámetros deben ser un objeto
@msg vc.run: the result{place} is too large for a script vc.run: el resultado{place} es demasiado grande para un script
@msg $.evalFile requires a file path $.evalFile requiere una ruta de archivo
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: el tiempo de espera debe ser un número finito de milisegundos, 0 o más
@msg $.evalFile: takes a file path and a timeout $.evalFile: recibe una ruta de archivo y un tiempo de espera
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: línea {line}, columna {column} de {file}: {e} (lanzado)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: línea {line}, columna {column}: {e} (lanzado)
@msg {name}: {e} (thrown) {name}: {e} (lanzado)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: línea {line}, columna {column} de {file}: {e} (límite)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: línea {line}, columna {column}: {e} (límite)
@msg {name}: {e} (limit) {name}: {e} (límite)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: línea {line}, columna {column} de {file}: {e} (error de sintaxis)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: línea {line}, columna {column}: {e} (error de sintaxis)
@msg {name}: {e} (syntax) {name}: {e} (error de sintaxis)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: línea {line}, columna {column} de {file}: {e} (detenido)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: línea {line}, columna {column}: {e} (detenido)
@msg {name}: {e} (stopped) {name}: {e} (detenido)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: línea {line}, columna {column} de {file}: {e} (error interno)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: línea {line}, columna {column}: {e} (error interno)
@msg {name}: {e} (internal) {name}: {e} (error interno)
@msg {e} (these files stay written: {paths}) {e} (estos archivos quedan escritos: {paths})
@msg $.{name}: give a name, as a string $.{name}: indique un nombre, como cadena
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: indique una configuración regional como "en" o "de_DE", o null para la de la interfaz
@msg $.localize: give true or false $.localize: indique true o false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: solo se puede establecer 512, que activa la localización, o 0
@msg $.flags: give a number $.flags: indique un número
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: aquí los scripts solo leen y escriben UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: indique el nombre de una codificación, como cadena
@msg $.memCache: the memory cache size cannot be set $.memCache: no se puede establecer el tamaño de la caché de memoria
@msg $.setenv: give a value, as a string $.setenv: indique un valor, como cadena
@msg $.setenv: only {_1} can be set $.setenv: solo se pueden establecer {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: un valor tiene como máximo {MAX_ENV_BYTES} letras, dígitos y _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: indique un número de milisegundos de 0 a {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: indique un número de milisegundos
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: una ejecución no puede esperar dentro de una devolución de llamada de una función integrada, un getter, una conversión o un archivo que ejecuta $.evalFile; llámelo desde el propio código del script
@msg $.bp: scripts here have no debugger $.bp: aquí los scripts no tienen depurador
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: los scripts aún no pueden mostrar un cuadro de diálogo
@msg {name}: give a message {name}: indique un mensaje
@msg {name}: give the text the field starts with {name}: indique el texto con el que empieza el campo
@msg {name}: the message is longer than 16 KiB {name}: el mensaje ocupa más de 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: el título ocupa más de 256 bytes
@msg {name}: the text the field starts with is longer than 16 KiB {name}: el texto con el que empieza el campo ocupa más de 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un cuadro de diálogo no puede abrirse dentro de una devolución de llamada de una función integrada, un getter, una conversión o un archivo que ejecuta $.evalFile; llámelo desde el propio código del script
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la siguiente respuesta de `answers` es para {_1}, no para {name}
@msg {name}: `answers` has no answer left for this dialog {name}: a `answers` no le quedan respuestas para este cuadro de diálogo
@msg vc.document{place} is too large for a script vc.document{place} es demasiado grande para un script
@msg vc.log: the log of this run is full vc.log: el registro de esta ejecución está lleno
@msg this function's script run has ended la ejecución del script de esta función ha terminado
@msg the script made more host calls than one run may make el script hizo más llamadas al anfitrión de las que puede hacer una ejecución
@msg the script passed more data to and from commands than one run may pass el script pasó más datos a los comandos y desde ellos de los que puede pasar una ejecución
@msg the script added more objects and data to the documents than one run may add el script añadió a los documentos más objetos y datos de los que puede añadir una ejecución
@msg {what}: the object is not a File or a Folder {what}: el objeto no es un File ni un Folder
@msg {what}: the count must be a finite number, 0 or more {what}: la cantidad debe ser un número finito, 0 o más
@msg File.seek: the position must be a finite number File.seek: la posición debe ser un número finito
@msg File.seek: the mode must be 0, 1 or 2 File.seek: el modo debe ser 0, 1 o 2
@msg script file is compiled: {value} el archivo de script está compilado: {value}
@msg `name` must be the name of a script engine `name` debe ser el nombre de un motor de scripts
@msg the main script engine is new for each run and is never kept, so it cannot be dropped el motor de scripts principal es nuevo en cada ejecución y nunca se conserva, por lo que no se puede descartar
@msg there is no script engine named {name} no hay ningún motor de scripts llamado {name}
@msg Running a script Ejecutando un script
@msg Copied the script report Se copió el informe del script
@msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -1561,6 +1561,8 @@ lighting Light Valo
Leading Riviväli
No Break Ei katkoa
Proportional Metrics Suhteelliset metriikat
Insert Aki Left Lisää aki vasemmalle
Insert Aki Right Lisää aki oikealle
Character Direction Merkkien suunta
Digits Numerot
Arabic Arabia
@@ -1580,6 +1582,7 @@ digits Malayalam Malajalam
Select a text object to edit its character attributes. Valitse tekstiobjekti, jonka merkkimääritteitä haluat muokata.
Show Options Näytä asetukset
Show Recent Colors Näytä viimeisimmät värit
Toggle RGB Percent Vaihda RGB prosentteina
Small Caps Kapiteelit
Small Caps (on the roadmap) Kapiteelit (suunnitteilla)
Standard Vertical Roman Alignment Tavallinen pystysuuntainen latinalainen tasaus
@@ -2818,6 +2821,8 @@ digits Malayalam Malajalam
Randomly change saturation and brightness Muuta kylläisyyttä ja kirkkautta satunnaisesti
Recolor this row Väritä tämä rivi uudelleen
Reset the rows to the artwork's colors Palauta rivit kuvituksen väreihin
Color Theme Picker Väriteeman valitsin
Click or drag across the art to pick its colors; Shift adds more Napsauta tai vedä kuvituksen yli poimiaksesi sen värit; Vaihto lisää useampia
Separate colors into rows Erottele värit riveille
Unlink harmony colors Poista harmoniavärien linkitys
1 Color Job 1 värin työ
@@ -4435,6 +4440,85 @@ imageTrace Outline Ääriviiva
@msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä
@msg a failed command changed undo steps that could not be put back, so the script was stopped epäonnistunut komento muutti kumoamisvaiheita, joita ei voitu palauttaa, joten komentosarja pysäytettiin
@msg a recovery copy could not be written, so the script was not run palautuskopiota ei voitu kirjoittaa, joten komentosarjaa ei suoritettu
@msg Script file access denied Pääsy komentosarjatiedostoon estettiin
@msg Script file exceeds 8 MiB Komentosarjatiedosto on suurempi kuin 8 MiB
@msg Script file is not open Komentosarjatiedosto ei ole auki
@msg Script file cannot be decoded Komentosarjatiedostoa ei voi purkaa
@msg Script file is not a regular file Komentosarjatiedosto ei ole tavallinen tiedosto
@msg Script file does not exist Komentosarjatiedostoa ei ole olemassa
@msg Script file could not be read Komentosarjatiedostoa ei voitu lukea
@msg Script folder has more than 2,048 entries Komentosarjakansiossa on yli 2 048 kohdetta
@msg Script file open mode must be r, w, e or a Komentosarjatiedoston avaustilan on oltava r, w, e tai a
@msg Script file writing is not available Komentosarjatiedostojen kirjoittaminen ei ole käytettävissä
@msg Script file dialogs are not available Komentosarjojen tiedostovalintaikkunat eivät ole käytettävissä
@msg Script files cannot be opened in another application Komentosarjatiedostoja ei voi avata toisessa sovelluksessa
@msg Script file access is unavailable on the web Komentosarjatiedostojen käyttö ei ole mahdollista verkossa
@msg Script has 256 files open Komentosarjalla on 256 tiedostoa auki
@msg Script file path exceeds 32,767 characters Komentosarjatiedoston polku on yli 32 767 merkkiä
@msg Script folder mask takes too many steps to match Komentosarjakansion maskin täsmäytys vaatii liian monta vaihetta
@msg the script opened more file data than one run may open (32 MiB) komentosarja avasi enemmän tiedostodataa kuin yksi suoritus saa avata (32 MiB)
@msg File.seek: takes a position and a mode File.seek: ottaa sijainnin ja tilan
@msg vc.run: give a command id, as a string vc.run: anna komennon tunnus merkkijonona
@msg vc.run: takes a command id and an object of parameters vc.run: ottaa komennon tunnuksen ja parametriobjektin
@msg vc.run: the parameters must be an object vc.run: parametrien on oltava objekti
@msg vc.run: the result{place} is too large for a script vc.run: tulos{place} on liian suuri komentosarjalle
@msg $.evalFile requires a file path $.evalFile vaatii tiedostopolun
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: aikakatkaisun on oltava äärellinen määrä millisekunteja, 0 tai enemmän
@msg $.evalFile: takes a file path and a timeout $.evalFile: ottaa tiedostopolun ja aikakatkaisun
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, rivi {line}, sarake {column}: {e} (heitetty)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: rivi {line}, sarake {column}: {e} (heitetty)
@msg {name}: {e} (thrown) {name}: {e} (heitetty)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: {file}, rivi {line}, sarake {column}: {e} (raja)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: rivi {line}, sarake {column}: {e} (raja)
@msg {name}: {e} (limit) {name}: {e} (raja)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: {file}, rivi {line}, sarake {column}: {e} (syntaksivirhe)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: rivi {line}, sarake {column}: {e} (syntaksivirhe)
@msg {name}: {e} (syntax) {name}: {e} (syntaksivirhe)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: {file}, rivi {line}, sarake {column}: {e} (pysäytetty)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: rivi {line}, sarake {column}: {e} (pysäytetty)
@msg {name}: {e} (stopped) {name}: {e} (pysäytetty)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: {file}, rivi {line}, sarake {column}: {e} (sisäinen virhe)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: rivi {line}, sarake {column}: {e} (sisäinen virhe)
@msg {name}: {e} (internal) {name}: {e} (sisäinen virhe)
@msg {e} (these files stay written: {paths}) {e} (nämä tiedostot jäävät kirjoitetuiksi: {paths})
@msg $.{name}: give a name, as a string $.{name}: anna nimi merkkijonona
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: anna kieliasetus, kuten "en" tai "de_DE", tai null käyttöliittymän kieliasetukselle
@msg $.localize: give true or false $.localize: anna true tai false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: vain 512, joka ottaa lokalisoinnin käyttöön, tai 0 voidaan asettaa
@msg $.flags: give a number $.flags: anna luku
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: skriptit lukevat ja kirjoittavat täällä vain UTF-8:aa
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: anna merkistökoodauksen nimi merkkijonona
@msg $.memCache: the memory cache size cannot be set $.memCache: muistivälimuistin kokoa ei voi asettaa
@msg $.setenv: give a value, as a string $.setenv: anna arvo merkkijonona
@msg $.setenv: only {_1} can be set $.setenv: vain {_1} voidaan asettaa
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: arvossa on enintään {MAX_ENV_BYTES} kirjainta, numeroa ja merkkiä _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: anna millisekuntimäärä väliltä 0–{MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: anna millisekuntimäärä
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: ajo ei voi odottaa sisäänrakennetun funktion takaisinkutsussa, getterissä, muunnoksessa tai tiedostossa, jonka $.evalFile ajaa; kutsu sitä skriptin omasta koodista
@msg $.bp: scripts here have no debugger $.bp: skripteillä ei ole täällä virheenjäljitintä
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: skriptit eivät vielä voi näyttää valintaikkunaa
@msg {name}: give a message {name}: anna viesti
@msg {name}: give the text the field starts with {name}: anna teksti, jolla kenttä alkaa
@msg {name}: the message is longer than 16 KiB {name}: viesti on pidempi kuin 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: otsikko on pidempi kuin 256 tavua
@msg {name}: the text the field starts with is longer than 16 KiB {name}: teksti, jolla kenttä alkaa, on pidempi kuin 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: valintaikkuna ei voi avautua sisäänrakennetun funktion takaisinkutsussa, getterissä, muunnoksessa tai tiedostossa, jonka $.evalFile ajaa; kutsu sitä skriptin omasta koodista
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: seuraava vastaus kohteessa `answers` on kohteelle {_1}, ei kohteelle {name}
@msg {name}: `answers` has no answer left for this dialog {name}: kohteessa `answers` ei ole enää vastausta tälle valintaikkunalle
@msg vc.document{place} is too large for a script vc.document{place} on liian suuri skriptille
@msg vc.log: the log of this run is full vc.log: tämän ajon loki on täynnä
@msg this function's script run has ended tämän funktion skriptiajo on päättynyt
@msg the script made more host calls than one run may make skripti teki enemmän isäntäkutsuja kuin yksi ajo saa tehdä
@msg the script passed more data to and from commands than one run may pass skripti välitti komennoille ja komennoilta enemmän tietoa kuin yksi ajo saa välittää
@msg the script added more objects and data to the documents than one run may add skripti lisäsi asiakirjoihin enemmän objekteja ja tietoja kuin yksi ajo saa lisätä
@msg {what}: the object is not a File or a Folder {what}: objekti ei ole File eikä Folder
@msg {what}: the count must be a finite number, 0 or more {what}: määrän on oltava äärellinen luku, 0 tai enemmän
@msg File.seek: the position must be a finite number File.seek: sijainnin on oltava äärellinen luku
@msg File.seek: the mode must be 0, 1 or 2 File.seek: tilan on oltava 0, 1 tai 2
@msg script file is compiled: {value} skriptitiedosto on käännetty: {value}
@msg `name` must be the name of a script engine `name` on oltava skriptimoottorin nimi
@msg the main script engine is new for each run and is never kept, so it cannot be dropped pääskriptimoottori on uusi jokaisella ajolla eikä sitä koskaan säilytetä, joten sitä ei voi poistaa
@msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole
@msg Running a script Suoritetaan komentosarjaa
@msg Copied the script report Komentosarjan raportti kopioitiin
@msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -2613,6 +2613,8 @@ font-technology Variable Variables
Proof Setup Format d’épreuve
Properties Propriétés
Proportional Metrics Métrique proportionnelle
Insert Aki Left Insérer un aki à gauche
Insert Aki Right Insérer un aki à droite
Character Direction Direction des caractères
Digits Chiffres
Arabic Arabes
@@ -2886,6 +2888,8 @@ digits Malayalam Malayalam
Reset Rotate View Réinitialiser la rotation de l’affichage
Rotate View to Selection Faire pivoter l’affichage selon la sélection
Reset the rows to the artwork's colors Réinitialiser les lignes avec les couleurs de l’illustration
Color Theme Picker Sélecteur de thème de couleurs
Click or drag across the art to pick its colors; Shift adds more Cliquez ou faites glisser sur l’illustration pour prélever ses couleurs ; Maj en ajoute d’autres
Reset to Default Rétablir les valeurs par défaut
Reset to White, Black Réinitialiser à blanc, noir
Reset with Mesh Réinitialiser avec un filet
@@ -3293,6 +3297,7 @@ digits Malayalam Malayalam
Show Note Afficher la note
Show Options Afficher les options
Show Recent Colors Afficher les couleurs récentes
Toggle RGB Percent Basculer RVB en pourcentage
Show Original Path Afficher le tracé d’origine
Open this dialog with these settings next time Ouvrir cette boîte de dialogue avec ces réglages la prochaine fois
Auto-Simplify Simplifier automatiquement
@@ -4200,6 +4205,85 @@ axis Both Les deux
@msg the script's run is no longer available l’exécution du script n’est plus disponible
@msg a failed command changed undo steps that could not be put back, so the script was stopped une commande en échec a modifié des étapes d’annulation qui n’ont pas pu être rétablies, le script a donc été arrêté
@msg a recovery copy could not be written, so the script was not run une copie de récupération n’a pas pu être écrite, le script n’a donc pas été exécuté
@msg Script file access denied Accès au fichier de script refusé
@msg Script file exceeds 8 MiB Le fichier de script dépasse 8 Mio
@msg Script file is not open Le fichier de script n’est pas ouvert
@msg Script file cannot be decoded Le fichier de script ne peut pas être décodé
@msg Script file is not a regular file Le fichier de script n’est pas un fichier ordinaire
@msg Script file does not exist Le fichier de script n’existe pas
@msg Script file could not be read Le fichier de script n’a pas pu être lu
@msg Script folder has more than 2,048 entries Le dossier de script contient plus de 2 048 entrées
@msg Script file open mode must be r, w, e or a Le mode d’ouverture du fichier de script doit être r, w, e ou a
@msg Script file writing is not available L’écriture de fichiers de script n’est pas disponible
@msg Script file dialogs are not available Les boîtes de dialogue de fichiers de script ne sont pas disponibles
@msg Script files cannot be opened in another application Les fichiers de script ne peuvent pas être ouverts dans une autre application
@msg Script file access is unavailable on the web L’accès aux fichiers de script n’est pas disponible sur le web
@msg Script has 256 files open Le script a 256 fichiers ouverts
@msg Script file path exceeds 32,767 characters Le chemin du fichier de script dépasse 32 767 caractères
@msg Script folder mask takes too many steps to match Le masque de dossier de script demande trop d’étapes de correspondance
@msg the script opened more file data than one run may open (32 MiB) le script a ouvert plus de données de fichier qu’une exécution ne peut en ouvrir (32 Mio)
@msg File.seek: takes a position and a mode File.seek : prend une position et un mode
@msg vc.run: give a command id, as a string vc.run : indiquez un identifiant de commande, sous forme de chaîne
@msg vc.run: takes a command id and an object of parameters vc.run : prend un identifiant de commande et un objet de paramètres
@msg vc.run: the parameters must be an object vc.run : les paramètres doivent être un objet
@msg vc.run: the result{place} is too large for a script vc.run : le résultat{place} est trop volumineux pour un script
@msg $.evalFile requires a file path $.evalFile nécessite un chemin de fichier
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile : le délai doit être un nombre fini de millisecondes, 0 ou plus
@msg $.evalFile: takes a file path and a timeout $.evalFile : prend un chemin de fichier et un délai
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name} : ligne {line}, colonne {column} de {file} : {e} (levée)
@msg {name}: line {line}, column {column}: {e} (thrown) {name} : ligne {line}, colonne {column} : {e} (levée)
@msg {name}: {e} (thrown) {name} : {e} (levée)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name} : ligne {line}, colonne {column} de {file} : {e} (limite)
@msg {name}: line {line}, column {column}: {e} (limit) {name} : ligne {line}, colonne {column} : {e} (limite)
@msg {name}: {e} (limit) {name} : {e} (limite)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name} : ligne {line}, colonne {column} de {file} : {e} (erreur de syntaxe)
@msg {name}: line {line}, column {column}: {e} (syntax) {name} : ligne {line}, colonne {column} : {e} (erreur de syntaxe)
@msg {name}: {e} (syntax) {name} : {e} (erreur de syntaxe)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name} : ligne {line}, colonne {column} de {file} : {e} (arrêté)
@msg {name}: line {line}, column {column}: {e} (stopped) {name} : ligne {line}, colonne {column} : {e} (arrêté)
@msg {name}: {e} (stopped) {name} : {e} (arrêté)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name} : ligne {line}, colonne {column} de {file} : {e} (erreur interne)
@msg {name}: line {line}, column {column}: {e} (internal) {name} : ligne {line}, colonne {column} : {e} (erreur interne)
@msg {name}: {e} (internal) {name} : {e} (erreur interne)
@msg {e} (these files stay written: {paths}) {e} (ces fichiers restent écrits : {paths})
@msg $.{name}: give a name, as a string $.{name} : indiquez un nom, sous forme de chaîne
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale : indiquez des paramètres régionaux tels que "en" ou "de_DE", ou null pour ceux de l'interface
@msg $.localize: give true or false $.localize : indiquez true ou false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags : seules les valeurs 512, qui active la localisation, ou 0 peuvent être définies
@msg $.flags: give a number $.flags : indiquez un nombre
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding : ici, les scripts lisent et écrivent uniquement en UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding : indiquez le nom d'un encodage, sous forme de chaîne
@msg $.memCache: the memory cache size cannot be set $.memCache : la taille du cache mémoire ne peut pas être définie
@msg $.setenv: give a value, as a string $.setenv : indiquez une valeur, sous forme de chaîne
@msg $.setenv: only {_1} can be set $.setenv : seules {_1} peuvent être définies
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv : une valeur comporte au plus {MAX_ENV_BYTES} lettres, chiffres et _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep : indiquez un nombre de millisecondes de 0 à {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep : indiquez un nombre de millisecondes
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep : une exécution ne peut pas attendre dans un rappel d'une fonction intégrée, un accesseur, une conversion ou un fichier que $.evalFile exécute ; appelez-la depuis le code du script lui-même
@msg $.bp: scripts here have no debugger $.bp : ici, les scripts n'ont pas de débogueur
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker : les scripts ne peuvent pas encore afficher de boîte de dialogue
@msg {name}: give a message {name} : indiquez un message
@msg {name}: give the text the field starts with {name} : indiquez le texte par lequel le champ commence
@msg {name}: the message is longer than 16 KiB {name} : le message dépasse 16 Kio
@msg {name}: the title is longer than 256 bytes {name} : le titre dépasse 256 octets
@msg {name}: the text the field starts with is longer than 16 KiB {name} : le texte par lequel le champ commence dépasse 16 Kio
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name} : une boîte de dialogue ne peut pas s'ouvrir dans un rappel d'une fonction intégrée, un accesseur, une conversion ou un fichier que $.evalFile exécute ; appelez-la depuis le code du script lui-même
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name} : la réponse suivante de `answers` est pour {_1}, pas pour {name}
@msg {name}: `answers` has no answer left for this dialog {name} : `answers` n'a plus de réponse pour cette boîte de dialogue
@msg vc.document{place} is too large for a script vc.document{place} est trop volumineux pour un script
@msg vc.log: the log of this run is full vc.log : le journal de cette exécution est plein
@msg this function's script run has ended l'exécution du script de cette fonction est terminée
@msg the script made more host calls than one run may make le script a fait plus d'appels à l'hôte qu'une exécution ne peut en faire
@msg the script passed more data to and from commands than one run may pass le script a transmis plus de données vers et depuis les commandes qu'une exécution ne peut en transmettre
@msg the script added more objects and data to the documents than one run may add le script a ajouté aux documents plus d'objets et de données qu'une exécution ne peut en ajouter
@msg {what}: the object is not a File or a Folder {what} : l'objet n'est ni un File ni un Folder
@msg {what}: the count must be a finite number, 0 or more {what} : le nombre doit être un nombre fini, 0 ou plus
@msg File.seek: the position must be a finite number File.seek : la position doit être un nombre fini
@msg File.seek: the mode must be 0, 1 or 2 File.seek : le mode doit être 0, 1 ou 2
@msg script file is compiled: {value} le fichier de script est compilé : {value}
@msg `name` must be the name of a script engine `name` doit être le nom d'un moteur de script
@msg the main script engine is new for each run and is never kept, so it cannot be dropped le moteur de script principal est nouveau à chaque exécution et n'est jamais conservé, il ne peut donc pas être supprimé
@msg there is no script engine named {name} il n'y a aucun moteur de script nommé {name}
@msg Running a script Exécution d’un script
@msg Copied the script report Rapport du script copié
@msg Corners edits the corners of a path Angles modifie les angles d’un tracé
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -3608,6 +3608,8 @@ antiAlias Sharp शार्प
Properties प्रॉपर्टीज़
Proportional Lining आनुपातिक लाइनिंग
Proportional Metrics आनुपातिक मीट्रिक
Insert Aki Left बाईं ओर आकी जोड़ें
Insert Aki Right दाईं ओर आकी जोड़ें
Proportional Oldstyle आनुपातिक ओल्डस्टाइल
Protect Corners कॉर्नर को सुरक्षित रखें
Proximity Guides निकटता गाइड
@@ -3928,6 +3930,8 @@ antiAlias Sharp शार्प
Reset Text Transform टेक्स्ट ट्रांसफॉर्मर को रीसेट करें
Reset Text Transform and Scale टेक्स्ट ट्रांसफॉर्म और स्केल को रीसेट करें
Reset the rows to the artwork's colors आर्टवर्क के रंग के लिए पंक्तियों को रीसेट करें
Color Theme Picker रंग थीम पिकर
Click or drag across the art to pick its colors; Shift adds more आर्टवर्क के रंग लेने के लिए उस पर क्लिक करें या खींचें; Shift और जोड़ता है
Reset to default डिफ़ॉल्ट पर रीसेट करें
Reset to Default डिफ़ॉल्ट पर रीसेट करें
Reset to Defaults डिफ़ॉल्ट पर रीसेट करें
@@ -4505,6 +4509,7 @@ antiAlias Sharp शार्प
Show Note नोट दिखाएं
Show Options ऑप्शन्स दिखाएँ
Show Recent Colors हाल के रंग दिखाएँ
Toggle RGB Percent RGB प्रतिशत में बदलें
Show Original Path मूल पाथ दिखाएं
Show Package पैकेज करें दिखाएँ
Show Panel शो पैनल
@@ -6448,6 +6453,85 @@ antiAlias Sharp शार्प
@msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है
@msg a failed command changed undo steps that could not be put back, so the script was stopped एक विफल कमांड ने पूर्ववत चरण बदल दिए जिन्हें वापस नहीं रखा जा सका, इसलिए स्क्रिप्ट रोक दी गई
@msg a recovery copy could not be written, so the script was not run रिकवरी प्रति नहीं लिखी जा सकी, इसलिए स्क्रिप्ट नहीं चलाई गई
@msg Script file access denied स्क्रिप्ट फ़ाइल तक पहुँच अस्वीकृत
@msg Script file exceeds 8 MiB स्क्रिप्ट फ़ाइल 8 MiB से बड़ी है
@msg Script file is not open स्क्रिप्ट फ़ाइल खुली नहीं है
@msg Script file cannot be decoded स्क्रिप्ट फ़ाइल को डिकोड नहीं किया जा सकता
@msg Script file is not a regular file स्क्रिप्ट फ़ाइल सामान्य फ़ाइल नहीं है
@msg Script file does not exist स्क्रिप्ट फ़ाइल मौजूद नहीं है
@msg Script file could not be read स्क्रिप्ट फ़ाइल पढ़ी नहीं जा सकी
@msg Script folder has more than 2,048 entries स्क्रिप्ट फ़ोल्डर में 2,048 से अधिक प्रविष्टियाँ हैं
@msg Script file open mode must be r, w, e or a स्क्रिप्ट फ़ाइल खोलने का मोड r, w, e या a होना चाहिए
@msg Script file writing is not available स्क्रिप्ट फ़ाइल लिखना उपलब्ध नहीं है
@msg Script file dialogs are not available स्क्रिप्ट फ़ाइल संवाद उपलब्ध नहीं हैं
@msg Script files cannot be opened in another application स्क्रिप्ट फ़ाइलें किसी अन्य ऐप्लिकेशन में नहीं खोली जा सकतीं
@msg Script file access is unavailable on the web वेब पर स्क्रिप्ट फ़ाइल पहुँच उपलब्ध नहीं है
@msg Script has 256 files open स्क्रिप्ट ने 256 फ़ाइलें खोल रखी हैं
@msg Script file path exceeds 32,767 characters स्क्रिप्ट फ़ाइल का पथ 32,767 वर्णों से अधिक है
@msg Script folder mask takes too many steps to match स्क्रिप्ट फ़ोल्डर मास्क के मिलान में बहुत अधिक चरण लगते हैं
@msg the script opened more file data than one run may open (32 MiB) स्क्रिप्ट ने एक रन में खोले जा सकने वाले फ़ाइल डेटा से अधिक डेटा खोला (32 MiB)
@msg File.seek: takes a position and a mode File.seek: एक स्थिति और एक मोड लेता है
@msg vc.run: give a command id, as a string vc.run: कमांड id स्ट्रिंग के रूप में दें
@msg vc.run: takes a command id and an object of parameters vc.run: एक कमांड id और पैरामीटर का एक ऑब्जेक्ट लेता है
@msg vc.run: the parameters must be an object vc.run: पैरामीटर एक ऑब्जेक्ट होने चाहिए
@msg vc.run: the result{place} is too large for a script vc.run: परिणाम{place} स्क्रिप्ट के लिए बहुत बड़ा है
@msg $.evalFile requires a file path $.evalFile के लिए फ़ाइल पथ आवश्यक है
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: टाइमआउट मिलीसेकंड की एक सीमित संख्या होनी चाहिए, 0 या अधिक
@msg $.evalFile: takes a file path and a timeout $.evalFile: एक फ़ाइल पथ और एक टाइमआउट लेता है
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file} की लाइन {line}, कॉलम {column}: {e} (थ्रो किया गया)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: लाइन {line}, कॉलम {column}: {e} (थ्रो किया गया)
@msg {name}: {e} (thrown) {name}: {e} (थ्रो किया गया)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: {file} की लाइन {line}, कॉलम {column}: {e} (सीमा)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: लाइन {line}, कॉलम {column}: {e} (सीमा)
@msg {name}: {e} (limit) {name}: {e} (सीमा)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: {file} की लाइन {line}, कॉलम {column}: {e} (सिंटैक्स त्रुटि)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: लाइन {line}, कॉलम {column}: {e} (सिंटैक्स त्रुटि)
@msg {name}: {e} (syntax) {name}: {e} (सिंटैक्स त्रुटि)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: {file} की लाइन {line}, कॉलम {column}: {e} (रोका गया)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: लाइन {line}, कॉलम {column}: {e} (रोका गया)
@msg {name}: {e} (stopped) {name}: {e} (रोका गया)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: {file} की लाइन {line}, कॉलम {column}: {e} (आंतरिक त्रुटि)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: लाइन {line}, कॉलम {column}: {e} (आंतरिक त्रुटि)
@msg {name}: {e} (internal) {name}: {e} (आंतरिक त्रुटि)
@msg {e} (these files stay written: {paths}) {e} (ये फ़ाइलें लिखी हुई रहती हैं: {paths})
@msg $.{name}: give a name, as a string $.{name}: एक नाम स्ट्रिंग के रूप में दें
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: "en" या "de_DE" जैसी कोई लोकेल दें, या इंटरफ़ेस की लोकेल के लिए null दें
@msg $.localize: give true or false $.localize: true या false दें
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: केवल 512, जो स्थानीयकरण चालू करता है, या 0 सेट किया जा सकता है
@msg $.flags: give a number $.flags: एक संख्या दें
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: यहाँ स्क्रिप्ट केवल UTF-8 पढ़ती और लिखती हैं
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: किसी एन्कोडिंग का नाम स्ट्रिंग के रूप में दें
@msg $.memCache: the memory cache size cannot be set $.memCache: मेमोरी कैश का आकार सेट नहीं किया जा सकता
@msg $.setenv: give a value, as a string $.setenv: एक मान स्ट्रिंग के रूप में दें
@msg $.setenv: only {_1} can be set $.setenv: केवल {_1} सेट किए जा सकते हैं
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: किसी मान में अधिकतम {MAX_ENV_BYTES} अक्षर, अंक और _ . - @ होते हैं
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: 0 से {MAX_SLEEP_MS} तक मिलीसेकंड की संख्या दें
@msg $.sleep: give a number of milliseconds $.sleep: मिलीसेकंड की संख्या दें
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: कोई रन किसी बिल्ट-इन फ़ंक्शन के कॉलबैक, getter, रूपांतरण या $.evalFile द्वारा चलाई गई फ़ाइल के भीतर प्रतीक्षा नहीं कर सकता; इसे स्क्रिप्ट के अपने कोड से कॉल करें
@msg $.bp: scripts here have no debugger $.bp: यहाँ स्क्रिप्ट के लिए कोई डीबगर नहीं है
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: स्क्रिप्ट अभी डायलॉग नहीं दिखा सकतीं
@msg {name}: give a message {name}: एक संदेश दें
@msg {name}: give the text the field starts with {name}: वह टेक्स्ट दें जिससे फ़ील्ड शुरू होता है
@msg {name}: the message is longer than 16 KiB {name}: संदेश 16 KiB से लंबा है
@msg {name}: the title is longer than 256 bytes {name}: शीर्षक 256 बाइट से लंबा है
@msg {name}: the text the field starts with is longer than 16 KiB {name}: जिस टेक्स्ट से फ़ील्ड शुरू होता है वह 16 KiB से लंबा है
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: कोई डायलॉग किसी बिल्ट-इन फ़ंक्शन के कॉलबैक, getter, रूपांतरण या $.evalFile द्वारा चलाई गई फ़ाइल के भीतर नहीं खुल सकता; इसे स्क्रिप्ट के अपने कोड से कॉल करें
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` में अगला उत्तर {_1} के लिए है, {name} के लिए नहीं
@msg {name}: `answers` has no answer left for this dialog {name}: `answers` में इस डायलॉग के लिए कोई उत्तर नहीं बचा है
@msg vc.document{place} is too large for a script vc.document{place} स्क्रिप्ट के लिए बहुत बड़ा है
@msg vc.log: the log of this run is full vc.log: इस रन का लॉग भर गया है
@msg this function's script run has ended इस फ़ंक्शन का स्क्रिप्ट रन समाप्त हो गया है
@msg the script made more host calls than one run may make स्क्रिप्ट ने एक रन में अनुमत से अधिक होस्ट कॉल किए
@msg the script passed more data to and from commands than one run may pass स्क्रिप्ट ने कमांड को और कमांड से एक रन में अनुमत से अधिक डेटा भेजा
@msg the script added more objects and data to the documents than one run may add स्क्रिप्ट ने दस्तावेज़ों में एक रन में अनुमत से अधिक ऑब्जेक्ट और डेटा जोड़े
@msg {what}: the object is not a File or a Folder {what}: ऑब्जेक्ट न File है न Folder
@msg {what}: the count must be a finite number, 0 or more {what}: गिनती एक सीमित संख्या होनी चाहिए, 0 या अधिक
@msg File.seek: the position must be a finite number File.seek: स्थिति एक सीमित संख्या होनी चाहिए
@msg File.seek: the mode must be 0, 1 or 2 File.seek: मोड 0, 1 या 2 होना चाहिए
@msg script file is compiled: {value} स्क्रिप्ट फ़ाइल कंपाइल की हुई है: {value}
@msg `name` must be the name of a script engine `name` किसी स्क्रिप्ट इंजन का नाम होना चाहिए
@msg the main script engine is new for each run and is never kept, so it cannot be dropped मुख्य स्क्रिप्ट इंजन हर रन के लिए नया होता है और कभी रखा नहीं जाता, इसलिए इसे हटाया नहीं जा सकता
@msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है
@msg Running a script स्क्रिप्ट चल रही है
@msg Copied the script report Copied स्क्रिप्ट रिपोर्ट
@msg copy needs path: the file to copy into the document's folder copy: प्रतिलिपि की जरूरत है पाथ: फ़ाइल को डॉक्यूमेंट के फ़ोल्डर में कॉपी करने के लिए
Can't render this file because it is too large.
+84
View File
@@ -3171,6 +3171,8 @@ mark-style Japanese Japán
Proof Setup Színpróba beállítása
Properties Tulajdonságok
Proportional Metrics Arányos metrika
Insert Aki Left Aki beszúrása balra
Insert Aki Right Aki beszúrása jobbra
Proportional Lining Arányos modern
Position: Pozíció:
Default Position Alapértelmezett pozíció
@@ -3444,6 +3446,8 @@ mark-style Japanese Japán
Reset Rotate View Nézetforgatás visszaállítása
Rotate View to Selection Nézet elforgatása a kijelöléshez
Reset the rows to the artwork's colors Sorok visszaállítása a grafika színeire
Color Theme Picker Színtéma-választó
Click or drag across the art to pick its colors; Shift adds more Kattintson vagy húzzon a grafikán a színei felvételéhez; a Shift továbbiakat ad hozzá
Reset to default Alapérték visszaállítása
Reset to Default Alapérték visszaállítása
Reset to Defaults Alapértékek visszaállítása
@@ -3935,6 +3939,7 @@ mark-style Japanese Japán
Show Note Megjegyzés megjelenítése
Show Options Beállítások megjelenítése
Show Recent Colors Legutóbbi színek megjelenítése
Toggle RGB Percent RGB százalékos megjelenítésének váltása
Show Original Path Eredeti útvonal megjelenítése
Open this dialog with these settings next time Legközelebb ez a párbeszédablak nyíljon meg ezekkel a beállításokkal
Auto-Simplify Automatikus egyszerűsítés
@@ -5015,6 +5020,85 @@ imageTrace Outline Körvonal
@msg the script's run is no longer available a parancsfájl futása már nem érhető el
@msg a failed command changed undo steps that could not be put back, so the script was stopped egy sikertelen parancs olyan visszavonási lépéseket módosított, amelyeket nem lehetett visszaállítani, ezért a parancsfájl leállt
@msg a recovery copy could not be written, so the script was not run a helyreállítási másolatot nem sikerült kiírni, ezért a parancsfájl nem futott le
@msg Script file access denied A parancsfájl elérése megtagadva
@msg Script file exceeds 8 MiB A parancsfájl nagyobb 8 MiB-nál
@msg Script file is not open A parancsfájl nincs megnyitva
@msg Script file cannot be decoded A parancsfájl nem dekódolható
@msg Script file is not a regular file A parancsfájl nem normál fájl
@msg Script file does not exist A parancsfájl nem létezik
@msg Script file could not be read A parancsfájlt nem sikerült beolvasni
@msg Script folder has more than 2,048 entries A parancsfájlmappában 2048-nál több bejegyzés van
@msg Script file open mode must be r, w, e or a A parancsfájl megnyitási módja r, w, e vagy a lehet
@msg Script file writing is not available A parancsfájlok írása nem érhető el
@msg Script file dialogs are not available A parancsfájlok fájlpárbeszédpanelei nem érhetők el
@msg Script files cannot be opened in another application A parancsfájlok nem nyithatók meg másik alkalmazásban
@msg Script file access is unavailable on the web A parancsfájlok elérése a weben nem érhető el
@msg Script has 256 files open A parancsfájlnak 256 megnyitott fájlja van
@msg Script file path exceeds 32,767 characters A parancsfájl elérési útja hosszabb 32 767 karakternél
@msg Script folder mask takes too many steps to match A parancsfájlmappa maszkjának illesztése túl sok lépést igényel
@msg the script opened more file data than one run may open (32 MiB) a parancsfájl több fájladatot nyitott meg, mint amennyit egy futás megnyithat (32 MiB)
@msg File.seek: takes a position and a mode File.seek: egy pozíciót és egy módot vár
@msg vc.run: give a command id, as a string vc.run: adjon meg egy parancsazonosítót karakterláncként
@msg vc.run: takes a command id and an object of parameters vc.run: egy parancsazonosítót és egy paraméterobjektumot vár
@msg vc.run: the parameters must be an object vc.run: a paramétereknek objektumnak kell lenniük
@msg vc.run: the result{place} is too large for a script vc.run: az eredmény{place} túl nagy egy parancsfájlhoz
@msg $.evalFile requires a file path A $.evalFile fájlútvonalat igényel
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: az időkorlátnak véges számú ezredmásodpercnek kell lennie, 0 vagy több
@msg $.evalFile: takes a file path and a timeout $.evalFile: egy fájlútvonalat és egy időkorlátot vár
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, {line}. sor, {column}. oszlop: {e} (kivétel)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line}. sor, {column}. oszlop: {e} (kivétel)
@msg {name}: {e} (thrown) {name}: {e} (kivétel)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: {file}, {line}. sor, {column}. oszlop: {e} (korlát)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: {line}. sor, {column}. oszlop: {e} (korlát)
@msg {name}: {e} (limit) {name}: {e} (korlát)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: {file}, {line}. sor, {column}. oszlop: {e} (szintaktikai hiba)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: {line}. sor, {column}. oszlop: {e} (szintaktikai hiba)
@msg {name}: {e} (syntax) {name}: {e} (szintaktikai hiba)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: {file}, {line}. sor, {column}. oszlop: {e} (leállítva)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: {line}. sor, {column}. oszlop: {e} (leállítva)
@msg {name}: {e} (stopped) {name}: {e} (leállítva)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: {file}, {line}. sor, {column}. oszlop: {e} (belső hiba)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: {line}. sor, {column}. oszlop: {e} (belső hiba)
@msg {name}: {e} (internal) {name}: {e} (belső hiba)
@msg {e} (these files stay written: {paths}) {e} (ezek a fájlok írva maradnak: {paths})
@msg $.{name}: give a name, as a string $.{name}: adjon meg egy nevet karakterláncként
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: adjon meg egy területi beállítást, például "en" vagy "de_DE", vagy null értéket a felületéhez
@msg $.localize: give true or false $.localize: adjon meg true vagy false értéket
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: csak a 512, amely bekapcsolja a honosítást, vagy a 0 állítható be
@msg $.flags: give a number $.flags: adjon meg egy számot
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: a parancsfájlok itt csak UTF-8 kódolást olvasnak és írnak
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: adja meg egy kódolás nevét karakterláncként
@msg $.memCache: the memory cache size cannot be set $.memCache: a memória-gyorsítótár mérete nem állítható be
@msg $.setenv: give a value, as a string $.setenv: adjon meg egy értéket karakterláncként
@msg $.setenv: only {_1} can be set $.setenv: csak ezek állíthatók be: {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: egy érték legfeljebb {MAX_ENV_BYTES} betűből, számjegyből és _ . - @ jelből áll
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: adjon meg 0 és {MAX_SLEEP_MS} közötti ezredmásodperc-számot
@msg $.sleep: give a number of milliseconds $.sleep: adjon meg egy ezredmásodperc-számot
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: egy futás nem várakozhat beépített függvény visszahívásában, getterben, átalakításban vagy a $.evalFile által futtatott fájlban; hívja a parancsfájl saját kódjából
@msg $.bp: scripts here have no debugger $.bp: a parancsfájlokhoz itt nincs hibakereső
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: a parancsfájlok még nem tudnak párbeszédpanelt megjeleníteni
@msg {name}: give a message {name}: adjon meg egy üzenetet
@msg {name}: give the text the field starts with {name}: adja meg a szöveget, amellyel a mező kezdődik
@msg {name}: the message is longer than 16 KiB {name}: az üzenet hosszabb 16 KiB-nál
@msg {name}: the title is longer than 256 bytes {name}: a cím hosszabb 256 bájtnál
@msg {name}: the text the field starts with is longer than 16 KiB {name}: a szöveg, amellyel a mező kezdődik, hosszabb 16 KiB-nál
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: párbeszédpanel nem nyílhat meg beépített függvény visszahívásában, getterben, átalakításban vagy a $.evalFile által futtatott fájlban; hívja a parancsfájl saját kódjából
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: a következő válasz az `answers` listában ehhez tartozik: {_1}, nem ehhez: {name}
@msg {name}: `answers` has no answer left for this dialog {name}: az `answers` listában nem maradt válasz ehhez a párbeszédpanelhez
@msg vc.document{place} is too large for a script a vc.document{place} túl nagy egy parancsfájlhoz
@msg vc.log: the log of this run is full vc.log: ennek a futásnak a naplója megtelt
@msg this function's script run has ended ennek a függvénynek a parancsfájl-futása véget ért
@msg the script made more host calls than one run may make a parancsfájl több gazdahívást végzett, mint amennyit egy futás végezhet
@msg the script passed more data to and from commands than one run may pass a parancsfájl több adatot adott át a parancsoknak és a parancsoktól, mint amennyit egy futás átadhat
@msg the script added more objects and data to the documents than one run may add a parancsfájl több objektumot és adatot adott a dokumentumokhoz, mint amennyit egy futás hozzáadhat
@msg {what}: the object is not a File or a Folder {what}: az objektum nem File és nem Folder
@msg {what}: the count must be a finite number, 0 or more {what}: a darabszámnak véges számnak kell lennie, 0 vagy több
@msg File.seek: the position must be a finite number File.seek: a pozíciónak véges számnak kell lennie
@msg File.seek: the mode must be 0, 1 or 2 File.seek: a mód csak 0, 1 vagy 2 lehet
@msg script file is compiled: {value} a parancsfájl le van fordítva: {value}
@msg `name` must be the name of a script engine a `name` értékének egy parancsfájlmotor nevének kell lennie
@msg the main script engine is new for each run and is never kept, so it cannot be dropped a fő parancsfájlmotor minden futáshoz új, és sosem marad meg, ezért nem dobható el
@msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor
@msg Running a script Parancsfájl futtatása
@msg Copied the script report Szkriptjelentés másolva
@msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -1494,6 +1494,8 @@ lighting Light Cahaya
Leading Leading
No Break Tanpa pemenggalan
Proportional Metrics Metrik proporsional
Insert Aki Left Sisipkan aki kiri
Insert Aki Right Sisipkan aki kanan
Character Direction Arah karakter
Digits Digit
Arabic Arab
@@ -1513,6 +1515,7 @@ digits Malayalam Malayalam
Select a text object to edit its character attributes. Pilih objek teks untuk mengedit atribut karakternya.
Show Options Tampilkan opsi
Show Recent Colors Tampilkan warna terbaru
Toggle RGB Percent Alihkan RGB dalam persen
Small Caps Kapital kecil
Small Caps (on the roadmap) Kapital kecil (masih dalam roadmap)
Standard Vertical Roman Alignment Perataan Romawi vertikal standar
@@ -2658,6 +2661,8 @@ digits Malayalam Malayalam
Randomly change saturation and brightness Ubah saturasi dan kecerahan secara acak
Recolor this row Warnai ulang baris ini
Reset the rows to the artwork's colors Setel ulang baris ke warna karya seni
Color Theme Picker Pemilih tema warna
Click or drag across the art to pick its colors; Shift adds more Klik atau seret melintasi karya seni untuk mengambil warnanya; Shift menambahkan lagi
Separate colors into rows Pisahkan warna ke dalam baris
Unlink harmony colors Lepaskan tautan warna harmoni
1 Color Job Pekerjaan 1 warna
Can't render this file because it contains an unexpected character in line 2406 and column 5.
+84
View File
@@ -2663,6 +2663,8 @@ mark-style Japanese Giapponese
Proof Setup Impostazione prova
Properties Proprietà
Proportional Metrics Metrica proporzionale
Insert Aki Left Inserisci aki a sinistra
Insert Aki Right Inserisci aki a destra
Character Direction Direzione caratteri
Digits Cifre
Arabic Arabe
@@ -2937,6 +2939,8 @@ digits Malayalam Malayalam
Reset Rotate View Reimposta rotazione vista
Rotate View to Selection Ruota vista in base alla selezione
Reset the rows to the artwork's colors Reimposta le righe sui colori della grafica
Color Theme Picker Selettore tema colore
Click or drag across the art to pick its colors; Shift adds more Fai clic o trascina sulla grafica per prelevarne i colori; Maiusc ne aggiunge altri
Reset to Default Reimposta valori predefiniti
Reset to White, Black Reimposta su bianco, nero
Reset with Mesh Reimposta con trama
@@ -3346,6 +3350,7 @@ digits Malayalam Malayalam
Show Note Mostra nota
Show Options Mostra opzioni
Show Recent Colors Mostra colori recenti
Toggle RGB Percent Alterna RGB in percentuale
Show Original Path Mostra tracciato originale
Open this dialog with these settings next time Apri questa finestra di dialogo con queste impostazioni la prossima volta
Auto-Simplify Semplifica automaticamente
@@ -4262,6 +4267,85 @@ axis Both Entrambi
@msg the script's run is no longer available l'esecuzione dello script non è più disponibile
@msg a failed command changed undo steps that could not be put back, so the script was stopped un comando non riuscito ha modificato passaggi di annullamento che non è stato possibile ripristinare, quindi lo script è stato interrotto
@msg a recovery copy could not be written, so the script was not run non è stato possibile scrivere una copia di recupero, quindi lo script non è stato eseguito
@msg Script file access denied Accesso al file di script negato
@msg Script file exceeds 8 MiB Il file di script supera 8 MiB
@msg Script file is not open Il file di script non è aperto
@msg Script file cannot be decoded Impossibile decodificare il file di script
@msg Script file is not a regular file Il file di script non è un file normale
@msg Script file does not exist Il file di script non esiste
@msg Script file could not be read Impossibile leggere il file di script
@msg Script folder has more than 2,048 entries La cartella di script contiene più di 2.048 voci
@msg Script file open mode must be r, w, e or a La modalità di apertura del file di script deve essere r, w, e oppure a
@msg Script file writing is not available La scrittura dei file di script non è disponibile
@msg Script file dialogs are not available Le finestre di dialogo dei file di script non sono disponibili
@msg Script files cannot be opened in another application I file di script non possono essere aperti in un'altra applicazione
@msg Script file access is unavailable on the web L'accesso ai file di script non è disponibile sul web
@msg Script has 256 files open Lo script ha 256 file aperti
@msg Script file path exceeds 32,767 characters Il percorso del file di script supera 32.767 caratteri
@msg Script folder mask takes too many steps to match La maschera della cartella di script richiede troppi passaggi per la corrispondenza
@msg the script opened more file data than one run may open (32 MiB) lo script ha aperto più dati di file di quanti ne possa aprire un'esecuzione (32 MiB)
@msg File.seek: takes a position and a mode File.seek: accetta una posizione e una modalità
@msg vc.run: give a command id, as a string vc.run: indica un id di comando, come stringa
@msg vc.run: takes a command id and an object of parameters vc.run: accetta un id di comando e un oggetto di parametri
@msg vc.run: the parameters must be an object vc.run: i parametri devono essere un oggetto
@msg vc.run: the result{place} is too large for a script vc.run: il risultato{place} è troppo grande per uno script
@msg $.evalFile requires a file path $.evalFile richiede un percorso di file
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: il timeout deve essere un numero finito di millisecondi, 0 o più
@msg $.evalFile: takes a file path and a timeout $.evalFile: accetta un percorso di file e un timeout
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: riga {line}, colonna {column} di {file}: {e} (generato)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: riga {line}, colonna {column}: {e} (generato)
@msg {name}: {e} (thrown) {name}: {e} (generato)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: riga {line}, colonna {column} di {file}: {e} (limite)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: riga {line}, colonna {column}: {e} (limite)
@msg {name}: {e} (limit) {name}: {e} (limite)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: riga {line}, colonna {column} di {file}: {e} (errore di sintassi)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: riga {line}, colonna {column}: {e} (errore di sintassi)
@msg {name}: {e} (syntax) {name}: {e} (errore di sintassi)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: riga {line}, colonna {column} di {file}: {e} (interrotto)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: riga {line}, colonna {column}: {e} (interrotto)
@msg {name}: {e} (stopped) {name}: {e} (interrotto)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: riga {line}, colonna {column} di {file}: {e} (errore interno)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: riga {line}, colonna {column}: {e} (errore interno)
@msg {name}: {e} (internal) {name}: {e} (errore interno)
@msg {e} (these files stay written: {paths}) {e} (questi file restano scritti: {paths})
@msg $.{name}: give a name, as a string $.{name}: indica un nome, come stringa
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: indica una impostazione locale come "en" o "de_DE", oppure null per quella dell'interfaccia
@msg $.localize: give true or false $.localize: indica true o false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: si può impostare solo 512, che attiva la localizzazione, oppure 0
@msg $.flags: give a number $.flags: indica un numero
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: qui gli script leggono e scrivono solo UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: indica il nome di una codifica, come stringa
@msg $.memCache: the memory cache size cannot be set $.memCache: la dimensione della cache di memoria non può essere impostata
@msg $.setenv: give a value, as a string $.setenv: indica un valore, come stringa
@msg $.setenv: only {_1} can be set $.setenv: si possono impostare solo {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: un valore ha al massimo {MAX_ENV_BYTES} lettere, cifre e _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: indica un numero di millisecondi da 0 a {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: indica un numero di millisecondi
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: un'esecuzione non può attendere dentro un callback di una funzione integrata, un getter, una conversione o un file eseguito da $.evalFile; chiamala dal codice dello script stesso
@msg $.bp: scripts here have no debugger $.bp: qui gli script non hanno un debugger
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: gli script non possono ancora mostrare una finestra di dialogo
@msg {name}: give a message {name}: indica un messaggio
@msg {name}: give the text the field starts with {name}: indica il testo con cui inizia il campo
@msg {name}: the message is longer than 16 KiB {name}: il messaggio supera 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: il titolo supera 256 byte
@msg {name}: the text the field starts with is longer than 16 KiB {name}: il testo con cui inizia il campo supera 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: una finestra di dialogo non può aprirsi dentro un callback di una funzione integrata, un getter, una conversione o un file eseguito da $.evalFile; chiamala dal codice dello script stesso
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la prossima risposta in `answers` è per {_1}, non per {name}
@msg {name}: `answers` has no answer left for this dialog {name}: in `answers` non rimangono risposte per questa finestra di dialogo
@msg vc.document{place} is too large for a script vc.document{place} è troppo grande per uno script
@msg vc.log: the log of this run is full vc.log: il registro di questa esecuzione è pieno
@msg this function's script run has ended l'esecuzione dello script di questa funzione è terminata
@msg the script made more host calls than one run may make lo script ha fatto più chiamate all'host di quante ne possa fare un'esecuzione
@msg the script passed more data to and from commands than one run may pass lo script ha passato ai comandi e dai comandi più dati di quanti ne possa passare un'esecuzione
@msg the script added more objects and data to the documents than one run may add lo script ha aggiunto ai documenti più oggetti e dati di quanti ne possa aggiungere un'esecuzione
@msg {what}: the object is not a File or a Folder {what}: l'oggetto non è un File né un Folder
@msg {what}: the count must be a finite number, 0 or more {what}: il conteggio deve essere un numero finito, 0 o più
@msg File.seek: the position must be a finite number File.seek: la posizione deve essere un numero finito
@msg File.seek: the mode must be 0, 1 or 2 File.seek: la modalità deve essere 0, 1 o 2
@msg script file is compiled: {value} il file di script è compilato: {value}
@msg `name` must be the name of a script engine `name` deve essere il nome di un motore di script
@msg the main script engine is new for each run and is never kept, so it cannot be dropped il motore di script principale è nuovo a ogni esecuzione e non viene mai conservato, quindi non può essere eliminato
@msg there is no script engine named {name} non esiste un motore di script chiamato {name}
@msg Running a script Esecuzione di uno script
@msg Copied the script report Rapporto dello script copiato
@msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -50,6 +50,8 @@ font-technology Variable バリアブル
x-Height x ハイト
ICF Box 平均字面
Proportional Metrics プロポーショナルメトリクス
Insert Aki Left 前にアキを挿入
Insert Aki Right 後ろにアキを挿入
Character Direction 文字の方向
Digits 数字
Arabic アラビア数字
@@ -2942,6 +2944,8 @@ mark-style Japanese 日本式
Edit Arrowheads… 矢印を編集…
Reload Arrowheads 矢印を再読み込み
Reset the rows to the artwork's colors 行をアートワークのカラーにリセット
Color Theme Picker カラーテーマピッカー
Click or drag across the art to pick its colors; Shift adds more アートワークをクリックまたはドラッグしてカラーを取得します。Shift キーで追加します
Reset to Default 初期設定に戻す
Reset to White, Black 白、黒にリセット
Reset {name} {name}をリセット
@@ -3166,6 +3170,7 @@ mark-style Japanese 日本式
Show Note メモを表示
Show Options オプションを表示
Show Recent Colors 最近使用したカラーを表示
Toggle RGB Percent RGB のパーセント表示を切り替え
Show Original Path 元のパスを表示
Open this dialog with these settings next time 次回はこの設定でこのダイアログを開く
Auto-Simplify 自動単純化
@@ -5011,6 +5016,85 @@ swatch Bright Violet ビビッドバイオレット
@msg the script's run is no longer available スクリプトの実行は利用できなくなりました
@msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗したコマンドが元に戻せない取り消し手順を変更したため、スクリプトを停止しました
@msg a recovery copy could not be written, so the script was not run 復元用のコピーを書き込めなかったため、スクリプトは実行されませんでした
@msg Script file access denied スクリプトファイルへのアクセスが拒否されました
@msg Script file exceeds 8 MiB スクリプトファイルが 8 MiB を超えています
@msg Script file is not open スクリプトファイルが開かれていません
@msg Script file cannot be decoded スクリプトファイルをデコードできません
@msg Script file is not a regular file スクリプトファイルが通常のファイルではありません
@msg Script file does not exist スクリプトファイルが存在しません
@msg Script file could not be read スクリプトファイルを読み込めませんでした
@msg Script folder has more than 2,048 entries スクリプトフォルダーの項目が 2,048 を超えています
@msg Script file open mode must be r, w, e or a スクリプトファイルを開くモードは r、w、e、a のいずれかにしてください
@msg Script file writing is not available スクリプトファイルの書き込みは利用できません
@msg Script file dialogs are not available スクリプトファイルのダイアログは利用できません
@msg Script files cannot be opened in another application スクリプトファイルを別のアプリケーションで開くことはできません
@msg Script file access is unavailable on the web Web ではスクリプトファイルにアクセスできません
@msg Script has 256 files open スクリプトが 256 個のファイルを開いています
@msg Script file path exceeds 32,767 characters スクリプトファイルのパスが 32,767 文字を超えています
@msg Script folder mask takes too many steps to match スクリプトフォルダーのマスクの照合に必要な手順が多すぎます
@msg the script opened more file data than one run may open (32 MiB) スクリプトが 1 回の実行で開ける量 (32 MiB) を超えるファイルデータを開きました
@msg File.seek: takes a position and a mode File.seek: 位置とモードを指定します
@msg vc.run: give a command id, as a string vc.run: コマンド ID を文字列で指定してください
@msg vc.run: takes a command id and an object of parameters vc.run: コマンド ID とパラメーターのオブジェクトを指定します
@msg vc.run: the parameters must be an object vc.run: パラメーターはオブジェクトにしてください
@msg vc.run: the result{place} is too large for a script vc.run: 結果 {place} がスクリプトには大きすぎます
@msg $.evalFile requires a file path $.evalFile にはファイルパスが必要です
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: タイムアウトは 0 以上の有限のミリ秒数にしてください
@msg $.evalFile: takes a file path and a timeout $.evalFile: ファイルパスとタイムアウトを指定します
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file} の {line} 行目、{column} 列目: {e} (スロー)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line} 行目、{column} 列目: {e} (スロー)
@msg {name}: {e} (thrown) {name}: {e} (スロー)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: {file} の {line} 行目、{column} 列目: {e} (上限)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: {line} 行目、{column} 列目: {e} (上限)
@msg {name}: {e} (limit) {name}: {e} (上限)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: {file} の {line} 行目、{column} 列目: {e} (構文エラー)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: {line} 行目、{column} 列目: {e} (構文エラー)
@msg {name}: {e} (syntax) {name}: {e} (構文エラー)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: {file} の {line} 行目、{column} 列目: {e} (停止)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: {line} 行目、{column} 列目: {e} (停止)
@msg {name}: {e} (stopped) {name}: {e} (停止)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: {file} の {line} 行目、{column} 列目: {e} (内部エラー)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: {line} 行目、{column} 列目: {e} (内部エラー)
@msg {name}: {e} (internal) {name}: {e} (内部エラー)
@msg {e} (these files stay written: {paths}) {e} (これらのファイルは書き込まれたままです: {paths})
@msg $.{name}: give a name, as a string $.{name}: 名前を文字列で指定してください
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: "en" や "de_DE" などのロケールを指定するか、インターフェイスのロケールには null を指定してください
@msg $.localize: give true or false $.localize: true または false を指定してください
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: 設定できるのはローカライズをオンにする 512 か 0 だけです
@msg $.flags: give a number $.flags: 数値を指定してください
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: ここではスクリプトは UTF-8 のみを読み書きします
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: エンコーディング名を文字列で指定してください
@msg $.memCache: the memory cache size cannot be set $.memCache: メモリーキャッシュのサイズは設定できません
@msg $.setenv: give a value, as a string $.setenv: 値を文字列で指定してください
@msg $.setenv: only {_1} can be set $.setenv: 設定できるのは {_1} だけです
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: 値は最大 {MAX_ENV_BYTES} 文字の英字、数字、_ . - @ です
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: 0 から {MAX_SLEEP_MS} までのミリ秒数を指定してください
@msg $.sleep: give a number of milliseconds $.sleep: ミリ秒数を指定してください
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: 組み込み関数のコールバック、getter、変換、または $.evalFile が実行するファイルの中では実行を待機できません。スクリプト自身のコードから呼び出してください
@msg $.bp: scripts here have no debugger $.bp: ここではスクリプトにデバッガーはありません
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: スクリプトはまだダイアログを表示できません
@msg {name}: give a message {name}: メッセージを指定してください
@msg {name}: give the text the field starts with {name}: フィールドの初期テキストを指定してください
@msg {name}: the message is longer than 16 KiB {name}: メッセージが 16 KiB を超えています
@msg {name}: the title is longer than 256 bytes {name}: タイトルが 256 バイトを超えています
@msg {name}: the text the field starts with is longer than 16 KiB {name}: フィールドの初期テキストが 16 KiB を超えています
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 組み込み関数のコールバック、getter、変換、または $.evalFile が実行するファイルの中ではダイアログを開けません。スクリプト自身のコードから呼び出してください
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` の次の回答は {name} ではなく {_1} のものです
@msg {name}: `answers` has no answer left for this dialog {name}: `answers` にこのダイアログの回答が残っていません
@msg vc.document{place} is too large for a script vc.document{place} はスクリプトには大きすぎます
@msg vc.log: the log of this run is full vc.log: この実行のログがいっぱいです
@msg this function's script run has ended この関数のスクリプトの実行は終了しています
@msg the script made more host calls than one run may make スクリプトが 1 回の実行で許されるより多くのホスト呼び出しを行いました
@msg the script passed more data to and from commands than one run may pass スクリプトが 1 回の実行で許されるより多くのデータをコマンドとやり取りしました
@msg the script added more objects and data to the documents than one run may add スクリプトが 1 回の実行で許されるより多くのオブジェクトとデータをドキュメントに追加しました
@msg {what}: the object is not a File or a Folder {what}: オブジェクトは File でも Folder でもありません
@msg {what}: the count must be a finite number, 0 or more {what}: 数は 0 以上の有限の数値にしてください
@msg File.seek: the position must be a finite number File.seek: 位置は有限の数値にしてください
@msg File.seek: the mode must be 0, 1 or 2 File.seek: モードは 0, 1 または 2 にしてください
@msg script file is compiled: {value} スクリプトファイルはコンパイル済みです: {value}
@msg `name` must be the name of a script engine `name` はスクリプトエンジンの名前にしてください
@msg the main script engine is new for each run and is never kept, so it cannot be dropped メインのスクリプトエンジンは実行ごとに新しく作られ、保持されないため、破棄できません
@msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません
@msg Running a script スクリプトを実行中
@msg Copied the script report スクリプトのレポートをコピーしました
@msg Exported {path} {path} を書き出しました
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -1431,6 +1431,8 @@ lighting Light სინათლე
Leading სტრიქონთა დაშორება
No Break გადატანის გარეშე
Proportional Metrics პროპორციული მეტრიკა
Insert Aki Left აკის ჩასმა მარცხნივ
Insert Aki Right აკის ჩასმა მარჯვნივ
Character Direction სიმბოლოების მიმართულება
Digits ციფრები
Arabic არაბული
@@ -1451,6 +1453,7 @@ digits Malayalam მალაიალამური
Select a text object to edit its character attributes. სიმბოლოების ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი.
Show Options პარამეტრების ჩვენება
Show Recent Colors ბოლოდროინდელი ფერების ჩვენება
Toggle RGB Percent RGB-ის პროცენტებში ჩვენების გადართვა
Small Caps პატარა მთავრული
Small Caps (on the roadmap) პატარა მთავრული (სამომავლო გეგმაშია)
Standard Vertical Roman Alignment სტანდარტული ვერტიკალური ლათინური სწორება
@@ -2574,6 +2577,8 @@ digits Malayalam მალაიალამური
Randomly change saturation and brightness გაჯერებისა და სიკაშკაშის შემთხვევითი შეცვლა
Recolor this row ამ სტრიქონის ხელახლა შეფერადება
Reset the rows to the artwork's colors სტრიქონებისთვის ნახატის ფერების დაბრუნება
Color Theme Picker ფერთა თემის ამრჩევი
Click or drag across the art to pick its colors; Shift adds more დააწკაპუნეთ ან გადაატარეთ ნახატზე მისი ფერების ასაღებად; Shift ამატებს კიდევ
Separate colors into rows ფერების სტრიქონებად დაყოფა
Unlink harmony colors ჰარმონიის ფერების კავშირის გაწყვეტა
1 Color Job 1-ფერიანი ბეჭდვა
@@ -5349,6 +5354,85 @@ imageTrace Outline კონტური
@msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი
@msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ დაბრუნების ნაბიჯები შეცვალა და მათი პირვანდელ მდგომარეობაში მოყვანა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა
@msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა
@msg Script file access denied სკრიპტის ფაილზე წვდომა აკრძალულია
@msg Script file exceeds 8 MiB სკრიპტის ფაილი 8 MiB-ს აღემატება
@msg Script file is not open სკრიპტის ფაილი გახსნილი არ არის
@msg Script file cannot be decoded სკრიპტის ფაილის დეკოდირება შეუძლებელია
@msg Script file is not a regular file სკრიპტის ფაილი ჩვეულებრივი ფაილი არ არის
@msg Script file does not exist სკრიპტის ფაილი არ არსებობს
@msg Script file could not be read სკრიპტის ფაილის წაკითხვა ვერ მოხერხდა
@msg Script folder has more than 2,048 entries სკრიპტის საქაღალდეში 2048-ზე მეტი ჩანაწერია
@msg Script file open mode must be r, w, e or a სკრიპტის ფაილის გახსნის რეჟიმი უნდა იყოს r, w, e ან a
@msg Script file writing is not available სკრიპტის ფაილების ჩაწერა მიუწვდომელია
@msg Script file dialogs are not available სკრიპტის ფაილის დიალოგები მიუწვდომელია
@msg Script files cannot be opened in another application სკრიპტის ფაილების სხვა აპლიკაციაში გახსნა შეუძლებელია
@msg Script file access is unavailable on the web ვებში სკრიპტის ფაილებზე წვდომა მიუწვდომელია
@msg Script has 256 files open სკრიპტს 256 ფაილი აქვს გახსნილი
@msg Script file path exceeds 32,767 characters სკრიპტის ფაილის მისამართი 32 767 სიმბოლოს აღემატება
@msg Script folder mask takes too many steps to match სკრიპტის საქაღალდის ნიღბის შედარებას ზედმეტად ბევრი ნაბიჯი სჭირდება
@msg the script opened more file data than one run may open (32 MiB) სკრიპტმა გახსნა იმაზე მეტი ფაილის მონაცემი, ვიდრე ერთ გაშვებას შეუძლია (32 MiB)
@msg File.seek: takes a position and a mode File.seek: იღებს პოზიციას და რეჟიმს
@msg vc.run: give a command id, as a string vc.run: მიუთითეთ ბრძანების id სტრიქონის სახით
@msg vc.run: takes a command id and an object of parameters vc.run: იღებს ბრძანების id-ს და პარამეტრების ობიექტს
@msg vc.run: the parameters must be an object vc.run: პარამეტრები უნდა იყოს ობიექტი
@msg vc.run: the result{place} is too large for a script vc.run: შედეგი{place} ზედმეტად დიდია სკრიპტისთვის
@msg $.evalFile requires a file path $.evalFile-ს სჭირდება ფაილის მისამართი
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: დროის ლიმიტი უნდა იყოს მილიწამების სასრული რიცხვი, 0 ან მეტი
@msg $.evalFile: takes a file path and a timeout $.evalFile: იღებს ფაილის მისამართს და დროის ლიმიტს
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, სტრიქონი {line}, სვეტი {column}: {e} (გამონაკლისი)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: სტრიქონი {line}, სვეტი {column}: {e} (გამონაკლისი)
@msg {name}: {e} (thrown) {name}: {e} (გამონაკლისი)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: {file}, სტრიქონი {line}, სვეტი {column}: {e} (ლიმიტი)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: სტრიქონი {line}, სვეტი {column}: {e} (ლიმიტი)
@msg {name}: {e} (limit) {name}: {e} (ლიმიტი)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: {file}, სტრიქონი {line}, სვეტი {column}: {e} (სინტაქსური შეცდომა)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: სტრიქონი {line}, სვეტი {column}: {e} (სინტაქსური შეცდომა)
@msg {name}: {e} (syntax) {name}: {e} (სინტაქსური შეცდომა)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: {file}, სტრიქონი {line}, სვეტი {column}: {e} (შეჩერდა)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: სტრიქონი {line}, სვეტი {column}: {e} (შეჩერდა)
@msg {name}: {e} (stopped) {name}: {e} (შეჩერდა)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: {file}, სტრიქონი {line}, სვეტი {column}: {e} (შიდა შეცდომა)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: სტრიქონი {line}, სვეტი {column}: {e} (შიდა შეცდომა)
@msg {name}: {e} (internal) {name}: {e} (შიდა შეცდომა)
@msg {e} (these files stay written: {paths}) {e} (ეს ფაილები ჩაწერილი რჩება: {paths})
@msg $.{name}: give a name, as a string $.{name}: მიუთითეთ სახელი სტრიქონის სახით
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: მიუთითეთ ლოკალი, მაგალითად "en" ან "de_DE", ან null ინტერფეისის ლოკალისთვის
@msg $.localize: give true or false $.localize: მიუთითეთ true ან false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: შეიძლება დაყენდეს მხოლოდ 512, რომელიც ლოკალიზაციას რთავს, ან 0
@msg $.flags: give a number $.flags: მიუთითეთ რიცხვი
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: აქ სკრიპტები მხოლოდ UTF-8-ს კითხულობენ და წერენ
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: მიუთითეთ კოდირების სახელი სტრიქონის სახით
@msg $.memCache: the memory cache size cannot be set $.memCache: მეხსიერების ქეშის ზომის დაყენება შეუძლებელია
@msg $.setenv: give a value, as a string $.setenv: მიუთითეთ მნიშვნელობა სტრიქონის სახით
@msg $.setenv: only {_1} can be set $.setenv: შეიძლება დაყენდეს მხოლოდ {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: მნიშვნელობაში არის არაუმეტეს {MAX_ENV_BYTES} ასო, ციფრი და _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: მიუთითეთ მილიწამების რაოდენობა 0-დან {MAX_SLEEP_MS}-მდე
@msg $.sleep: give a number of milliseconds $.sleep: მიუთითეთ მილიწამების რაოდენობა
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: გაშვებას არ შეუძლია ლოდინი ჩაშენებული ფუნქციის უკუძახილში, getter-ში, გარდაქმნაში ან ფაილში, რომელსაც $.evalFile უშვებს; გამოიძახეთ ის სკრიპტის საკუთარი კოდიდან
@msg $.bp: scripts here have no debugger $.bp: აქ სკრიპტებს გამმართველი არ აქვთ
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: სკრიპტებს ჯერ არ შეუძლიათ დიალოგის ჩვენება
@msg {name}: give a message {name}: მიუთითეთ შეტყობინება
@msg {name}: give the text the field starts with {name}: მიუთითეთ ტექსტი, რომლითაც ველი იწყება
@msg {name}: the message is longer than 16 KiB {name}: შეტყობინება 16 KiB-ზე გრძელია
@msg {name}: the title is longer than 256 bytes {name}: სათაური 256 ბაიტზე გრძელია
@msg {name}: the text the field starts with is longer than 16 KiB {name}: ტექსტი, რომლითაც ველი იწყება, 16 KiB-ზე გრძელია
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: დიალოგი ვერ გაიხსნება ჩაშენებული ფუნქციის უკუძახილში, getter-ში, გარდაქმნაში ან ფაილში, რომელსაც $.evalFile უშვებს; გამოიძახეთ ის სკრიპტის საკუთარი კოდიდან
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: შემდეგი პასუხი `answers`-ში არის {_1}-ისთვის და არა {name}-ისთვის
@msg {name}: `answers` has no answer left for this dialog {name}: `answers`-ში ამ დიალოგისთვის პასუხი აღარ დარჩა
@msg vc.document{place} is too large for a script vc.document{place} ზედმეტად დიდია სკრიპტისთვის
@msg vc.log: the log of this run is full vc.log: ამ გაშვების ჟურნალი სავსეა
@msg this function's script run has ended ამ ფუნქციის სკრიპტის გაშვება დასრულდა
@msg the script made more host calls than one run may make სკრიპტმა იმაზე მეტი მასპინძლის გამოძახება შეასრულა, ვიდრე ერთ გაშვებას შეუძლია
@msg the script passed more data to and from commands than one run may pass სკრიპტმა ბრძანებებს და ბრძანებებიდან იმაზე მეტი მონაცემი გადასცა, ვიდრე ერთ გაშვებას შეუძლია
@msg the script added more objects and data to the documents than one run may add სკრიპტმა დოკუმენტებს იმაზე მეტი ობიექტი და მონაცემი დაამატა, ვიდრე ერთ გაშვებას შეუძლია
@msg {what}: the object is not a File or a Folder {what}: ობიექტი არც File-ია და არც Folder
@msg {what}: the count must be a finite number, 0 or more {what}: რაოდენობა უნდა იყოს სასრული რიცხვი, 0 ან მეტი
@msg File.seek: the position must be a finite number File.seek: პოზიცია უნდა იყოს სასრული რიცხვი
@msg File.seek: the mode must be 0, 1 or 2 File.seek: რეჟიმი უნდა იყოს 0, 1 ან 2
@msg script file is compiled: {value} სკრიპტის ფაილი კომპილირებულია: {value}
@msg `name` must be the name of a script engine `name` უნდა იყოს სკრიპტის ძრავის სახელი
@msg the main script engine is new for each run and is never kept, so it cannot be dropped მთავარი სკრიპტის ძრავა ყოველი გაშვებისთვის ახალია და არასოდეს ინახება, ამიტომ მისი მოცილება შეუძლებელია
@msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს
@msg Running a script სკრიპტი მუშაობს
@msg Copied the script report კოპირებულია სკრიპტის ანგარიში
@msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია)
Can't render this file because it is too large.
+84
View File
@@ -44,6 +44,8 @@ font-technology Variable 가변
x-Height x 높이
ICF Box ICF 박스
Proportional Metrics 비례 메트릭
Insert Aki Left 앞 아키 삽입
Insert Aki Right 뒤 아키 삽입
Character Direction 문자 방향
Digits 숫자
Arabic 아라비아어
@@ -2931,6 +2933,8 @@ mark-style Japanese 일본식
Edit Arrowheads… 화살촉 편집…
Reload Arrowheads 화살촉 다시 불러오기
Reset the rows to the artwork's colors 행을 아트웍 색상으로 재설정
Color Theme Picker 색상 테마 피커
Click or drag across the art to pick its colors; Shift adds more 아트웍을 클릭하거나 드래그하여 색상을 가져옵니다. Shift 키로 더 추가합니다
Reset to Default 기본값으로 재설정
Reset to White, Black 흰색, 검정으로 재설정
Reset {name} {name} 재설정
@@ -3155,6 +3159,7 @@ mark-style Japanese 일본식
Show Note 메모 표시
Show Options 옵션 표시
Show Recent Colors 최근 색상 표시
Toggle RGB Percent RGB 백분율 표시 전환
Show Original Path 원래 패스 표시
Open this dialog with these settings next time 다음에 이 설정으로 이 대화상자 열기
Auto-Simplify 자동 단순화
@@ -4938,6 +4943,85 @@ theme Appearance 외관
@msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다
@msg a failed command changed undo steps that could not be put back, so the script was stopped 실패한 명령이 되돌릴 수 없는 실행 취소 단계를 변경하여 스크립트를 중지했습니다
@msg a recovery copy could not be written, so the script was not run 복구 사본을 쓸 수 없어 스크립트를 실행하지 않았습니다
@msg Script file access denied 스크립트 파일 접근이 거부되었습니다
@msg Script file exceeds 8 MiB 스크립트 파일이 8 MiB를 초과합니다
@msg Script file is not open 스크립트 파일이 열려 있지 않습니다
@msg Script file cannot be decoded 스크립트 파일을 디코딩할 수 없습니다
@msg Script file is not a regular file 스크립트 파일이 일반 파일이 아닙니다
@msg Script file does not exist 스크립트 파일이 없습니다
@msg Script file could not be read 스크립트 파일을 읽을 수 없습니다
@msg Script folder has more than 2,048 entries 스크립트 폴더의 항목이 2,048개를 초과합니다
@msg Script file open mode must be r, w, e or a 스크립트 파일 열기 모드는 r, w, e 또는 a여야 합니다
@msg Script file writing is not available 스크립트 파일 쓰기를 사용할 수 없습니다
@msg Script file dialogs are not available 스크립트 파일 대화 상자를 사용할 수 없습니다
@msg Script files cannot be opened in another application 스크립트 파일을 다른 응용 프로그램에서 열 수 없습니다
@msg Script file access is unavailable on the web 웹에서는 스크립트 파일에 접근할 수 없습니다
@msg Script has 256 files open 스크립트가 파일 256개를 열고 있습니다
@msg Script file path exceeds 32,767 characters 스크립트 파일 경로가 32,767자를 초과합니다
@msg Script folder mask takes too many steps to match 스크립트 폴더 마스크를 일치시키는 데 단계가 너무 많이 필요합니다
@msg the script opened more file data than one run may open (32 MiB) 스크립트가 한 번의 실행에서 열 수 있는 것보다 많은 파일 데이터를 열었습니다(32 MiB)
@msg File.seek: takes a position and a mode File.seek: 위치와 모드를 받습니다
@msg vc.run: give a command id, as a string vc.run: 명령 id를 문자열로 지정하세요
@msg vc.run: takes a command id and an object of parameters vc.run: 명령 id와 매개변수 객체를 받습니다
@msg vc.run: the parameters must be an object vc.run: 매개변수는 객체여야 합니다
@msg vc.run: the result{place} is too large for a script vc.run: 결과{place}이(가) 스크립트에 비해 너무 큽니다
@msg $.evalFile requires a file path $.evalFile에는 파일 경로가 필요합니다
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: 시간 제한은 0 이상의 유한한 밀리초 수여야 합니다
@msg $.evalFile: takes a file path and a timeout $.evalFile: 파일 경로와 시간 제한을 받습니다
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}의 {line}행 {column}열: {e} (발생)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line}행 {column}열: {e} (발생)
@msg {name}: {e} (thrown) {name}: {e} (발생)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: {file}의 {line}행 {column}열: {e} (제한)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: {line}행 {column}열: {e} (제한)
@msg {name}: {e} (limit) {name}: {e} (제한)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: {file}의 {line}행 {column}열: {e} (구문 오류)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: {line}행 {column}열: {e} (구문 오류)
@msg {name}: {e} (syntax) {name}: {e} (구문 오류)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: {file}의 {line}행 {column}열: {e} (중지됨)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: {line}행 {column}열: {e} (중지됨)
@msg {name}: {e} (stopped) {name}: {e} (중지됨)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: {file}의 {line}행 {column}열: {e} (내부 오류)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: {line}행 {column}열: {e} (내부 오류)
@msg {name}: {e} (internal) {name}: {e} (내부 오류)
@msg {e} (these files stay written: {paths}) {e} (이 파일은 쓰인 상태로 남습니다: {paths})
@msg $.{name}: give a name, as a string $.{name}: 이름을 문자열로 지정하세요
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: "en" 또는 "de_DE" 같은 로캘을 지정하거나, 인터페이스 로캘에는 null을 지정하세요
@msg $.localize: give true or false $.localize: true 또는 false를 지정하세요
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: 현지화를 켜는 512 또는 0만 설정할 수 있습니다
@msg $.flags: give a number $.flags: 숫자를 지정하세요
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: 여기서 스크립트는 UTF-8만 읽고 씁니다
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: 인코딩 이름을 문자열로 지정하세요
@msg $.memCache: the memory cache size cannot be set $.memCache: 메모리 캐시 크기는 설정할 수 없습니다
@msg $.setenv: give a value, as a string $.setenv: 값을 문자열로 지정하세요
@msg $.setenv: only {_1} can be set $.setenv: {_1}만 설정할 수 있습니다
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: 값은 최대 {MAX_ENV_BYTES}자의 문자, 숫자 및 _ . - @입니다
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: 0부터 {MAX_SLEEP_MS}까지의 밀리초 수를 지정하세요
@msg $.sleep: give a number of milliseconds $.sleep: 밀리초 수를 지정하세요
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: 기본 제공 함수의 콜백, getter, 변환 또는 $.evalFile이 실행하는 파일 안에서는 실행이 기다릴 수 없습니다. 스크립트 자체 코드에서 호출하세요
@msg $.bp: scripts here have no debugger $.bp: 여기서는 스크립트에 디버거가 없습니다
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: 스크립트는 아직 대화 상자를 표시할 수 없습니다
@msg {name}: give a message {name}: 메시지를 지정하세요
@msg {name}: give the text the field starts with {name}: 필드의 시작 텍스트를 지정하세요
@msg {name}: the message is longer than 16 KiB {name}: 메시지가 16 KiB보다 깁니다
@msg {name}: the title is longer than 256 bytes {name}: 제목이 256바이트보다 깁니다
@msg {name}: the text the field starts with is longer than 16 KiB {name}: 필드의 시작 텍스트가 16 KiB보다 깁니다
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 기본 제공 함수의 콜백, getter, 변환 또는 $.evalFile이 실행하는 파일 안에서는 대화 상자를 열 수 없습니다. 스크립트 자체 코드에서 호출하세요
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers`의 다음 답은 {name}이(가) 아니라 {_1}에 대한 것입니다
@msg {name}: `answers` has no answer left for this dialog {name}: `answers`에 이 대화 상자에 대한 답이 남아 있지 않습니다
@msg vc.document{place} is too large for a script vc.document{place}이(가) 스크립트에 비해 너무 큽니다
@msg vc.log: the log of this run is full vc.log: 이 실행의 로그가 가득 찼습니다
@msg this function's script run has ended 이 함수의 스크립트 실행이 끝났습니다
@msg the script made more host calls than one run may make 스크립트가 한 번의 실행에 허용된 것보다 많은 호스트 호출을 했습니다
@msg the script passed more data to and from commands than one run may pass 스크립트가 한 번의 실행에 허용된 것보다 많은 데이터를 명령과 주고받았습니다
@msg the script added more objects and data to the documents than one run may add 스크립트가 한 번의 실행에 허용된 것보다 많은 객체와 데이터를 문서에 추가했습니다
@msg {what}: the object is not a File or a Folder {what}: 객체가 File도 Folder도 아닙니다
@msg {what}: the count must be a finite number, 0 or more {what}: 개수는 0 이상의 유한한 숫자여야 합니다
@msg File.seek: the position must be a finite number File.seek: 위치는 유한한 숫자여야 합니다
@msg File.seek: the mode must be 0, 1 or 2 File.seek: 모드는 0, 1 또는 2여야 합니다
@msg script file is compiled: {value} 스크립트 파일이 컴파일되어 있습니다: {value}
@msg `name` must be the name of a script engine `name`은(는) 스크립트 엔진의 이름이어야 합니다
@msg the main script engine is new for each run and is never kept, so it cannot be dropped 기본 스크립트 엔진은 실행마다 새로 만들어지고 유지되지 않으므로 삭제할 수 없습니다
@msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다
@msg Running a script 스크립트 실행 중
@msg Copied the script report 스크립트 보고서를 복사했습니다
@msg Exported {path} {path}을(를) 내보냈습니다
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -1508,6 +1508,8 @@ lighting Light Licht
Leading Regelafstand
No Break Niet afbreken
Proportional Metrics Proportionele metingen
Insert Aki Left Aki links invoegen
Insert Aki Right Aki rechts invoegen
Character Direction Tekenrichting
Digits Cijfers
Arabic Arabisch
@@ -1527,6 +1529,7 @@ digits Malayalam Malayalam
Select a text object to edit its character attributes. Selecteer een tekstobject om de tekenkenmerken ervan te bewerken.
Show Options Opties tonen
Show Recent Colors Recente kleuren tonen
Toggle RGB Percent RGB in procenten wisselen
Small Caps Kleine kapitalen
Small Caps (on the roadmap) Kleine kapitalen (op de roadmap)
Standard Vertical Roman Alignment Standaard verticale Romeinse uitlijning
@@ -2672,6 +2675,8 @@ digits Malayalam Malayalam
Randomly change saturation and brightness Verzadiging en helderheid willekeurig wijzigen
Recolor this row Deze rij opnieuw kleuren
Reset the rows to the artwork's colors De rijen herstellen naar de kleuren van de artwork
Color Theme Picker Kleurthemakiezer
Click or drag across the art to pick its colors; Shift adds more Klik of sleep over het artwork om de kleuren ervan op te nemen; Shift voegt er meer toe
Separate colors into rows Kleuren over rijen verdelen
Unlink harmony colors Harmoniekleuren ontkoppelen
1 Color Job Opdracht in 1 kleur
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -1499,6 +1499,8 @@ lighting Light Światło
Leading Interlinia
No Break Bez podziału
Proportional Metrics Metryka proporcjonalna
Insert Aki Left Wstaw aki z lewej
Insert Aki Right Wstaw aki z prawej
Character Direction Kierunek znaków
Digits Cyfry
Arabic Arabskie
@@ -1518,6 +1520,7 @@ digits Malayalam Malajalam
Select a text object to edit its character attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty znaków.
Show Options Pokaż opcje
Show Recent Colors Pokaż ostatnie kolory
Toggle RGB Percent Przełącz RGB w procentach
Color Panel Options Opcje panelu Kolor
Small Caps Kapitaliki
Small Caps (on the roadmap) Kapitaliki (w planach)
@@ -2783,6 +2786,8 @@ digits Malayalam Malajalam
Randomly change saturation and brightness Losowo zmień nasycenie i jasność
Recolor this row Zmień kolory tego wiersza
Reset the rows to the artwork's colors Przywróć w wierszach kolory kompozycji
Color Theme Picker Próbnik motywu kolorów
Click or drag across the art to pick its colors; Shift adds more Kliknij lub przeciągnij po kompozycji, aby pobrać jej kolory; Shift dodaje kolejne
Separate colors into rows Rozdziel kolory na wiersze
Unlink harmony colors Odłącz kolory harmonii
1 Color Job Praca 1-kolorowa
@@ -4344,6 +4349,85 @@ imageTrace Outline Kontur
@msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne
@msg a failed command changed undo steps that could not be put back, so the script was stopped nieudane polecenie zmieniło kroki cofania, których nie udało się przywrócić, więc skrypt został zatrzymany
@msg a recovery copy could not be written, so the script was not run nie udało się zapisać kopii odzyskiwania, więc skrypt nie został uruchomiony
@msg Script file access denied Odmowa dostępu do pliku skryptu
@msg Script file exceeds 8 MiB Plik skryptu przekracza 8 MiB
@msg Script file is not open Plik skryptu nie jest otwarty
@msg Script file cannot be decoded Nie można zdekodować pliku skryptu
@msg Script file is not a regular file Plik skryptu nie jest zwykłym plikiem
@msg Script file does not exist Plik skryptu nie istnieje
@msg Script file could not be read Nie udało się odczytać pliku skryptu
@msg Script folder has more than 2,048 entries Folder skryptu ma więcej niż 2048 pozycji
@msg Script file open mode must be r, w, e or a Tryb otwarcia pliku skryptu musi być r, w, e lub a
@msg Script file writing is not available Zapisywanie plików skryptu jest niedostępne
@msg Script file dialogs are not available Okna dialogowe plików skryptu są niedostępne
@msg Script files cannot be opened in another application Plików skryptu nie można otworzyć w innej aplikacji
@msg Script file access is unavailable on the web Dostęp do plików skryptu jest niedostępny w przeglądarce
@msg Script has 256 files open Skrypt ma otwartych 256 plików
@msg Script file path exceeds 32,767 characters Ścieżka pliku skryptu przekracza 32 767 znaków
@msg Script folder mask takes too many steps to match Dopasowanie maski folderu skryptu wymaga zbyt wielu kroków
@msg the script opened more file data than one run may open (32 MiB) skrypt otworzył więcej danych plików, niż może otworzyć jedno uruchomienie (32 MiB)
@msg File.seek: takes a position and a mode File.seek: przyjmuje pozycję i tryb
@msg vc.run: give a command id, as a string vc.run: podaj identyfikator polecenia jako ciąg znaków
@msg vc.run: takes a command id and an object of parameters vc.run: przyjmuje identyfikator polecenia i obiekt parametrów
@msg vc.run: the parameters must be an object vc.run: parametry muszą być obiektem
@msg vc.run: the result{place} is too large for a script vc.run: wynik{place} jest za duży dla skryptu
@msg $.evalFile requires a file path $.evalFile wymaga ścieżki pliku
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: limit czasu musi być skończoną liczbą milisekund, 0 lub więcej
@msg $.evalFile: takes a file path and a timeout $.evalFile: przyjmuje ścieżkę pliku i limit czasu
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: wiersz {line}, kolumna {column} w {file}: {e} (zgłoszony wyjątek)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: wiersz {line}, kolumna {column}: {e} (zgłoszony wyjątek)
@msg {name}: {e} (thrown) {name}: {e} (zgłoszony wyjątek)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: wiersz {line}, kolumna {column} w {file}: {e} (ograniczenie)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: wiersz {line}, kolumna {column}: {e} (ograniczenie)
@msg {name}: {e} (limit) {name}: {e} (ograniczenie)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: wiersz {line}, kolumna {column} w {file}: {e} (błąd składni)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: wiersz {line}, kolumna {column}: {e} (błąd składni)
@msg {name}: {e} (syntax) {name}: {e} (błąd składni)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: wiersz {line}, kolumna {column} w {file}: {e} (zatrzymany)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: wiersz {line}, kolumna {column}: {e} (zatrzymany)
@msg {name}: {e} (stopped) {name}: {e} (zatrzymany)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: wiersz {line}, kolumna {column} w {file}: {e} (błąd wewnętrzny)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: wiersz {line}, kolumna {column}: {e} (błąd wewnętrzny)
@msg {name}: {e} (internal) {name}: {e} (błąd wewnętrzny)
@msg {e} (these files stay written: {paths}) {e} (te pliki pozostają zapisane: {paths})
@msg $.{name}: give a name, as a string $.{name}: podaj nazwę jako ciąg znaków
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: podaj ustawienia regionalne, takie jak "en" lub "de_DE", albo null dla ustawień interfejsu
@msg $.localize: give true or false $.localize: podaj true lub false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: można ustawić tylko 512, które włącza lokalizację, albo 0
@msg $.flags: give a number $.flags: podaj liczbę
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: skrypty odczytują i zapisują tu tylko UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: podaj nazwę kodowania jako ciąg znaków
@msg $.memCache: the memory cache size cannot be set $.memCache: nie można ustawić rozmiaru pamięci podręcznej
@msg $.setenv: give a value, as a string $.setenv: podaj wartość jako ciąg znaków
@msg $.setenv: only {_1} can be set $.setenv: można ustawić tylko {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: wartość ma najwyżej {MAX_ENV_BYTES} liter, cyfr i znaków _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: podaj liczbę milisekund od 0 do {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: podaj liczbę milisekund
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: uruchomienie nie może czekać w wywołaniu zwrotnym funkcji wbudowanej, getterze, konwersji ani pliku uruchamianym przez $.evalFile; wywołaj ją z własnego kodu skryptu
@msg $.bp: scripts here have no debugger $.bp: skrypty nie mają tu debugera
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: skrypty nie mogą jeszcze wyświetlać okna dialogowego
@msg {name}: give a message {name}: podaj komunikat
@msg {name}: give the text the field starts with {name}: podaj tekst, od którego zaczyna się pole
@msg {name}: the message is longer than 16 KiB {name}: komunikat jest dłuższy niż 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: tytuł jest dłuższy niż 256 bajtów
@msg {name}: the text the field starts with is longer than 16 KiB {name}: tekst, od którego zaczyna się pole, jest dłuższy niż 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: okno dialogowe nie może się otworzyć w wywołaniu zwrotnym funkcji wbudowanej, getterze, konwersji ani pliku uruchamianym przez $.evalFile; wywołaj je z własnego kodu skryptu
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: następna odpowiedź w `answers` jest dla {_1}, nie dla {name}
@msg {name}: `answers` has no answer left for this dialog {name}: w `answers` nie została żadna odpowiedź dla tego okna dialogowego
@msg vc.document{place} is too large for a script vc.document{place} jest za duży dla skryptu
@msg vc.log: the log of this run is full vc.log: dziennik tego uruchomienia jest pełny
@msg this function's script run has ended uruchomienie skryptu tej funkcji zakończyło się
@msg the script made more host calls than one run may make skrypt wykonał więcej wywołań hosta, niż może wykonać jedno uruchomienie
@msg the script passed more data to and from commands than one run may pass skrypt przekazał do poleceń i z poleceń więcej danych, niż może przekazać jedno uruchomienie
@msg the script added more objects and data to the documents than one run may add skrypt dodał do dokumentów więcej obiektów i danych, niż może dodać jedno uruchomienie
@msg {what}: the object is not a File or a Folder {what}: obiekt nie jest ani File, ani Folder
@msg {what}: the count must be a finite number, 0 or more {what}: liczba musi być liczbą skończoną, 0 lub większą
@msg File.seek: the position must be a finite number File.seek: pozycja musi być liczbą skończoną
@msg File.seek: the mode must be 0, 1 or 2 File.seek: tryb musi wynosić 0, 1 lub 2
@msg script file is compiled: {value} plik skryptu jest skompilowany: {value}
@msg `name` must be the name of a script engine `name` musi być nazwą silnika skryptów
@msg the main script engine is new for each run and is never kept, so it cannot be dropped główny silnik skryptów jest nowy przy każdym uruchomieniu i nigdy nie jest zachowywany, więc nie można go usunąć
@msg there is no script engine named {name} nie ma silnika skryptów o nazwie {name}
@msg Running a script Uruchamianie skryptu
@msg Copied the script report Skopiowano raport skryptu
@msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki
Can't render this file because it contains an unexpected character in line 2 and column 73.
+84
View File
@@ -2191,6 +2191,8 @@ antiAlias Sharp Nítido
Proof Setup Configuração de Prova
Properties Propriedades
Proportional Metrics Métrica Proporcional
Insert Aki Left Inserir Aki à Esquerda
Insert Aki Right Inserir Aki à Direita
Character Direction Direção de Caracteres
Digits Dígitos
Arabic Arábicos
@@ -2432,6 +2434,8 @@ digits Malayalam Malaiala
Reset Rotate View Redefinir Visualização Girada
Rotate View to Selection Girar Visualização para a Seleção
Reset the rows to the artwork's colors Redefinir as linhas para as cores da arte
Color Theme Picker Seletor de Tema de Cores
Click or drag across the art to pick its colors; Shift adds more Clique ou arraste sobre a arte para pegar suas cores; Shift adiciona mais
Reset to Default Redefinir para o Padrão
Reset to White, Black Redefinir para Branco, Preto
Reset with Mesh… Redefinir com Malha…
@@ -2778,6 +2782,7 @@ digits Malayalam Malaiala
Show Note Mostrar Nota
Show Options Mostrar Opções
Show Recent Colors Mostrar Cores Recentes
Toggle RGB Percent Alternar RGB em Porcentagem
Show Original Path Mostrar Caminho Original
Open this dialog with these settings next time Abrir este diálogo com estas configurações na próxima vez
Auto-Simplify Simplificar Automaticamente
@@ -5218,6 +5223,85 @@ axis Both Ambos
@msg the script's run is no longer available a execução do script não está mais disponível
@msg a failed command changed undo steps that could not be put back, so the script was stopped um comando que falhou alterou etapas de desfazer que não puderam ser restauradas, então o script foi interrompido
@msg a recovery copy could not be written, so the script was not run não foi possível gravar uma cópia de recuperação, portanto o script não foi executado
@msg Script file access denied Acesso ao arquivo de script negado
@msg Script file exceeds 8 MiB O arquivo de script excede 8 MiB
@msg Script file is not open O arquivo de script não está aberto
@msg Script file cannot be decoded Não é possível decodificar o arquivo de script
@msg Script file is not a regular file O arquivo de script não é um arquivo comum
@msg Script file does not exist O arquivo de script não existe
@msg Script file could not be read Não foi possível ler o arquivo de script
@msg Script folder has more than 2,048 entries A pasta de script tem mais de 2.048 entradas
@msg Script file open mode must be r, w, e or a O modo de abertura do arquivo de script deve ser r, w, e ou a
@msg Script file writing is not available A gravação de arquivos de script não está disponível
@msg Script file dialogs are not available As caixas de diálogo de arquivos de script não estão disponíveis
@msg Script files cannot be opened in another application Arquivos de script não podem ser abertos em outro aplicativo
@msg Script file access is unavailable on the web O acesso a arquivos de script não está disponível na web
@msg Script has 256 files open O script tem 256 arquivos abertos
@msg Script file path exceeds 32,767 characters O caminho do arquivo de script excede 32.767 caracteres
@msg Script folder mask takes too many steps to match A máscara de pasta de script exige etapas demais para corresponder
@msg the script opened more file data than one run may open (32 MiB) o script abriu mais dados de arquivo do que uma execução pode abrir (32 MiB)
@msg File.seek: takes a position and a mode File.seek: recebe uma posição e um modo
@msg vc.run: give a command id, as a string vc.run: informe um id de comando, como string
@msg vc.run: takes a command id and an object of parameters vc.run: recebe um id de comando e um objeto de parâmetros
@msg vc.run: the parameters must be an object vc.run: os parâmetros devem ser um objeto
@msg vc.run: the result{place} is too large for a script vc.run: o resultado{place} é grande demais para um script
@msg $.evalFile requires a file path $.evalFile requer um caminho de arquivo
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: o tempo limite deve ser um número finito de milissegundos, 0 ou mais
@msg $.evalFile: takes a file path and a timeout $.evalFile: recebe um caminho de arquivo e um tempo limite
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: linha {line}, coluna {column} de {file}: {e} (lançado)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: linha {line}, coluna {column}: {e} (lançado)
@msg {name}: {e} (thrown) {name}: {e} (lançado)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: linha {line}, coluna {column} de {file}: {e} (limite)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: linha {line}, coluna {column}: {e} (limite)
@msg {name}: {e} (limit) {name}: {e} (limite)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: linha {line}, coluna {column} de {file}: {e} (erro de sintaxe)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: linha {line}, coluna {column}: {e} (erro de sintaxe)
@msg {name}: {e} (syntax) {name}: {e} (erro de sintaxe)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: linha {line}, coluna {column} de {file}: {e} (interrompido)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: linha {line}, coluna {column}: {e} (interrompido)
@msg {name}: {e} (stopped) {name}: {e} (interrompido)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: linha {line}, coluna {column} de {file}: {e} (erro interno)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: linha {line}, coluna {column}: {e} (erro interno)
@msg {name}: {e} (internal) {name}: {e} (erro interno)
@msg {e} (these files stay written: {paths}) {e} (estes arquivos continuam gravados: {paths})
@msg $.{name}: give a name, as a string $.{name}: informe um nome, como string
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: informe uma localidade como "en" ou "de_DE", ou null para a da interface
@msg $.localize: give true or false $.localize: informe true ou false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: só é possível definir 512, que ativa a localização, ou 0
@msg $.flags: give a number $.flags: informe um número
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: aqui os scripts só leem e gravam UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: informe o nome de uma codificação, como string
@msg $.memCache: the memory cache size cannot be set $.memCache: o tamanho do cache de memória não pode ser definido
@msg $.setenv: give a value, as a string $.setenv: informe um valor, como string
@msg $.setenv: only {_1} can be set $.setenv: só é possível definir {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: um valor tem no máximo {MAX_ENV_BYTES} letras, dígitos e _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: informe um número de milissegundos de 0 a {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: informe um número de milissegundos
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: uma execução não pode esperar dentro de um callback de uma função interna, um getter, uma conversão ou um arquivo que $.evalFile executa; chame-a a partir do próprio código do script
@msg $.bp: scripts here have no debugger $.bp: aqui os scripts não têm depurador
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: os scripts ainda não podem mostrar uma caixa de diálogo
@msg {name}: give a message {name}: informe uma mensagem
@msg {name}: give the text the field starts with {name}: informe o texto com que o campo começa
@msg {name}: the message is longer than 16 KiB {name}: a mensagem tem mais de 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: o título tem mais de 256 bytes
@msg {name}: the text the field starts with is longer than 16 KiB {name}: o texto com que o campo começa tem mais de 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: uma caixa de diálogo não pode abrir dentro de um callback de uma função interna, um getter, uma conversão ou um arquivo que $.evalFile executa; chame-a a partir do próprio código do script
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: a próxima resposta em `answers` é para {_1}, não para {name}
@msg {name}: `answers` has no answer left for this dialog {name}: `answers` não tem mais respostas para esta caixa de diálogo
@msg vc.document{place} is too large for a script vc.document{place} é grande demais para um script
@msg vc.log: the log of this run is full vc.log: o registro desta execução está cheio
@msg this function's script run has ended a execução do script desta função terminou
@msg the script made more host calls than one run may make o script fez mais chamadas ao host do que uma execução pode fazer
@msg the script passed more data to and from commands than one run may pass o script passou mais dados para os comandos e a partir deles do que uma execução pode passar
@msg the script added more objects and data to the documents than one run may add o script adicionou aos documentos mais objetos e dados do que uma execução pode adicionar
@msg {what}: the object is not a File or a Folder {what}: o objeto não é um File nem um Folder
@msg {what}: the count must be a finite number, 0 or more {what}: a contagem deve ser um número finito, 0 ou mais
@msg File.seek: the position must be a finite number File.seek: a posição deve ser um número finito
@msg File.seek: the mode must be 0, 1 or 2 File.seek: o modo deve ser 0, 1 ou 2
@msg script file is compiled: {value} o arquivo de script está compilado: {value}
@msg `name` must be the name of a script engine `name` deve ser o nome de um mecanismo de script
@msg the main script engine is new for each run and is never kept, so it cannot be dropped o mecanismo de script principal é novo a cada execução e nunca é mantido, por isso não pode ser descartado
@msg there is no script engine named {name} não há nenhum mecanismo de script chamado {name}
@msg Running a script Executando um script
@msg Copied the script report Relatório do script copiado
@msg This shortcut file is in a form VectorCraft can't read. Este arquivo de atalhos está em um formato que o VectorCraft não consegue ler.
Can't render this file because it contains an unexpected character in line 6 and column 47.
+84
View File
@@ -2650,6 +2650,8 @@ mark-style Japanese Японский
Proof Setup Настройка цветопробы
Properties Свойства
Proportional Metrics Пропорциональные метрики
Insert Aki Left Вставить аки слева
Insert Aki Right Вставить аки справа
Character Direction Направление символов
Digits Цифры
Arabic Арабские
@@ -2924,6 +2926,8 @@ digits Malayalam Малаялам
Reset Rotate View Сбросить поворот вида
Rotate View to Selection Повернуть вид по выделению
Reset the rows to the artwork's colors Сбросить строки к цветам рисунка
Color Theme Picker Выбор цветовой темы
Click or drag across the art to pick its colors; Shift adds more Щёлкните или проведите по рисунку, чтобы взять его цвета; Shift добавляет ещё
Reset to Default Сбросить к значениям по умолчанию
Reset to White, Black Сбросить к белому, чёрному
Reset with Mesh Сбросить с сеткой
@@ -3333,6 +3337,7 @@ digits Malayalam Малаялам
Show Note Показать примечание
Show Options Показать параметры
Show Recent Colors Показать последние цвета
Toggle RGB Percent Переключить RGB в процентах
Show Original Path Показать исходный контур
Open this dialog with these settings next time Открывать это диалоговое окно с этими параметрами в следующий раз
Auto-Simplify Автоматическое упрощение
@@ -4248,6 +4253,85 @@ axis Both Оба
@msg the script's run is no longer available выполнение скрипта больше недоступно
@msg a failed command changed undo steps that could not be put back, so the script was stopped неудавшаяся команда изменила шаги отмены, которые не удалось восстановить, поэтому скрипт остановлен
@msg a recovery copy could not be written, so the script was not run не удалось записать копию для восстановления, поэтому скрипт не выполнен
@msg Script file access denied Доступ к файлу скрипта запрещен
@msg Script file exceeds 8 MiB Файл скрипта больше 8 МиБ
@msg Script file is not open Файл скрипта не открыт
@msg Script file cannot be decoded Не удается декодировать файл скрипта
@msg Script file is not a regular file Файл скрипта не является обычным файлом
@msg Script file does not exist Файл скрипта не существует
@msg Script file could not be read Не удалось прочитать файл скрипта
@msg Script folder has more than 2,048 entries В папке скрипта больше 2048 элементов
@msg Script file open mode must be r, w, e or a Режим открытия файла скрипта должен быть r, w, e или a
@msg Script file writing is not available Запись файлов скрипта недоступна
@msg Script file dialogs are not available Диалоговые окна файлов скрипта недоступны
@msg Script files cannot be opened in another application Файлы скрипта нельзя открыть в другом приложении
@msg Script file access is unavailable on the web Доступ к файлам скрипта в веб-версии недоступен
@msg Script has 256 files open У скрипта открыто 256 файлов
@msg Script file path exceeds 32,767 characters Путь к файлу скрипта длиннее 32 767 символов
@msg Script folder mask takes too many steps to match Сопоставление маски папки скрипта требует слишком много шагов
@msg the script opened more file data than one run may open (32 MiB) скрипт открыл больше данных файлов, чем может открыть один запуск (32 МиБ)
@msg File.seek: takes a position and a mode File.seek: принимает позицию и режим
@msg vc.run: give a command id, as a string vc.run: укажите идентификатор команды в виде строки
@msg vc.run: takes a command id and an object of parameters vc.run: принимает идентификатор команды и объект параметров
@msg vc.run: the parameters must be an object vc.run: параметры должны быть объектом
@msg vc.run: the result{place} is too large for a script vc.run: результат{place} слишком велик для скрипта
@msg $.evalFile requires a file path $.evalFile требует путь к файлу
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: тайм-аут должен быть конечным числом миллисекунд, 0 или больше
@msg $.evalFile: takes a file path and a timeout $.evalFile: принимает путь к файлу и тайм-аут
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: строка {line}, столбец {column} в {file}: {e} (исключение)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: строка {line}, столбец {column}: {e} (исключение)
@msg {name}: {e} (thrown) {name}: {e} (исключение)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: строка {line}, столбец {column} в {file}: {e} (ограничение)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: строка {line}, столбец {column}: {e} (ограничение)
@msg {name}: {e} (limit) {name}: {e} (ограничение)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: строка {line}, столбец {column} в {file}: {e} (синтаксическая ошибка)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: строка {line}, столбец {column}: {e} (синтаксическая ошибка)
@msg {name}: {e} (syntax) {name}: {e} (синтаксическая ошибка)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: строка {line}, столбец {column} в {file}: {e} (остановлен)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: строка {line}, столбец {column}: {e} (остановлен)
@msg {name}: {e} (stopped) {name}: {e} (остановлен)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: строка {line}, столбец {column} в {file}: {e} (внутренняя ошибка)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: строка {line}, столбец {column}: {e} (внутренняя ошибка)
@msg {name}: {e} (internal) {name}: {e} (внутренняя ошибка)
@msg {e} (these files stay written: {paths}) {e} (эти файлы остаются записанными: {paths})
@msg $.{name}: give a name, as a string $.{name}: укажите имя в виде строки
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: укажите локаль, например "en" или "de_DE", или null для локали интерфейса
@msg $.localize: give true or false $.localize: укажите true или false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: можно установить только 512, которое включает локализацию, или 0
@msg $.flags: give a number $.flags: укажите число
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: здесь скрипты читают и записывают только UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: укажите имя кодировки в виде строки
@msg $.memCache: the memory cache size cannot be set $.memCache: размер кэша памяти нельзя установить
@msg $.setenv: give a value, as a string $.setenv: укажите значение в виде строки
@msg $.setenv: only {_1} can be set $.setenv: можно установить только {_1}
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: значение содержит не более {MAX_ENV_BYTES} букв, цифр и знаков _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: укажите число миллисекунд от 0 до {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: укажите число миллисекунд
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: запуск не может ждать внутри обратного вызова встроенной функции, геттера, преобразования или файла, который выполняет $.evalFile; вызовите её из собственного кода скрипта
@msg $.bp: scripts here have no debugger $.bp: здесь у скриптов нет отладчика
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: скрипты пока не могут показывать диалоговое окно
@msg {name}: give a message {name}: укажите сообщение
@msg {name}: give the text the field starts with {name}: укажите текст, с которого начинается поле
@msg {name}: the message is longer than 16 KiB {name}: сообщение длиннее 16 КиБ
@msg {name}: the title is longer than 256 bytes {name}: заголовок длиннее 256 байт
@msg {name}: the text the field starts with is longer than 16 KiB {name}: текст, с которого начинается поле, длиннее 16 КиБ
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: диалоговое окно не может открыться внутри обратного вызова встроенной функции, геттера, преобразования или файла, который выполняет $.evalFile; вызовите его из собственного кода скрипта
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: следующий ответ в `answers` предназначен для {_1}, а не для {name}
@msg {name}: `answers` has no answer left for this dialog {name}: в `answers` не осталось ответа для этого диалогового окна
@msg vc.document{place} is too large for a script vc.document{place} слишком велик для скрипта
@msg vc.log: the log of this run is full vc.log: журнал этого запуска заполнен
@msg this function's script run has ended запуск скрипта этой функции завершён
@msg the script made more host calls than one run may make скрипт сделал больше вызовов хоста, чем разрешено одному запуску
@msg the script passed more data to and from commands than one run may pass скрипт передал командам и получил от них больше данных, чем разрешено одному запуску
@msg the script added more objects and data to the documents than one run may add скрипт добавил в документы больше объектов и данных, чем разрешено одному запуску
@msg {what}: the object is not a File or a Folder {what}: объект не является ни File, ни Folder
@msg {what}: the count must be a finite number, 0 or more {what}: количество должно быть конечным числом, 0 или больше
@msg File.seek: the position must be a finite number File.seek: позиция должна быть конечным числом
@msg File.seek: the mode must be 0, 1 or 2 File.seek: режим должен быть 0, 1 или 2
@msg script file is compiled: {value} файл скрипта скомпилирован: {value}
@msg `name` must be the name of a script engine `name` должно быть именем движка скриптов
@msg the main script engine is new for each run and is never kept, so it cannot be dropped основной движок скриптов создаётся заново для каждого запуска и никогда не сохраняется, поэтому его нельзя удалить
@msg there is no script engine named {name} движка скриптов с именем {name} нет
@msg Running a script Выполняется скрипт
@msg Copied the script report Отчёт о сценарии скопирован
@msg Corners edits the corners of a path «Углы» редактирует углы контура
Can't render this file because it is too large.
+84
View File
@@ -2558,6 +2558,8 @@ font-technology Variable Variabla
Proof Setup Provtrycksinställningar
Properties Egenskaper
Proportional Metrics Proportionella mått
Insert Aki Left Infoga aki till vänster
Insert Aki Right Infoga aki till höger
Character Direction Teckenriktning
Digits Siffror
Arabic Arabiska
@@ -2830,6 +2832,8 @@ digits Malayalam Malayalam
Reset Rotate View Återställ Rotera vy
Rotate View to Selection Rotera vyn efter markeringen
Reset the rows to the artwork's colors Återställ raderna till teckningens färger
Color Theme Picker Färgtemaväljare
Click or drag across the art to pick its colors; Shift adds more Klicka eller dra över teckningen för att hämta dess färger; Skift lägger till fler
Reset to Default Återställ till standard
Reset to White, Black Återställ till vitt, svart
Reset with Mesh Återställ med nät
@@ -3225,6 +3229,7 @@ digits Malayalam Malayalam
Show Note Visa anteckning
Show Options Visa alternativ
Show Recent Colors Visa senaste färger
Toggle RGB Percent Växla RGB i procent
Show Original Path Visa ursprunglig bana
Open this dialog with these settings next time Öppna den här dialogrutan med de här inställningarna nästa gång
Auto-Simplify Förenkla automatiskt
@@ -4121,6 +4126,85 @@ axis Both Båda
@msg the script's run is no longer available skriptets körning är inte längre tillgänglig
@msg a failed command changed undo steps that could not be put back, so the script was stopped ett misslyckat kommando ändrade ångrasteg som inte kunde återställas, så skriptet stoppades
@msg a recovery copy could not be written, so the script was not run en återställningskopia kunde inte skrivas, så skriptet kördes inte
@msg Script file access denied Åtkomst till skriptfilen nekades
@msg Script file exceeds 8 MiB Skriptfilen är större än 8 MiB
@msg Script file is not open Skriptfilen är inte öppen
@msg Script file cannot be decoded Skriptfilen kan inte avkodas
@msg Script file is not a regular file Skriptfilen är inte en vanlig fil
@msg Script file does not exist Skriptfilen finns inte
@msg Script file could not be read Skriptfilen kunde inte läsas
@msg Script folder has more than 2,048 entries Skriptmappen har fler än 2 048 poster
@msg Script file open mode must be r, w, e or a Skriptfilens öppningsläge måste vara r, w, e eller a
@msg Script file writing is not available Skrivning av skriptfiler är inte tillgänglig
@msg Script file dialogs are not available Fildialogrutor för skript är inte tillgängliga
@msg Script files cannot be opened in another application Skriptfiler kan inte öppnas i ett annat program
@msg Script file access is unavailable on the web Åtkomst till skriptfiler är inte tillgänglig på webben
@msg Script has 256 files open Skriptet har 256 filer öppna
@msg Script file path exceeds 32,767 characters Skriptfilens sökväg är längre än 32 767 tecken
@msg Script folder mask takes too many steps to match Skriptmappens mask kräver för många steg för att matcha
@msg the script opened more file data than one run may open (32 MiB) skriptet öppnade mer fildata än en körning får öppna (32 MiB)
@msg File.seek: takes a position and a mode File.seek: tar en position och ett läge
@msg vc.run: give a command id, as a string vc.run: ange ett kommando-id som en sträng
@msg vc.run: takes a command id and an object of parameters vc.run: tar ett kommando-id och ett objekt med parametrar
@msg vc.run: the parameters must be an object vc.run: parametrarna måste vara ett objekt
@msg vc.run: the result{place} is too large for a script vc.run: resultatet{place} är för stort för ett skript
@msg $.evalFile requires a file path $.evalFile kräver en filsökväg
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: tidsgränsen måste vara ett ändligt antal millisekunder, 0 eller mer
@msg $.evalFile: takes a file path and a timeout $.evalFile: tar en filsökväg och en tidsgräns
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: rad {line}, kolumn {column} i {file}: {e} (kastat)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: rad {line}, kolumn {column}: {e} (kastat)
@msg {name}: {e} (thrown) {name}: {e} (kastat)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: rad {line}, kolumn {column} i {file}: {e} (gräns)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: rad {line}, kolumn {column}: {e} (gräns)
@msg {name}: {e} (limit) {name}: {e} (gräns)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: rad {line}, kolumn {column} i {file}: {e} (syntaxfel)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: rad {line}, kolumn {column}: {e} (syntaxfel)
@msg {name}: {e} (syntax) {name}: {e} (syntaxfel)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: rad {line}, kolumn {column} i {file}: {e} (stoppat)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: rad {line}, kolumn {column}: {e} (stoppat)
@msg {name}: {e} (stopped) {name}: {e} (stoppat)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: rad {line}, kolumn {column} i {file}: {e} (internt fel)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: rad {line}, kolumn {column}: {e} (internt fel)
@msg {name}: {e} (internal) {name}: {e} (internt fel)
@msg {e} (these files stay written: {paths}) {e} (dessa filer förblir skrivna: {paths})
@msg $.{name}: give a name, as a string $.{name}: ange ett namn som en sträng
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: ange en språkinställning som "en" eller "de_DE", eller null för gränssnittets
@msg $.localize: give true or false $.localize: ange true eller false
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: endast 512, som slår på lokalisering, eller 0 kan anges
@msg $.flags: give a number $.flags: ange ett tal
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: skript läser och skriver här endast UTF-8
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: ange namnet på en kodning som en sträng
@msg $.memCache: the memory cache size cannot be set $.memCache: minnescachens storlek kan inte anges
@msg $.setenv: give a value, as a string $.setenv: ange ett värde som en sträng
@msg $.setenv: only {_1} can be set $.setenv: endast {_1} kan anges
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: ett värde har högst {MAX_ENV_BYTES} bokstäver, siffror och _ . - @
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: ange ett antal millisekunder från 0 till {MAX_SLEEP_MS}
@msg $.sleep: give a number of milliseconds $.sleep: ange ett antal millisekunder
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: en körning kan inte vänta i ett återanrop från en inbyggd funktion, en getter, en konvertering eller en fil som $.evalFile kör; anropa den från skriptets egen kod
@msg $.bp: scripts here have no debugger $.bp: skript har ingen felsökare här
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: skript kan inte visa en dialogruta ännu
@msg {name}: give a message {name}: ange ett meddelande
@msg {name}: give the text the field starts with {name}: ange texten som fältet börjar med
@msg {name}: the message is longer than 16 KiB {name}: meddelandet är längre än 16 KiB
@msg {name}: the title is longer than 256 bytes {name}: rubriken är längre än 256 byte
@msg {name}: the text the field starts with is longer than 16 KiB {name}: texten som fältet börjar med är längre än 16 KiB
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en dialogruta kan inte öppnas i ett återanrop från en inbyggd funktion, en getter, en konvertering eller en fil som $.evalFile kör; anropa den från skriptets egen kod
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: nästa svar i `answers` gäller {_1}, inte {name}
@msg {name}: `answers` has no answer left for this dialog {name}: `answers` har inget svar kvar för den här dialogrutan
@msg vc.document{place} is too large for a script vc.document{place} är för stort för ett skript
@msg vc.log: the log of this run is full vc.log: loggen för den här körningen är full
@msg this function's script run has ended skriptkörningen för den här funktionen har avslutats
@msg the script made more host calls than one run may make skriptet gjorde fler värdanrop än en körning får göra
@msg the script passed more data to and from commands than one run may pass skriptet skickade mer data till och från kommandon än en körning får skicka
@msg the script added more objects and data to the documents than one run may add skriptet lade till fler objekt och mer data i dokumenten än en körning får lägga till
@msg {what}: the object is not a File or a Folder {what}: objektet är varken en File eller en Folder
@msg {what}: the count must be a finite number, 0 or more {what}: antalet måste vara ett ändligt tal, 0 eller mer
@msg File.seek: the position must be a finite number File.seek: positionen måste vara ett ändligt tal
@msg File.seek: the mode must be 0, 1 or 2 File.seek: läget måste vara 0, 1 eller 2
@msg script file is compiled: {value} skriptfilen är kompilerad: {value}
@msg `name` must be the name of a script engine `name` måste vara namnet på en skriptmotor
@msg the main script engine is new for each run and is never kept, so it cannot be dropped huvudskriptmotorn är ny för varje körning och sparas aldrig, så den kan inte tas bort
@msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name}
@msg Running a script Kör ett skript
@msg Copied the script report Kopierade skriptrapporten
@msg Corners edits the corners of a path Hörn redigerar hörnen på en bana
Can't render this file because it contains an unexpected character in line 5 and column 25.
+398 -17
View File
@@ -1754,6 +1754,23 @@ fn package_status_message_templates_parse() {
assert!(Catalog::parse("@msg\tPackaged {n} file(s) in {folder}{note}\tbad\n").message("Packaged 1 file(s) in /a b").is_none());
}
/// A placeholder that occurs twice in a template matches the same text both times, so a template
/// that ends with the name it starts with does not swallow a line that wraps its message.
#[test]
fn a_repeated_placeholder_matches_the_same_text() {
let c = Catalog::parse(concat!(
"@msg\t{name}: the next answer is for {_1}, not {name}\tnext {name} {_1}\n",
"@msg\t{file}: line {line}: {e} (thrown)\tthrown {file} {line} {e}\n",
));
let (form, caps) = c.message("confirm: the next answer is for prompt, not confirm").expect("matches");
assert_eq!((form, caps), ("next {name} {_1}", vec![("name", "confirm"), ("_1", "prompt"), ("name", "confirm")]));
let line = "t.js: line 3: Error: confirm: the next answer is for prompt, not confirm (thrown)";
let (form, caps) = c.message(line).expect("matches");
assert_eq!(form, "thrown {file} {line} {e}");
assert_eq!(caps.last(), Some(&("e", "Error: confirm: the next answer is for prompt, not confirm")));
assert!(c.message("alert: the next answer is for prompt, not confirm").is_none());
}
/// A template that starts with text matches a message it wraps before a template that starts
/// with a placeholder, even one with more literal text, so the wrapped reason is translated by
/// its own row.
@@ -2181,6 +2198,73 @@ fn wrong(&self) -> String { String::new() }
assert_eq!(found.iter().collect::<Vec<_>>(), want);
}
/// A constant's name reads the text the file declares under it, else every text the files of its
/// own crate declare under it, else every text any scanned crate declares under it: an engine
/// reader's error does not read the Scripts menu's headers, which are constants of the same names
/// in another crate.
#[test]
fn message_scan_reads_constants_of_the_file_and_its_crate() {
use std::collections::{BTreeMap, BTreeSet};
let jxl = str_consts(r#"const TRUNCATED: &str = "the JPEG XL file is cut short"; const LIMIT: &str = "the image is too large";"#);
let pcx = str_consts(r#"const TRUNCATED: &str = "the PCX file is cut short";"#);
let menu = str_consts(r#"const TRUNCATED: &str = "Some scripts were not listed"; const SHARED: &str = "a message of another crate";"#);
let gather = |files: &[&Vec<(String, String)>]| {
let mut map: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (name, value) in files.iter().copied().flatten() {
map.entry(name.clone()).or_default().push(value.clone());
}
map
};
let engine = gather(&[&jxl, &pcx]);
let everywhere = gather(&[&jxl, &pcx, &menu]);
let code =
"fn f() -> Result<()> { Err(TRUNCATED.into()) }\nfn g() -> Result<()> { Err(LIMIT.into()) }\nfn h() -> Result<()> { Err(SHARED.into()) }";
let found = |own: &[(String, String)], in_crate: &BTreeMap<String, Vec<String>>| -> BTreeSet<String> {
source_messages(code, &[], &scoped_consts(own, in_crate, &everywhere)).into_iter().collect()
};
let in_jxl = ["a message of another crate", "the JPEG XL file is cut short", "the image is too large"];
assert_eq!(found(&jxl, &engine).iter().collect::<Vec<_>>(), in_jxl);
let in_engine = ["a message of another crate", "the JPEG XL file is cut short", "the PCX file is cut short", "the image is too large"];
assert_eq!(found(&[], &engine).iter().collect::<Vec<_>>(), in_engine);
assert_eq!(found(&[], &BTreeMap::new()).len(), 5);
let scanned = message_literals();
for header in [crate::scripts_menu::TRUNCATED, crate::scripts_menu::UNREADABLE] {
assert!(!scanned.contains(header), "{header}");
}
}
/// The scan reads the errors the script interpreter throws at a script with a method of any
/// receiver, `&format!` strings included, and not a call of a longer name.
#[test]
fn message_scan_reads_script_interpreter_errors() {
let code = r#"
fn f(i: &mut Interp, interp: &mut Interp) -> JsResult<Value> {
let _ = i.type_error(&format!("{what}: the object is not a File or a Folder"));
let _ = interp.throw(ErrorType::Range, "File.seek: the mode must be 0, 1 or 2");
let _ = self.error("the path has an empty step");
let _ = self.throw_host(t, "not an error: a longer name");
let _ = throw_type_error(interp, "not an error: a function");
Ok(Value::Undefined)
}
"#;
let js: Vec<_> = ERROR_HELPERS.iter().filter(|(c, _, _)| *c == "js").map(|&(_, call, before)| (call, before)).collect();
let found = source_messages(code, &js, &Default::default());
assert_eq!(found, ["{what}: the object is not a File or a Folder", "File.seek: the mode must be 0, 1 or 2", "the path has an empty step"]);
}
/// The scan stops at a test module whose `cfg` is `test` or `all(test, …)`, and reads on past a
/// declaration of a test file and a module that is not only for tests.
#[test]
fn message_scan_skips_test_modules_with_any_test_cfg() {
let code = "fn a() {}\n#[cfg(test)]\nmod tests_x;\n#[cfg(any(test, feature = \"x\"))]\nmod extra {}\nfn b() {}\n";
for module in ["#[cfg(test)]\nmod tests {", "#[cfg(all(test, not(target_arch = \"wasm32\")))]\nmod tests {", "#[cfg(all( test , unix))] mod t {"]
{
let text = format!("{code}{module} fn c() {{}} }}\n");
assert_eq!(without_test_module(&text), code, "{module}");
}
assert_eq!(without_test_module(code), code);
}
/// The limits a plug-in run can exceed, and the error of a removal that leaves the plug-in's grant
/// in the plug-in store, are translated in every language that translates every message, as the
/// status bar shows them.
@@ -2219,6 +2303,244 @@ fn plugin_limit_errors_are_translated() {
}
}
/// The errors a script's `File` and `Folder` objects, `vc.run` and `$.evalFile` raise are
/// translated in every language of [`COMPLETE_MESSAGES`], and so is the status bar's line for a run
/// that ends with one: the script's name, its place, the command ids and what the script itself
/// threw stay as they are.
#[test]
fn script_errors_are_translated() {
use serde_json::json;
let scanned = message_literals();
let templates = [
"Script file access denied",
"Script file exceeds 8 MiB",
"Script file is not open",
"Script file cannot be decoded",
"Script file is not a regular file",
"Script file does not exist",
"Script file could not be read",
"Script folder has more than 2,048 entries",
"Script file open mode must be r, w, e or a",
"Script file writing is not available",
"Script file dialogs are not available",
"Script files cannot be opened in another application",
"Script file access is unavailable on the web",
"Script has 256 files open",
"Script file path exceeds 32,767 characters",
"Script folder mask takes too many steps to match",
"the script opened more file data than one run may open (32 MiB)",
"File.seek: takes a position and a mode",
"vc.run: give a command id, as a string",
"vc.run: takes a command id and an object of parameters",
"vc.run: the parameters must be an object",
"vc.run: the result{place} is too large for a script",
"$.evalFile requires a file path",
"$.evalFile: the timeout must be a finite number of milliseconds, 0 or more",
"$.evalFile: takes a file path and a timeout",
];
for template in templates {
assert!(scanned.contains(template), "{template}");
}
let messages: Vec<String> = templates.iter().map(|t| t.replace("{place}", ".layers[2]")).collect();
// The status bar's lines for runs that end with one of these errors, each with the message it holds.
let mut s = vectorcraft_engine::Session::new();
let mut lines = vec![];
for (source, inner) in [
("vc.run()", messages[18].as_str()),
("vc.run('view.capsLock', {}, 1)", &messages[19]),
("vc.run('view.capsLock', 1)", &messages[20]),
("$.evalFile()", &messages[22]),
("$.evalFile('a.jsx', -1)", &messages[23]),
("$.evalFile('a.jsx', 0, 1)", &messages[24]),
] {
let e = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_err().to_string();
assert!(e.starts_with("t.js: line ") && e.contains(inner) && e.ends_with(" (thrown)"), "{source}: {e}");
lines.push((e, Some(inner.to_string())));
}
// A `File` gives why it could not open as its `error`, which the script throws.
let source = "var f = new File('/vc-no-such-folder/a.txt');\nif (!f.open('r')) throw new Error(f.error);";
let e = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_err().to_string();
let inner = messages[..17].iter().find(|m| e.ends_with(&format!(": Error: {m} (thrown)"))).unwrap_or_else(|| panic!("{e}"));
lines.push((e, Some(inner.clone())));
let thrown = s.execute("script.run", &json!({"source": "throw new Error('mine')", "name": "t.js"})).unwrap_err().to_string();
assert_eq!(thrown, "t.js: line 1, column 1: Error: mine (thrown)");
lines.push((thrown, None));
// A script that does not compile, and an error raised in code `eval` compiled, which has no place.
let syntax = s.execute("script.run", &json!({"source": "var = 1;", "name": "t.js"})).unwrap_err().to_string();
assert!(syntax.starts_with("t.js: line 1, column ") && syntax.ends_with(" (syntax)"), "{syntax}");
lines.push((syntax, None));
let source = format!("eval(\"throw new Error('{}')\");", messages[18]);
let placeless = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_err().to_string();
assert_eq!(placeless, format!("t.js: Error: {} (thrown)", messages[18]));
lines.push((placeless, Some(messages[18].clone())));
lines.push((format!("t.js: line 7, column 2: {} (stopped)", messages[16]), Some(messages[16].clone())));
lines.push((format!("t.js: line 7, column 2 of lib.jsx: {} (internal)", messages[16]), Some(messages[16].clone())));
lines.push((format!("t.js: {} (internal)", messages[16]), Some(messages[16].clone())));
// A run that ends at a limit, in a file another one included, with files left written.
lines.push((format!("t.js: line 4, column 9 of lib.jsx: {} (limit)", messages[16]), Some(messages[16].clone())));
lines.push((format!("t.js: {} (limit)", messages[16]), Some(messages[16].clone())));
lines.push((format!("t.js: line 3, column 1 of lib.jsx: TypeError: {} (thrown)", messages[0]), Some(messages[0].clone())));
lines.push((format!("t.js: TypeError: {} (thrown)", messages[0]), Some(messages[0].clone())));
let kept = format!("t.js: line 2, column 5: Error: {} (thrown) (these files stay written: /tmp/a.txt, /tmp/b.txt)", messages[13]);
lines.push((kept, Some(messages[13].clone())));
for code in COMPLETE_MESSAGES {
let lang = Lang::from_code(code).expect("registered");
for m in &messages {
let shown = message(lang, m);
assert_ne!(shown, *m, "{code}");
assert!(["vc.run", "$.evalFile", "File.seek"].iter().all(|id| !m.contains(id) || shown.contains(id)), "{code}: {shown}");
}
assert!(message(lang, &messages[21]).contains(".layers[2]"), "{code}");
for (line, inner) in &lines {
let shown = message(lang, line);
let kinds = ["(thrown)", "(limit)", "(syntax)", "(stopped)", "(internal)", "stay written"];
assert!(kinds.iter().all(|k| !shown.contains(k)), "{code}: {shown}");
let numbers: Vec<&str> = line.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect();
assert!(shown.starts_with("t.js") && numbers.iter().all(|n| shown.contains(n)), "{code}: {line} -> {shown}");
match inner {
Some(inner) => assert!(shown.contains(&message(lang, inner)), "{code}: {line} -> {shown}"),
None if line.ends_with("(syntax)") => assert_ne!(shown, *line, "{code}"),
None => assert!(shown.contains("Error") && shown.contains("mine"), "{code}: {shown}"),
}
for kept in ["lib.jsx", "/tmp/a.txt, /tmp/b.txt"] {
assert!(!line.contains(kept) || shown.contains(kept), "{code}: {shown}");
}
}
}
}
/// The errors a script's `$` object, its `alert`, `confirm` and `prompt` dialogs, `vc.document`,
/// `vc.log`, the methods of its `File` and `Folder` objects and a run's limits give, and the errors
/// of the script engine commands, are translated in every language of [`COMPLETE_MESSAGES`], on
/// their own and in the status bar's line for a run that ends with one. Names, numbers and the
/// ids of functions stay as they are.
#[test]
fn script_host_errors_are_translated() {
use serde_json::json;
let scanned = message_literals();
let templates = [
"$.{name}: give a name, as a string",
"$.locale: give a locale such as \"en\" or \"de_DE\", or null for the interface's",
"$.localize: give true or false",
"$.flags: only 512, which turns localization on, or 0 can be set",
"$.flags: give a number",
"$.appEncoding: scripts here read and write UTF-8 only",
"$.appEncoding: give an encoding's name, as a string",
"$.memCache: the memory cache size cannot be set",
"$.setenv: give a value, as a string",
"$.setenv: only {_1} can be set",
"$.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @",
"$.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS}",
"$.sleep: give a number of milliseconds",
"$.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code",
"$.bp: scripts here have no debugger",
"$.colorPicker: scripts cannot show a dialog yet",
"{name}: give a message",
"{name}: give the text the field starts with",
"{name}: the message is longer than 16 KiB",
"{name}: the title is longer than 256 bytes",
"{name}: the text the field starts with is longer than 16 KiB",
"{name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code",
"{name}: the next answer in `answers` is for {_1}, not {name}",
"{name}: `answers` has no answer left for this dialog",
"vc.document{place} is too large for a script",
"vc.log: the log of this run is full",
"this function's script run has ended",
"the script made more host calls than one run may make",
"the script passed more data to and from commands than one run may pass",
"the script added more objects and data to the documents than one run may add",
"{what}: the object is not a File or a Folder",
"{what}: the count must be a finite number, 0 or more",
"File.seek: the position must be a finite number",
"File.seek: the mode must be 0, 1 or 2",
"script file is compiled: {value}",
"`name` must be the name of a script engine",
"the main script engine is new for each run and is never kept, so it cannot be dropped",
"there is no script engine named {name}",
];
for template in templates {
assert!(scanned.contains(template), "{template}");
}
let mut s = vectorcraft_engine::Session::new();
// (what the line holds, what that is as the script's error, what the catalogs must keep)
let mut lines: Vec<(String, String, Vec<&str>)> = vec![];
for (source, inner, kept) in [
("$.getenv(1)", "$.getenv: give a name, as a string", vec!["$.getenv"]),
("$.setenv('LANG', 1)", "$.setenv: give a value, as a string", vec!["$.setenv"]),
("$.setenv('HOME', 'x')", "$.setenv: only LANG, LC_MESSAGES, LC_ALL, OS can be set", vec!["$.setenv", "LANG, LC_MESSAGES, LC_ALL, OS"]),
("$.setenv('LANG', 'a b')", "$.setenv: a value has at most 64 letters, digits and _ . - @", vec!["$.setenv", "64", "_ . - @"]),
("$.sleep('x')", "$.sleep: give a number of milliseconds", vec!["$.sleep"]),
("$.sleep(5000)", "$.sleep: give a number of milliseconds from 0 to 1000", vec!["$.sleep", "1000"]),
("$.flags = 3", "$.flags: only 512, which turns localization on, or 0 can be set", vec!["$.flags", "512"]),
("$.flags = 'x'", "$.flags: give a number", vec!["$.flags"]),
("$.localize = 1", "$.localize: give true or false", vec!["$.localize"]),
("$.locale = 1", templates[1], vec!["$.locale", "\"en\"", "\"de_DE\""]),
("$.appEncoding = 'latin1'", templates[5], vec!["$.appEncoding", "UTF-8"]),
("$.appEncoding = 1", templates[6], vec!["$.appEncoding"]),
("$.memCache = 1", templates[7], vec!["$.memCache"]),
("$.bp()", templates[14], vec!["$.bp"]),
("$.colorPicker()", templates[15], vec!["$.colorPicker"]),
("File.prototype.seek.call({})", "seek: the object is not a File or a Folder", vec!["seek", "File"]),
("new File('a.txt').seek(NaN)", templates[32], vec!["File.seek"]),
("new File('a.txt').seek(0, 5)", templates[33], vec!["File.seek", "0, 1", "2"]),
("new File('a.txt').read(-1)", "File.read: the count must be a finite number, 0 or more", vec!["File.read", "0"]),
] {
let e = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_err().to_string();
assert!(e.starts_with("t.js: ") && e.contains(&format!(": {inner} (")), "{source}: {e}");
lines.push((e, inner.to_string(), kept));
}
let in_callback = templates[21].replace("{name}", "alert");
for (inner, kept) in [
("alert: give a message", vec!["alert"]),
("prompt: give the text the field starts with", vec!["prompt"]),
("confirm: the message is longer than 16 KiB", vec!["confirm", "16"]),
("alert: the title is longer than 256 bytes", vec!["alert", "256"]),
("prompt: the text the field starts with is longer than 16 KiB", vec!["prompt", "16"]),
(in_callback.as_str(), vec!["alert", "$.evalFile"]),
("confirm: the next answer in `answers` is for prompt, not confirm", vec!["`answers`", "prompt", "confirm"]),
("alert: `answers` has no answer left for this dialog", vec!["`answers`", "alert"]),
(templates[13], vec!["$.sleep", "$.evalFile"]),
("vc.document.layers[0] is too large for a script", vec!["vc.document.layers[0]"]),
(templates[25], vec!["vc.log"]),
(templates[26], vec![]),
(templates[27], vec![]),
(templates[28], vec![]),
(templates[29], vec![]),
("script file is compiled: lib.jsxbin", vec!["lib.jsxbin"]),
] {
let line = format!("t.js: line 3, column 7: Error: {inner} (thrown)");
lines.push((line, inner.to_string(), kept));
}
let mut commands = vec![];
for (id, params) in
[("script.engine.drop", json!({})), ("script.engine.drop", json!({"name": "main"})), ("script.engine.drop", json!({"name": "kept"}))]
{
commands.push(s.execute(id, &params).unwrap_err().to_string());
}
assert!(commands[0].contains(templates[35]) && commands[1].contains(templates[36]), "{commands:?}");
assert!(commands[2].contains("there is no script engine named \"kept\""), "{commands:?}");
for code in COMPLETE_MESSAGES {
let lang = Lang::from_code(code).expect("registered");
for (line, inner, kept) in &lines {
let shown = message(lang, inner);
assert_ne!(shown, *inner, "{code}");
assert!(kept.iter().all(|k| shown.contains(k)), "{code}: {inner} -> {shown}");
let whole = message(lang, line);
let kinds = ["(thrown)", "(limit)", "(syntax)", "(stopped)", "(internal)"];
assert!(whole.starts_with("t.js") && whole.contains(&shown) && kinds.iter().all(|k| !whole.contains(k)), "{code}: {line} -> {whole}");
}
for e in &commands {
let shown = message(lang, e);
assert_ne!(shown, *e, "{code}");
assert!(
!shown.contains("must be the name") && !shown.contains("is never kept") && !shown.contains("there is no script engine"),
"{code}: {shown}"
);
}
assert!(message(lang, &commands[2]).contains("\"kept\""), "{code}");
}
}
/// A manifest whose `commands` value has the wrong shape is refused with an error that every
/// language of [`COMPLETE_MESSAGES`] translates whole, the command's name and the place in the
/// manifest included.
@@ -2918,23 +3240,30 @@ const COMPLETE_MESSAGES: &[&str] = &[
];
/// Crates whose error and status messages reach the status bar.
const MESSAGE_CRATES: &[&str] = &["ui-egui", "engine", "doc", "format", "svg", "pdf", "eps", "text", "plugins", "metafile", "cad", "trace"];
const MESSAGE_CRATES: &[&str] = &["ui-egui", "engine", "doc", "format", "svg", "pdf", "eps", "text", "plugins", "metafile", "cad", "trace", "js"];
/// Where a message literal starts: a status, an error value, a `thiserror` message.
const MESSAGE_MARKERS: &[&str] = &[".status(", "ui.status = ", "status = ", "Other(", "Err(", "ok_or(", "ok_or_else(|| ", "#[error("];
/// Helpers that make an error from a message, by crate, with the number of arguments before the
/// message: the engine's `bad(cmd, msg)` (`EngineError::BadParams`), `err(msg)` (`cmd/fileio`)
/// and `error(msg)` (`cmd/dimension.rs`), the PDF writer's `bad(why)` (`forms.rs`) and
/// `failed(why)` (`encrypt.rs`, `linearize.rs`), and the plug-in host's `bad(what)` (a parameter's
/// spec and dialog keys), `wrong(what)` (a parameter's value), `out_err(at, msg)` (plug-in output),
/// `in_range(x, lo, hi, at, what)` and `unit(x, at, what)` (a painted effect's numbers) and
/// `.read_packed(packed, what, max)` (the block a plug-in returned). A helper that starts with
/// `.` is a method.
/// and `error(msg)` (`cmd/dimension.rs`), the script host's `fail(msg)` (`script/files.rs`,
/// `script/dollar.rs`) and `value(msg)`, which gives the messages the script `File` object's own
/// code throws (`script/files.rs`), and `.over(limit)` for a limit a run passes (`script/mod.rs`),
/// the PDF writer's `bad(why)` (`forms.rs`) and `failed(why)` (`encrypt.rs`, `linearize.rs`), the
/// plug-in host's `bad(what)` (a parameter's spec and dialog keys), `wrong(what)` (a parameter's
/// value), `out_err(at, msg)` (plug-in output), `in_range(x, lo, hi, at, what)` and
/// `unit(x, at, what)` (a painted effect's numbers) and `.read_packed(packed, what, max)` (the block
/// a plug-in returned), and the script interpreter's methods that throw an error at a script:
/// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`. A helper that
/// starts with `.` is a method of any receiver.
const ERROR_HELPERS: &[(&str, &str, usize)] = &[
("engine", "bad(", 1),
("engine", "err(", 0),
("engine", "error(", 0),
("engine", "fail(", 0),
("engine", "value(", 0),
("engine", ".over(", 0),
("pdf", "bad(", 0),
("pdf", "failed(", 0),
("plugins", "bad(", 0),
@@ -2943,6 +3272,9 @@ const ERROR_HELPERS: &[(&str, &str, usize)] = &[
("plugins", "in_range(", 4),
("plugins", "unit(", 2),
("plugins", ".read_packed(", 1),
("js", ".type_error(", 0),
("js", ".throw(", 1),
("js", ".error(", 0),
];
/// Error variants whose first argument is a name, not a message: a command id
@@ -2977,7 +3309,11 @@ fn message_literals_in(names: &[&str]) -> std::collections::BTreeSet<String> {
if name != "tests" {
stack.push(path);
}
} else if name.ends_with(".rs") && !name.starts_with("tests") && !(d == crates.join("ui-egui").join("src") && name == "control.rs") {
} else if name.ends_with(".rs")
&& !name.starts_with("tests")
&& !name.ends_with("_tests.rs")
&& !(d == crates.join("ui-egui").join("src") && name == "control.rs")
{
// Control replies are English protocol data, never status-bar messages
// (see i18n's module contract). Engine messages are scanned in their own crates.
let text = std::fs::read_to_string(&path).unwrap_or_default();
@@ -2985,20 +3321,59 @@ fn message_literals_in(names: &[&str]) -> std::collections::BTreeSet<String> {
}
}
}
let mut consts = std::collections::BTreeMap::new();
for (_, text) in &files {
for (name, value) in str_consts(without_test_module(text)) {
consts.entry(name).or_insert_with(Vec::new).push(value);
let crate_of = |path: &std::path::Path| names.iter().copied().find(|c| path.starts_with(crates.join(c))).unwrap_or("");
let declared: Vec<_> = files.iter().map(|(path, text)| (crate_of(path), str_consts(without_test_module(text)))).collect();
let mut by_crate: std::collections::BTreeMap<&str, std::collections::BTreeMap<String, Vec<String>>> = std::collections::BTreeMap::new();
let mut everywhere: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
for (krate, consts) in &declared {
let in_crate = by_crate.entry(*krate).or_default();
for (name, value) in consts {
in_crate.entry(name.clone()).or_default().push(value.clone());
everywhere.entry(name.clone()).or_default().push(value.clone());
}
}
for (path, text) in &files {
let none = std::collections::BTreeMap::new();
let crate_consts: std::collections::BTreeMap<&str, _> =
by_crate.iter().map(|(krate, in_crate)| (*krate, scoped_consts(&[], in_crate, &everywhere).into_owned())).collect();
for ((path, text), (krate, own)) in files.iter().zip(&declared) {
let helpers: Vec<_> =
ERROR_HELPERS.iter().filter(|(c, _, _)| path.starts_with(crates.join(c))).map(|&(_, call, before)| (call, before)).collect();
let consts = scoped_consts(own, crate_consts.get(krate).unwrap_or(&none), &none);
out.extend(source_messages(without_test_module(text), &helpers, &consts));
}
out
}
/// The `&str` constants a file can name, from the constants it declares (`own`), those the files
/// of its crate declare (`in_crate`) and those every scanned crate declares (`everywhere`): a name
/// the file declares has the file's own text only, a name its crate declares has every text the
/// crate's files give it, and any other name has every text the scanned crates give it.
fn scoped_consts<'a>(
own: &[(String, String)],
in_crate: &'a std::collections::BTreeMap<String, Vec<String>>,
everywhere: &std::collections::BTreeMap<String, Vec<String>>,
) -> std::borrow::Cow<'a, std::collections::BTreeMap<String, Vec<String>>> {
let elsewhere = everywhere.keys().any(|name| !in_crate.contains_key(name));
let own_differs = own.iter().any(|(name, _)| {
let mine: Vec<&String> = own.iter().filter(|(n, _)| n == name).map(|(_, v)| v).collect();
in_crate.get(name).is_none_or(|values| values.iter().collect::<Vec<_>>() != mine)
});
if !elsewhere && !own_differs {
return std::borrow::Cow::Borrowed(in_crate);
}
let mut consts = everywhere.clone();
for (name, values) in in_crate {
consts.insert(name.clone(), values.clone());
}
for (name, _) in own {
consts.remove(name);
}
for (name, value) in own {
consts.entry(name.clone()).or_default().push(value.clone());
}
std::borrow::Cow::Owned(consts)
}
/// The `&str` constants `code` declares outside its comments (`const NAME: &str = "…";`), with
/// their text, escapes resolved.
fn str_consts(code: &str) -> Vec<(String, String)> {
@@ -3103,11 +3478,17 @@ fn skip_args(args: &str, n: usize) -> Option<&str> {
None
}
/// Source up to its inline test module (`#[cfg(test)] mod tests {`); declarations of test files
/// (`#[cfg(test)] mod tests_x;`) don't end it.
/// Source up to its inline test module (`#[cfg(test)] mod tests {`, or a `cfg(all(test, …))` one);
/// declarations of test files (`#[cfg(test)] mod tests_x;`) don't end it.
fn without_test_module(text: &str) -> &str {
for (at, m) in text.match_indices("#[cfg(test)]") {
let after = text[at + m.len()..].trim_start();
for (at, m) in text.match_indices("#[cfg(") {
let rest = &text[at + m.len()..];
let Some(end) = rest.find(")]") else { continue };
let cond: String = rest[..end].chars().filter(|c| !c.is_whitespace()).collect();
if cond != "test" && !cond.starts_with("all(test,") {
continue;
}
let after = rest[end + 2..].trim_start();
if let Some(rest) = after.strip_prefix("mod ")
&& rest.trim_start_matches(|c: char| c.is_alphanumeric() || c == '_').trim_start().starts_with('{')
{
+84
View File
@@ -2430,6 +2430,8 @@ shape Open Açık
Proof Setup Prova Kurulumu
Properties Özellikler
Proportional Metrics Orantılı Metrikler
Insert Aki Left Sola Aki Ekle
Insert Aki Right Sağa Aki Ekle
Digits Rakamlar
Arabic Arapça
Hindi Hintçe
@@ -2698,6 +2700,8 @@ digits Malayalam Malayalam
Reset Rotate View Döndürme Görünümünü Sıfırla
Rotate View to Selection Görünümü Seçime Döndür
Reset the rows to the artwork's colors Satırları resmin renklerine göre sıfırlayın
Color Theme Picker Renk Teması Seçici
Click or drag across the art to pick its colors; Shift adds more Renklerini almak için resme tıklayın veya üzerinde sürükleyin; Shift daha fazlasını ekler
Reset to Default Varsayılana Sıfırla
Reset to White, Black Beyaz, Siyah'a Sıfırla
Reset with Mesh Mesh ile Sıfırla
@@ -3127,6 +3131,7 @@ digits Malayalam Malayalam
Show Note Notu Göster
Show Options Seçenekleri Göster
Show Recent Colors Son Renkleri Göster
Toggle RGB Percent RGB Yüzde Gösterimini Değiştir
Show Original Path Orijinal Yolu Göster
Color Panel Options Renk Paneli Seçenekleri
Show Package Paketi Göster
@@ -4001,6 +4006,85 @@ axis Both Her İkisi
@msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor
@msg a failed command changed undo steps that could not be put back, so the script was stopped başarısız bir komut geri yüklenemeyen geri alma adımlarını değiştirdi, bu yüzden betik durduruldu
@msg a recovery copy could not be written, so the script was not run kurtarma kopyası yazılamadı, bu nedenle betik çalıştırılmadı
@msg Script file access denied Betik dosyasına erişim reddedildi
@msg Script file exceeds 8 MiB Betik dosyası 8 MiB'yi aşıyor
@msg Script file is not open Betik dosyası açık değil
@msg Script file cannot be decoded Betik dosyasının kodu çözülemiyor
@msg Script file is not a regular file Betik dosyası normal bir dosya değil
@msg Script file does not exist Betik dosyası yok
@msg Script file could not be read Betik dosyası okunamadı
@msg Script folder has more than 2,048 entries Betik klasöründe 2.048'den fazla öğe var
@msg Script file open mode must be r, w, e or a Betik dosyası açma modu r, w, e veya a olmalıdır
@msg Script file writing is not available Betik dosyası yazma kullanılamıyor
@msg Script file dialogs are not available Betik dosyası iletişim kutuları kullanılamıyor
@msg Script files cannot be opened in another application Betik dosyaları başka bir uygulamada açılamaz
@msg Script file access is unavailable on the web Betik dosyası erişimi web'de kullanılamıyor
@msg Script has 256 files open Betiğin 256 açık dosyası var
@msg Script file path exceeds 32,767 characters Betik dosyası yolu 32.767 karakteri aşıyor
@msg Script folder mask takes too many steps to match Betik klasörü maskesinin eşleşmesi çok fazla adım gerektiriyor
@msg the script opened more file data than one run may open (32 MiB) betik, bir çalıştırmanın açabileceğinden fazla dosya verisi açtı (32 MiB)
@msg File.seek: takes a position and a mode File.seek: bir konum ve bir mod alır
@msg vc.run: give a command id, as a string vc.run: bir komut kimliğini dize olarak verin
@msg vc.run: takes a command id and an object of parameters vc.run: bir komut kimliği ve bir parametre nesnesi alır
@msg vc.run: the parameters must be an object vc.run: parametreler bir nesne olmalıdır
@msg vc.run: the result{place} is too large for a script vc.run: sonuç{place} bir betik için çok büyük
@msg $.evalFile requires a file path $.evalFile bir dosya yolu gerektirir
@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: zaman aşımı sonlu bir milisaniye sayısı olmalıdır, 0 veya daha fazla
@msg $.evalFile: takes a file path and a timeout $.evalFile: bir dosya yolu ve bir zaman aşımı alır
@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, satır {line}, sütun {column}: {e} (fırlatıldı)
@msg {name}: line {line}, column {column}: {e} (thrown) {name}: satır {line}, sütun {column}: {e} (fırlatıldı)
@msg {name}: {e} (thrown) {name}: {e} (fırlatıldı)
@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: {file}, satır {line}, sütun {column}: {e} (sınır)
@msg {name}: line {line}, column {column}: {e} (limit) {name}: satır {line}, sütun {column}: {e} (sınır)
@msg {name}: {e} (limit) {name}: {e} (sınır)
@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: {file}, satır {line}, sütun {column}: {e} (sözdizimi hatası)
@msg {name}: line {line}, column {column}: {e} (syntax) {name}: satır {line}, sütun {column}: {e} (sözdizimi hatası)
@msg {name}: {e} (syntax) {name}: {e} (sözdizimi hatası)
@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: {file}, satır {line}, sütun {column}: {e} (durduruldu)
@msg {name}: line {line}, column {column}: {e} (stopped) {name}: satır {line}, sütun {column}: {e} (durduruldu)
@msg {name}: {e} (stopped) {name}: {e} (durduruldu)
@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: {file}, satır {line}, sütun {column}: {e} (iç hata)
@msg {name}: line {line}, column {column}: {e} (internal) {name}: satır {line}, sütun {column}: {e} (iç hata)
@msg {name}: {e} (internal) {name}: {e} (iç hata)
@msg {e} (these files stay written: {paths}) {e} (bu dosyalar yazılmış olarak kalır: {paths})
@msg $.{name}: give a name, as a string $.{name}: bir adı dize olarak verin
@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: "en" veya "de_DE" gibi bir yerel ayar verin ya da arayüzünki için null verin
@msg $.localize: give true or false $.localize: true veya false verin
@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: yalnızca yerelleştirmeyi açan 512 veya 0 ayarlanabilir
@msg $.flags: give a number $.flags: bir sayı verin
@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: burada betikler yalnızca UTF-8 okur ve yazar
@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: bir kodlamanın adını dize olarak verin
@msg $.memCache: the memory cache size cannot be set $.memCache: bellek önbelleğinin boyutu ayarlanamaz
@msg $.setenv: give a value, as a string $.setenv: bir değeri dize olarak verin
@msg $.setenv: only {_1} can be set $.setenv: yalnızca {_1} ayarlanabilir
@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: bir değer en fazla {MAX_ENV_BYTES} harf, rakam ve _ . - @ içerir
@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: 0 ile {MAX_SLEEP_MS} arasında bir milisaniye sayısı verin
@msg $.sleep: give a number of milliseconds $.sleep: bir milisaniye sayısı verin
@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: bir çalıştırma yerleşik bir işlevin geri çağrısında, bir getter içinde, bir dönüştürmede veya $.evalFile'ın çalıştırdığı bir dosyada bekleyemez; bunu betiğin kendi kodundan çağırın
@msg $.bp: scripts here have no debugger $.bp: burada betiklerin hata ayıklayıcısı yok
@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: betikler henüz iletişim kutusu gösteremez
@msg {name}: give a message {name}: bir ileti verin
@msg {name}: give the text the field starts with {name}: alanın başladığı metni verin
@msg {name}: the message is longer than 16 KiB {name}: ileti 16 KiB'den uzun
@msg {name}: the title is longer than 256 bytes {name}: başlık 256 bayttan uzun
@msg {name}: the text the field starts with is longer than 16 KiB {name}: alanın başladığı metin 16 KiB'den uzun
@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: bir iletişim kutusu yerleşik bir işlevin geri çağrısında, bir getter içinde, bir dönüştürmede veya $.evalFile'ın çalıştırdığı bir dosyada açılamaz; bunu betiğin kendi kodundan çağırın
@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` içindeki sonraki yanıt {name} için değil, {_1} için
@msg {name}: `answers` has no answer left for this dialog {name}: `answers` içinde bu iletişim kutusu için yanıt kalmadı
@msg vc.document{place} is too large for a script vc.document{place} bir betik için çok büyük
@msg vc.log: the log of this run is full vc.log: bu çalıştırmanın günlüğü dolu
@msg this function's script run has ended bu işlevin betik çalıştırması sona erdi
@msg the script made more host calls than one run may make betik, bir çalıştırmanın yapabileceğinden daha fazla ana bilgisayar çağrısı yaptı
@msg the script passed more data to and from commands than one run may pass betik, komutlara ve komutlardan bir çalıştırmanın aktarabileceğinden daha fazla veri aktardı
@msg the script added more objects and data to the documents than one run may add betik, belgelere bir çalıştırmanın ekleyebileceğinden daha fazla nesne ve veri ekledi
@msg {what}: the object is not a File or a Folder {what}: nesne ne File ne de Folder
@msg {what}: the count must be a finite number, 0 or more {what}: sayı 0 veya daha büyük, sonlu bir sayı olmalıdır
@msg File.seek: the position must be a finite number File.seek: konum sonlu bir sayı olmalıdır
@msg File.seek: the mode must be 0, 1 or 2 File.seek: mod 0, 1 veya 2 olmalıdır
@msg script file is compiled: {value} betik dosyası derlenmiş: {value}
@msg `name` must be the name of a script engine `name` bir betik motorunun adı olmalıdır
@msg the main script engine is new for each run and is never kept, so it cannot be dropped ana betik motoru her çalıştırmada yenidir ve hiç saklanmaz, bu yüzden bırakılamaz
@msg there is no script engine named {name} {name} adlı bir betik motoru yok
@msg Running a script Betik çalıştırılıyor
@msg Copied the script report Komut dosyası raporu kopyalandı
@msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler
Can't render this file because it contains an unexpected character in line 5 and column 25.
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more