Merge main into feat/recolor-group-storage

This commit is contained in:
dotCooCoo
2026-11-15 20:02:49 -08:00
107 changed files with 6116 additions and 667 deletions
+2 -2
View File
@@ -182,7 +182,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
REVOLVE,
"Revolve…",
&["Effect", "3D and Materials"],
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
@@ -217,7 +217,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
CLASSIC_REVOLVE,
"Revolve (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
),
g(
+2 -2
View File
@@ -87,8 +87,8 @@ pub use raster::{
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
outline_text, paint_type_piece, reshape,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects,
outline_art, outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
+10
View File
@@ -900,6 +900,16 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
as_art(doc, n, symbol_art)
}
/// Symbol instance `n` as plain art for Expand Appearance, with or without geometry effects: the
/// art it places, reshaped by those effects when it has some, in the form [`expand_outlined`]
/// gives. `None` for other kinds of objects and for an instance without `symbol_art`.
pub fn instance_as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
if !matches!(n.kind, NodeKind::SymbolInstance { .. }) {
return None;
}
as_art(doc, n, symbol_art)
}
/// [`reshape`] without its checks (no geometry effects: just the art).
pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default())
+44 -32
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
use crate::solids::wireframe::{WireFace, wireframe_params};
@@ -105,6 +105,7 @@ pub fn revolve_options(p: &Value) -> Revolve {
shade: flag(p, "shade", true),
smooth_shading: true,
cap_ends: flag(p, "cap", true),
fill_rule: FillRule::NonZero,
curve_samples: None,
map_surface: false,
}
@@ -231,7 +232,7 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
return Ok(());
}
let mut caster = vectorcraft_three_d::ShadowCaster::new();
paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ()))
paths.into_iter().try_for_each(|path| caster.revolve(path, options.fill_rule, b, options).map(|_| ()))
}
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
@@ -418,7 +419,7 @@ fn cast_surface(
None => {
#[cfg(test)]
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
caster.revolve(path, options.fill_rule, b, options)
}
}
}
@@ -449,7 +450,7 @@ fn group_shadow(
if !ink.casts() {
continue;
}
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
let faces = cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, kept)?;
cast.push((s.scopes.as_slice(), ink, faces));
}
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
@@ -703,13 +704,16 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
}
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
/// [`surface`] adds to; its graphics take the symbols of `doc`.
/// A surface of one object about the bounds of `path`, filled with `rule`, built with options
/// derived from `fx` ([`rule_options`]), and when `fx` casts a shadow from it, the faces it is cast
/// from ([`surface`]). `copies` is the count [`surface`] adds to; its graphics take the symbols of
/// `doc`.
#[allow(clippy::too_many_arguments)]
fn object_surface(
doc: Option<&Document>,
n: &Node,
path: &PathData,
rule: FillRule,
fx: &Effect,
item: &AppearanceItem,
expand: bool,
@@ -718,10 +722,16 @@ fn object_surface(
let b = path.bounds()?;
let (paint, opacity, blend) = paint_of(item);
let cast = casts(fx, opacity);
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast)
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast)
.map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept))
}
/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides
/// leave open the holes `rule` leaves in the profile.
fn rule_options(fx: &Effect, rule: FillRule) -> Revolve {
Revolve { fill_rule: rule, ..fx_options(fx) }
}
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
/// that color: across the face with its smooth shading, under colored lights (`colored`) with
/// their color.
@@ -840,13 +850,13 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
let options = shared_options(&shapes, fx_options(fx))?;
let mut out = vec![];
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
out.extend(faces(&s.path, b, fx, options)?);
out.extend(faces(&s.path, b, fx, Revolve { fill_rule: s.rule, ..options })?);
}
// In wireframe mode the canvas draws no shadow.
let shadow = if crate::solids::renders_wireframe(fx) { vec![] } else { group_shadow(n.id, fx, &shapes, b, options, vec![])? };
return Ok((out, shadow));
}
let (path, _) = object_profile(n, "Revolve")?;
let (path, rule) = object_profile(n, "Revolve")?;
let ctx = GeomContext::of(n);
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], vec![])) };
@@ -854,8 +864,8 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
let paints = solid_paints(n);
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let surface = faces(&path, b, fx, fx_options(fx))?;
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)? };
let surface = faces(&path, b, fx, rule_options(fx, rule))?;
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), None)? };
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
@@ -866,7 +876,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
{
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let surface = faces(&p, b, fx, fx_options(fx))?;
let surface = faces(&p, b, fx, rule_options(fx, rule))?;
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
@@ -884,13 +894,14 @@ fn wire_faces(path: &PathData, b: Rect, fx: &Effect, options: Revolve) -> Result
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
}
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept
/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]).
/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art.
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, each with
/// its fill rule, all swept about the bounds `b` with `options`: the edges of their faces
/// ([`crate::solids::wireframe::wire_art`]). `None` when a profile can't be swept or past the edge
/// limit, when the canvas draws the source art.
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = (&'a PathData, FillRule)>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
let mut faces = vec![];
for path in paths {
faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path));
for (path, rule) in paths {
faces.extend(wire_faces(path, b, fx, Revolve { fill_rule: rule, ..options }).ok()?.into_iter().map(|f| f.path));
}
crate::solids::wireframe::wire_art(id, &faces)
}
@@ -940,11 +951,11 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
if crate::solids::renders_wireframe(fx) {
// In wireframe mode the edges of the faces, with no shadow.
children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?);
children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?);
} else {
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
let (surface, kept) = object_surface(doc, n, &path, rule, fx, item, expand, &mut copies)?;
if let Some(b) = path.bounds()
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), kept).ok()?
{
children.push(Arc::new(shadow));
}
@@ -970,16 +981,16 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
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));
if crate::solids::renders_wireframe(fx) {
let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?;
let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?;
Arc::make_mut(&mut art).appearance.effects =
item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
children.push(art);
continue;
}
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
let (mut art, kept) = object_surface(doc, n, &p, rule, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
if let Some(b) = p.bounds()
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()?
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()?
{
shadow.appearance.effects = art.appearance.effects.clone();
shadows.push(Arc::new(shadow));
@@ -1127,7 +1138,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let options = shared_options(&shapes, fx_options(fx)).ok()?;
if crate::solids::renders_wireframe(fx) {
// In wireframe mode the edges of every member's faces, with no shadow.
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path);
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule));
let mut art = n.clone();
art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false };
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
@@ -1157,6 +1168,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let expand = expand && s.scopes.is_empty();
let doc = doc.filter(|_| longest == Some(k));
let cast = casts(fx, opacity * s.opacity);
let options = Revolve { fill_rule: s.rule, ..options };
let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
surfaces.push((depths, art, s.scopes.as_slice()));
kept.push(faces);
@@ -2088,7 +2100,7 @@ mod tests {
let mut fx = crate::new_effect(id, &json!({})).unwrap();
fx.params = params.clone();
let n = profile_node();
let (path, _) = profile(&n).unwrap();
let (path, rule) = profile(&n).unwrap();
let b = path.bounds().unwrap();
let mut half = n.clone();
if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] {
@@ -2096,9 +2108,9 @@ mod tests {
}
for n in [n, half] {
let item = surface_item(&n.appearance.items).unwrap();
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap();
let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap();
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
let drawn = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), kept).unwrap();
let alone = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), None).unwrap();
assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}");
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
}
@@ -2164,11 +2176,11 @@ mod tests {
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
f.opacity = bad;
}
let (path, _) = profile(&n).unwrap();
let (path, rule) = profile(&n).unwrap();
let b = path.bounds().unwrap();
let item = surface_item(&n.appearance.items).unwrap();
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
let shadows = group_shadows(&group(bad));
+176 -46
View File
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
can_expand,
expand_appearance
),
@@ -963,16 +963,74 @@ fn is_container(n: &Node) -> bool {
/// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at
/// the document's raster effects resolution or a Rasterize effect's finer one, with whether they
/// all paint below it (shadows and outer glows: the image then holds just them). A group's or
/// layer's image leaves out its members' raster effects, which are expanded with them. `None`
/// when it has none.
fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
/// all paint below it (shadows and outer glows: the image then holds just them, and paints with
/// their blend mode when they all use one). A group's or layer's image leaves out its members'
/// raster effects, which are expanded with them. `None` when it has none.
/// `Err` when that image would take `budget` past its limits: the object then stays as it is.
fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result<Option<(Node, bool)>, OverBudget> {
let fx = rasterfx::raster_fx(n);
if fx.is_empty() {
return None;
return Ok(None);
}
let below = fx.iter().all(effects::RasterFx::is_below);
Some((rasterfx::raster_image(d, n, below, true)?, below))
let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?;
let mut image = rasterfx::raster_image(d, n, below, true);
if image.is_none() {
// No image was made: it takes nothing from the budget.
budget.images += 1;
budget.pixels += pixels;
}
// Rendered alone, over nothing, the shadows and glows can't blend with the art below the
// object, so the image does, as the canvas draws them.
let mut modes = fx.iter().filter_map(effects::RasterFx::mode);
if below
&& let (Some(mode), Some(image)) = (modes.next(), image.as_mut())
&& modes.all(|m| m == mode)
{
image.blend = mode;
}
Ok(image.map(|image| (image, below)))
}
/// The most images of raster effects one Expand Appearance makes.
const MAX_RASTER_IMAGES: u32 = 1_024;
/// The most pixels the images of raster effects one Expand Appearance makes hold in all.
const MAX_RASTER_PIXELS: u64 = 256_000_000;
/// The note when objects keep their raster effects because their images would take an Expand
/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`].
pub(crate) const RASTER_EFFECTS_LEFT: &str =
"some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all";
/// An image of raster effects that would take a [`RasterBudget`] past its limits.
#[derive(Debug)]
struct OverBudget;
/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the
/// objects whose raster effects it left as they are because their images would go past them.
pub(crate) struct RasterBudget {
images: u32,
pixels: u64,
pub(crate) left: usize,
}
impl RasterBudget {
pub(crate) fn new() -> Self {
Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 }
}
/// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return
/// them; `Err`, with its object counted in `left`, when it would go past what is left.
fn take(&mut self, pixels: u64) -> std::result::Result<u64, OverBudget> {
if self.images == 0 || pixels > self.pixels {
self.left += 1;
return Err(OverBudget);
}
self.images -= 1;
self.pixels -= pixels;
Ok(pixels)
}
}
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
@@ -983,6 +1041,7 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
/// the member's new id.
#[allow(clippy::too_many_arguments)]
fn expand_pieces(
d: &mut Document,
m: &mut Node,
@@ -991,6 +1050,7 @@ fn expand_pieces(
skip: &[NodeId],
kept: &mut Vec<NodeId>,
stroke_art: effects::StrokeArt,
raster: &mut RasterBudget,
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
let id = m.id;
let mut seen = std::collections::HashSet::from([id]);
@@ -1005,7 +1065,7 @@ fn expand_pieces(
if all || c.id == id {
effects::expand_art(d, c, stroke_art);
} else if has_seeded(c) && repeats_an_id(c, &seen) {
listed = Some(expand_in_place(d, c, brushes, skip));
listed = Some(expand_in_place(d, c, brushes, skip, raster));
}
let mut was = vec![];
if !skip.is_empty() {
@@ -1030,37 +1090,65 @@ fn expand_pieces(
}
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as
/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so
/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more
/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art
/// would take the objects placed so far past `budget`.
fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) {
/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`],
/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in
/// that art in turn, so [`expand_pieces`] bakes their effects with the rest.
fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) {
for c in m.children_mut().into_iter().flatten() {
if !matches!(c.kind, NodeKind::SymbolInstance { .. }) {
if c.children().is_some() {
expand_nested_instances(d, Arc::make_mut(c), depth, budget);
expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster);
}
continue;
}
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue };
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) {
continue;
}
let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue };
let count = sym.art.count() as u64;
if count > *budget {
continue;
}
*budget -= count;
let art = vectorcraft_render::instance_art(&sym.art, c);
if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) {
expand_nested_instances(d, &mut a, depth + 1, budget);
if let Some(a) = expanded_instance(d, c, depth, budget, raster) {
*c = Arc::new(a);
}
}
}
/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster
/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art
/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as
/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when
/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance
/// staying as it is, when its active fill and stroke have no such effect, it is more than
/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would
/// take the objects placed so far past `budget`, or the image of its raster effects would take
/// `raster` past its limits. When that image can't be made, they stay on the art its geometry
/// effects make, and without one it stays as it is.
fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option<Node> {
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None };
let has_raster = effects::has_instance_row_raster(c);
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) {
return None;
}
let sym = d.symbols.iter().find(|s| s.name == *symbol)?;
let count = sym.art.count() as u64;
if count > *budget {
return None;
}
let art = vectorcraft_render::instance_art(&sym.art, c);
let image = if has_raster { raster_image(d, c, raster).ok()? } else { None };
*budget -= count;
let mut v = c.clone();
if image.is_some() {
rasterfx::strip_raster(&mut v, false);
}
let below = match image {
Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)),
Some((image, true)) => Some(image),
None => None,
};
let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art))
.or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?;
expand_nested_instances(d, &mut a, depth + 1, budget, raster);
if let Some(image) = below {
rasterfx::put_below(d, &mut a, image);
}
Some(a)
}
/// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids?
fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
let mut ids = std::collections::HashSet::new();
@@ -1075,9 +1163,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
type Listed = (NodeId, usize);
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Vec<Listed> {
let mut listed = vec![];
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed, raster) {
*c = e;
}
listed
@@ -1099,18 +1187,26 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
/// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and
/// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art),
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
/// transparency.
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
expand_node_except(d, id, brushes, &[], out);
/// transparency. An object whose raster effects' image would take `raster` past its limits stays
/// as it is, with what is inside it.
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>, raster: &mut RasterBudget) {
expand_node_except(d, id, brushes, &[], out, raster);
}
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
/// copies of it that such an effect makes are left as they are too.
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
fn expand_node_except(
d: &mut Document,
id: NodeId,
brushes: &[vectorcraft_brush::Brush],
skip: &[NodeId],
out: &mut Vec<NodeId>,
raster: &mut RasterBudget,
) {
let Some(n) = d.node(id).cloned() else { return };
let mut listed = vec![];
let m = expanded_node(d, n, brushes, skip, &mut listed);
let m = expanded_node(d, n, brushes, skip, &mut listed, raster);
out.extend(listed.into_iter().map(|(id, _)| id));
if let Some(mut m) = m {
// Art made from type takes its emoji's pixels into the document.
@@ -1124,11 +1220,20 @@ fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
fn expanded_node(
d: &mut Document,
mut n: Node,
brushes: &[vectorcraft_brush::Brush],
skip: &[NodeId],
out: &mut Vec<Listed>,
raster: &mut RasterBudget,
) -> Option<Node> {
let id = n.id;
if skip.contains(&id) || !expandable(&n) {
return None;
}
// What `out` held before `n`: an object left by the raster budget lists nothing.
let listed_before = out.len();
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
// recoloured copy), then the rest of the appearance expands.
let mut changed = false;
@@ -1141,6 +1246,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
_ => None,
};
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
// is: the recolored copies the adjustment adds then go again.
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
if effects::has_adjustment(&n)
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
{
@@ -1163,7 +1272,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
let c = Arc::make_mut(c);
if i == 0 {
expanded = expand_in_place(d, c, brushes, skip);
expanded = expand_in_place(d, c, brushes, skip, raster);
fresh_ids_listed(d, c, &mut seen, &mut expanded);
} else {
effects::fresh_ids(d, c, &mut seen);
@@ -1186,7 +1295,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
return Some(m);
}
let image = raster_image(d, &n);
// Raster effects whose image would go past the budget stay: so does the object, with what is
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
let Ok(image) = raster_image(d, &n, raster) else {
out.truncate(listed_before);
if let Some(keys) = images_before {
d.images.retain(|k, _| keys.contains(k));
}
return None;
};
let mut v = n.clone();
rasterfx::strip_raster(&mut v, false);
let mut stroke_art =
@@ -1206,7 +1323,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
m
})
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
@@ -1224,10 +1341,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
_ => None,
};
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
// A symbol instance whose active fill or stroke has only effects that paint below it
// (now in the image) becomes its art as well.
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
outlined.map(|mut m| {
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
expand_nested_instances(d, &mut m, 1, &mut budget);
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
m
})
};
@@ -1262,7 +1384,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
match members.remove(&c.id) {
Some(listed) => out.extend(listed),
None => {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out, raster) {
*c = Arc::new(e);
changed = true;
}
@@ -1336,6 +1458,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
}
let failed = vectorcraft_render::decode_failures();
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let mut raster = RasterBudget::new();
let ids = s.edit("Expand Appearance", |d, _| {
let before = d.clone();
// The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose
@@ -1351,7 +1474,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let mut out = vec![];
let threaded = super::threads::frames(d);
for id in &roots {
expand_node_except(d, *id, &brushes, &designs, &mut out);
expand_node_except(d, *id, &brushes, &designs, &mut out, &mut raster);
}
super::dimension::put_back(d, lifted);
// A dimension whose source was replaced stays where it was, no longer linked.
@@ -1360,6 +1483,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
// stays type under a new id takes its frame's place.
super::threads::leave_threads(d, &threaded);
if out.is_empty() || (kept && d.layers == before.layers) {
if raster.left > 0 {
return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into()));
}
return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into()));
}
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?;
@@ -1367,8 +1493,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
})?;
let mut out = json!({ "ids": ids_json(&ids) });
// Raster effects become images rendered from the art.
if let Some(w) = rasterfx::undecoded_warning(failed) {
out["warning"] = json!(w);
let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect();
if !warnings.is_empty() {
out["warning"] = json!(warnings.join("; "));
}
if raster.left > 0 {
out["rasterLeft"] = json!(raster.left);
}
Ok(out)
}
+25
View File
@@ -1082,3 +1082,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
}
/// The raster budget charges each image its pixels before it is made: an image past what is left
/// is refused and counted, and the object keeps its blur.
#[test]
fn an_image_past_the_pixels_left_stays_unmade() {
let (mut s, id) = session_with_rect();
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap();
let mut d = s.doc().unwrap().doc.as_ref().clone();
let n = d.node(id).cloned().unwrap();
let pixels = super::rasterfx::raster_pixels(&d, &n, false, true);
assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}");
let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 };
assert!(super::raster_image(&mut d, &n, &mut budget).is_err());
assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken");
let mut budget = super::RasterBudget { images: 10, pixels, left: 0 };
let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made");
let NodeKind::Image(img) = &image.kind else { panic!("not an image") };
assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size");
assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0));
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
}
+9 -4
View File
@@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
let one = super::save::artboard_doc(doc, b);
let (full, placed) = crate::cmd::place::document::full_documents(&one);
let mut d = full.into_owned();
expand_appearances(&mut d);
if expand_appearances(&mut d) {
note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT);
}
if mode == SeeThrough::Flatten {
expand_image_patterns(&mut d)?;
}
@@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
Ok(enc)
}
/// Expand Appearance of every layer's art whose appearance the format can't hold.
fn expand_appearances(d: &mut Document) {
/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether
/// objects kept raster effects whose images would go past Expand Appearance's limits.
fn expand_appearances(d: &mut Document) -> bool {
let brushes = vectorcraft_brush::library(d);
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
let mut out = vec![];
let mut raster = super::super::effectcmd::RasterBudget::new();
for id in layers {
super::super::effectcmd::expand_node(d, id, &brushes, &mut out);
super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster);
}
raster.left > 0
}
/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint,
+1 -1
View File
@@ -764,7 +764,7 @@ fn leave_out_folder(r: &mut Value, folder: &str) {
/// Export settings kept in the document or a preset, as the request being served may see them: a
/// `folder` outside the read roots ([`super::access::shown`]) is left out.
fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
pub(super) fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) {
settings.remove("folder");
}
+13 -1
View File
@@ -180,12 +180,24 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
})
}
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
/// outside the read roots of the request being served (the open document keeps it).
fn native_attachment(doc: &Document) -> Vec<u8> {
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
if settings.len() == doc.export_settings.len() {
return vectorcraft_format::save(doc, false);
}
let mut kept = doc.clone();
kept.export_settings = settings;
vectorcraft_format::save(&kept, false)
}
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
/// link to and the writer's warnings.
pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Encoded, String> {
let (opts, boards, chosen) = plan(doc, p)?;
// Preserve editing embeds the native document (once, shared by every file).
let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false));
let native = opts.preserve_editing.then(|| native_attachment(doc));
// Draw linked files as vectors when available, or their previews with a warning. Keep
// that preparation out of the native attachment so missing links remain relinkable.
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
+39
View File
@@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
font_list
),
cmd!(
query "text.similarFonts",
"Show Similar Fonts",
[],
None,
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
always,
similar_fonts
),
cmd!(
query "text.glyphCategories",
"Glyph Categories",
@@ -1146,6 +1155,36 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
}
}
/// The most families `text.similarFonts` takes as its `limit`.
const MAX_SIMILAR: u64 = 100_000;
fn similar_fonts(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.similarFonts";
let db = vectorcraft_text::FontDb::global();
let family = match p.get("family") {
Some(Value::String(f)) if !f.trim().is_empty() => f.as_str(),
Some(Value::String(_)) | None => return Err(bad(C, "`family` is required")),
Some(_) => return Err(bad(C, "`family` must be a string")),
};
let limit = match p.get("limit") {
None => None,
Some(v) => Some(
v.as_u64()
.filter(|n| (1..=MAX_SIMILAR).contains(n))
.ok_or_else(|| bad(C, format!("`limit` must be a whole number from 1 to {MAX_SIMILAR}")))?,
),
};
// Any of the family's names, spelled as the font menus list it; a family they don't list is not available.
let menu = db.menu_family_list();
let listed = db.has_family(family).then(|| db.canonical(family, "").0).and_then(|c| menu.iter().find(|f| f.eq_ignore_ascii_case(&c)).cloned());
let Some(family) = listed else { return Err(bad(C, format!("font family `{family}` is not available"))) };
let mut families = db.similar_families(&family, &menu);
if let Some(n) = limit.and_then(|n| usize::try_from(n).ok()) {
families.truncate(n);
}
Ok(json!({ "family": family, "families": families }))
}
/// `text.glyphCategories`: the OpenType categories of a font's glyphs
/// ([`vectorcraft_text::FontFace::glyph_categories`]).
fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> {
+156 -23
View File
@@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Crop Image",
["Object"],
None,
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false), ppi?: number (without trim: the cropped image's resolution in pixels per inch, resampled from the cut pixels; 1 to 2400, at most the image's own, or 300 for a linked image; default the image's own; a rect over the whole image with a new ppi only resamples it)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
has_image,
crop_image
),
@@ -967,10 +967,10 @@ fn polygon_path(pts: &[Point]) -> PathData {
PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true))
}
/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and
/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or
/// `r` not on the pixel grid), so the caller draws it instead.
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec<u8>, u32, u32, Affine)> {
/// The part of an image under `r` (in document space) copied out of its pixels, with its placement. `None` when
/// the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or `r` not on the pixel
/// grid), so the caller draws it instead.
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(image::RgbaImage, Affine)> {
let blob = doc.images.get(&im.key)?;
let [a, b, c, d, _, _] = im.xf.as_coeffs();
if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 {
@@ -996,9 +996,85 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op
return None;
}
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
}
/// Crop Image's `ppi`: the resolution asked for, in pixels per point, and whether it keeps the image's pixels as
/// they are (its own, with square pixels); `None` for the image's own. Refuses a resolution that isn't a positive
/// number or is above what the image allows: its own, or 300 ppi for a linked image, within 1 to 2400 ppi as
/// Rasterize's.
fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<(f64, bool)>> {
const C: &str = "object.cropImage";
let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) };
let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?;
if !(1.0..=2400.0).contains(&ppi) {
return Err(bad(C, "ppi must be between 1 and 2400"));
}
let (_, max) = vectorcraft_tools::cropimage::image_ppi(im);
if ppi > max + 1e-6 {
let max = (max * 100.0 + 1e-6).floor() / 100.0;
return Err(bad(C, format!("ppi can't be more than {max} for this image")));
}
// An image whose pixels are not square is resampled on both sides, even at its denser side's resolution.
Ok(Some((ppi / 72.0, vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6))))
}
/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and
/// no side past the renderer's).
fn check_crop_size(w: f64, h: f64) -> Result<()> {
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
if w * h > MAX_PIXELS || w > side || h > side {
let (w, h) = (w as u64, h as u64);
return Err(bad("object.cropImage", format!("an image of {w} × {h} pixels is too large to draw")));
}
Ok(())
}
/// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully
/// transparent pixel does not show at the edges of what is opaque. The weighted colors are held in
/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. An error when
/// the working copies would not fit ([`check_resample_size`]).
fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> Result<image::RgbaImage> {
check_resample_size(img.width(), img.height(), w, h)?;
let mut pre = image::ImageBuffer::<image::Rgba<u16>, Vec<u16>>::new(img.width(), img.height());
for (d, s) in pre.pixels_mut().zip(img.pixels()) {
let a = u32::from(s[3]);
for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) {
// c × 257 × a / 255, rounded: the color scaled to 16 bits and weighted.
*dc = ((u32::from(*sc) * 257 * a + 127) / 255) as u16;
}
d.0[3] = (a * 257) as u16;
}
let out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3);
let mut res = image::RgbaImage::new(out.width(), out.height());
for (d, s) in res.pixels_mut().zip(out.pixels()) {
let a = u64::from(s[3]);
for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) {
// c × 65535 / a back to 8 bits (÷ 257), rounded: c × 255 / a.
*dc = (u64::from(*sc) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8;
}
d.0[3] = ((a + 128) / 257).min(255) as u8;
}
Ok(res)
}
/// Whether resampling a `sw` × `sh` image to `w` × `h` fits in [`MAX_RASTER_ALLOC`]: the source and
/// its weighted 16-bit copy (12 bytes a pixel), the resampler's float rows between its two passes
/// (16 bytes a pixel, `sw` × `h`) and the 16-bit and 8-bit results (12 bytes a pixel of `w` × `h`).
pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<()> {
let (sw, sh, w, h) = (u64::from(sw), u64::from(sh), u64::from(w), u64::from(h));
let bytes = (sw * sh).saturating_mul(12).saturating_add((sw * h).saturating_mul(16)).saturating_add((w * h).saturating_mul(12));
if bytes > crate::cmd::fileio::MAX_RASTER_ALLOC {
return Err(bad("object.cropImage", format!("an image of {sw} × {sh} pixels is too large to resample")));
}
Ok(())
}
/// `img` as PNG bytes.
fn encode_png(img: &image::RgbaImage) -> Result<Vec<u8>> {
let mut png = Vec::new();
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?;
Ok(png)
}
fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1014,9 +1090,15 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
if switch_or(p, "trim", false, C)? {
if p.get("ppi").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
}
return trim_image(s, id, (**im).clone());
}
let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
let asked = crop_resolution(p, im)?;
// The resolution the image's pixels are resampled to when they are cut straight.
let target = asked.and_then(|(t, keeps)| (!keeps).then_some(t));
let rect = match p.get("rect").filter(|v| !v.is_null()) {
Some(Value::Array(a)) if a.len() == 4 => {
let v: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();
@@ -1038,16 +1120,49 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
if r.width() <= 0.0 || r.height() <= 0.0 {
return Err(bad(C, "crop rectangle doesn't overlap the image"));
}
if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 {
// A box over the whole image still resamples it to a new resolution.
let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6;
// A turned or skewed image is drawn, so a resolution asked for, even its own, still makes a new image.
let [_, xb, xc, _, _, _] = im.xf.as_coeffs();
let turned = xb.abs() > 1e-9 || xc.abs() > 1e-9;
if whole && target.is_none() && (asked.is_none() || !turned) {
return Err(bad(C, "nothing to crop"));
}
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled.
if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) {
put_pixels(s, id, png, cw, ch, xf)?;
if let Some(t) = target {
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
}
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled unless a
// resolution is asked for.
if let Some((cut, xf)) = crop_pixels(&st.doc, im, r) {
let (cut, xf) = match target {
Some(t) => {
let (cw, ch) = cut.dimensions();
let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
let resized = resize_premultiplied(&cut, w, h)?;
(resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h)))
}
None => (cut, xf),
};
let (cw, ch) = cut.dimensions();
put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?;
return Ok(json!({ "id": id.0, "width": cw, "height": ch }));
}
// Keep the image's pixel density.
let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
// A drawn crop is made at a resolution asked for even when it is the image's own: the box of a
// turned or skewed image holds fewer of its pixels a point than the image does.
let target = asked.map(|(t, _)| t);
if let Some(t) = target {
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
}
// Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more
// than the image's own, measured on its pixel grid however it is turned, nor past the size a
// drawing may have), and resampled to it.
let native = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
let scale = target.map_or(native, |t| {
let own = native.max(vectorcraft_tools::cropimage::image_ppi(im).0 / 72.0);
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
let budget = (MAX_PIXELS / (r.width() * r.height()).max(1e-9)).sqrt().min(side / r.width().max(1e-9)).min(side / r.height().max(1e-9));
(2.0 * t).min(own).min(budget).max(t.min(own))
});
let mut bare = node.clone();
bare.opacity = 1.0;
bare.blend = Default::default();
@@ -1058,23 +1173,41 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(e) = bare.extras_if_any() {
e.color_mask = None;
}
let (dw, dh) = ((r.width() * scale).round().max(1.0), (r.height() * scale).round().max(1.0));
let region = Rect::new(r.x0, r.y0, r.x0 + dw / scale, r.y0 + dh / scale);
// At a resolution asked for, the drawing is fitted to the box below: the image is stretched
// about the box's corner so the box fills the whole pixels drawn, and nothing past it is drawn.
if target.is_some()
&& let NodeKind::Image(bi) = &mut bare.kind
{
let o = r.origin().to_vec2();
bi.xf = Affine::translate(o)
* Affine::scale_non_uniform(region.width() / r.width(), region.height() / r.height())
* Affine::translate(-o)
* bi.xf;
}
let tmp = isolated_doc(&st.doc, vec![bare]);
let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale);
let (png, w, h, warning) =
render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?;
// At a resolution asked for, the drawing is resampled to the box's size at that resolution and
// fitted to the box, so the image keeps its size.
let (png, w, h, xf) = match target {
Some(t) => {
let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.into_rgba8();
// Only the decoded pixels are held while they are resampled.
drop(png);
let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
let resized = resize_premultiplied(&drawn, tw, th)?;
let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th));
(encode_png(&resized)?, tw, th, xf)
}
None => (png, w, h, Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale)),
};
s.edit("Crop Image", |d, _| {
let key = unique_key(d, "crop");
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
if let Some(n) = d.node_mut(id) {
n.kind = NodeKind::Image(Box::new(ImageObject {
key,
width: w,
height: h,
xf: Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale),
link: None,
placement: Default::default(),
pixels: None,
}));
n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }));
}
Ok(())
})?;
+24 -8
View File
@@ -166,15 +166,18 @@ const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
/// An instance in another symbol's art is placed by that symbol's instances and is left as it is.
/// A document without pixel-aligned symbols is not walked.
/// An instance in another symbol's art, the art on the symbol editing layer included, is placed by
/// that symbol's instances and is left as it is. A document without pixel-aligned symbols is not walked.
fn refresh_symbols(before: &Document, doc: &mut Document) {
let aligned = doc.pixel_aligned_symbols();
if aligned.is_empty() {
return;
}
let was = before.pixel_aligned_symbols();
// The symbol whose editing mode this edit ended, if any.
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
let edited_now = doc.symbol_edit.as_ref().map(|e| e.symbol.as_str());
let edit_ended = edited_before.filter(|b| edited_now != Some(*b)).map(str::to_owned);
let mut every = false;
for name in &aligned {
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
@@ -184,22 +187,29 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
_ => true,
};
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed {
if !was.contains(name) || edit_ended.as_deref() == Some(name.as_str()) || art_changed || size_changed {
snap_symbol_art(doc, name);
every = true;
}
}
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
// The symbol editing layer holds another symbol's art.
let editing = doc.symbol_edit.as_ref().map(|e| e.layer);
if every {
for layer in doc.layers.iter_mut() {
if holds_instance(layer, &natural) {
if Some(layer.id) != editing && holds_instance(layer, &natural) {
snap_instances_in(Arc::make_mut(layer), &natural);
}
}
return;
}
let (mut ids, mut masked) = (vec![], vec![]);
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
if let Some(layer) = editing {
let outside = |layers: &[Arc<Node>]| layers.iter().filter(|l| l.id != layer).cloned().collect::<Vec<_>>();
changed_instances(&outside(&before.layers), &outside(&doc.layers), &natural, &mut ids, &mut masked);
} else {
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
}
for id in ids {
if let Some(n) = doc.node_mut(id) {
snap_instance(n, &natural);
@@ -358,9 +368,10 @@ fn snap_mask(n: &mut Node) -> bool {
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
/// rotated (a half turn included) or sheared instance stays where it is.
/// rotated (a half turn included) or sheared instance stays where it is. The instance moves as any
/// move moves it ([`Node::transform`]), so the art of a linked opacity mask moves with it.
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return };
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return };
let Some(nat) = natural.get(symbol.as_str()) else { return };
let [a, b, c, d, e, f] = xf.as_coeffs();
let [na, _, _, nd, _, _] = nat.as_coeffs();
@@ -373,7 +384,12 @@ fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
return;
}
let (x, y) = (e.round(), f.round());
if x != e || y != f {
if x == e && y == f {
return;
}
n.transform(Affine::translate((x - e, y - f)), Scaling::default());
// Whole points exactly, which adding the offset to the old position need not give.
if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind {
*xf = Affine::new([a, b, c, d, x, y]);
}
}
@@ -704,8 +704,9 @@ pub(super) const ALLOWED: &[&str] = &[
];
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
/// preferences, a tool's options, a drag's state or the font names the whole app knows, run
/// plug-ins again, or read a file and report where it is on disk.
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and
/// report where it is on disk.
pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
@@ -718,5 +719,6 @@ pub(super) const DENIED: &[&str] = &[
"object.pathfinder.options",
"stroke.arrowheads.edit",
"stroke.arrowheads.list",
"text.similarFonts",
"type.compositeFonts.set",
];
+90 -36
View File
@@ -174,19 +174,14 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 {
(doc.raster_effects_ppi / 72.0).clamp(1.0 / 72.0, 2400.0 / 72.0)
}
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
/// of the image, which then only holds what the effects add around it (a shadow to go under the
/// vector object). The document's raster effects settings add room around it and finish its pixels.
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
/// positive, or when its PNG can't be encoded.
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
/// The region [`effect_image`] renders `whole` over in `d`, and the scale it renders at (`scale`, or
/// less for an image past 64 Mpx or a side the renderer can't address). `None` when it paints
/// nothing, when the area it covers overflows `f64` or the scale is not positive.
fn effect_region(d: &Document, whole: &Node, scale: f64) -> Option<(Rect, f64)> {
// What it paints (its members' effects included), and how far its fills' and strokes' raster
// effects reach beyond that.
let b = vectorcraft_render::painted_bounds(out, whole)?;
let look = out.raster_effects.clone();
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around;
let b = vectorcraft_render::painted_bounds(d, whole)?;
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + d.raster_effects.add_around;
let b = b.inflate(reach, reach);
// An area too large for f64 gives a zero scale and an image transform that is not finite.
let area = b.width() * b.height();
@@ -201,6 +196,19 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N
return None;
}
let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale);
Some((region, scale))
}
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
/// of the image, which then only holds what the effects add around it (a shadow to go under the
/// vector object). The document's raster effects settings add room around it and finish its pixels.
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
/// positive, or when its PNG can't be encoded.
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
let (region, scale) = effect_region(out, whole, scale)?;
let look = out.raster_effects.clone();
// Anti-alias off: hard edges (the effects themselves stay smooth).
let anti_alias = if look.anti_alias { AntiAlias::Art } else { AntiAlias::None };
let mut img = render(out, vec![whole.clone()], region, scale, anti_alias);
@@ -311,6 +319,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
if !below && let Some(image) = rasterize_effect_image(d, n) {
return Some(image);
}
let whole = effect_art(n, below, members);
let bare = below.then(|| {
let mut b = whole.clone();
strip_raster(&mut b, false);
b
});
effect_image(d, &whole, bare.as_ref(), image_scale(d, n))
}
/// The art [`raster_image`] renders the raster effects of `n` from with `below` and `members`:
/// `n` without its transparency, a group's or layer's members without their raster effects when
/// both are set.
fn effect_art(n: &Node, below: bool, members: bool) -> Node {
let mut whole = n.clone();
(whole.opacity, whole.blend) = (1.0, Default::default());
whole.extras_mut().mask = None;
@@ -319,17 +340,39 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
strip_raster(Arc::make_mut(c), true);
}
}
let bare = below.then(|| {
let mut b = whole.clone();
strip_raster(&mut b, false);
b
});
// A Rasterize effect at a finer resolution than the document's is rendered at its own.
let scale = raster_fx(n)
.iter()
.filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None })
.fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0));
effect_image(d, &whole, bare.as_ref(), scale)
whole
}
/// Pixels per point of the image of the raster effects of `n`: the document's raster effects
/// resolution, or a Rasterize effect's finer one, which is rendered at its own.
fn image_scale(d: &Document, n: &Node) -> f64 {
raster_fx(n).iter().filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }).fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0))
}
/// The pixels of the image [`raster_image`] makes of the raster effects of `n` in `d` with `below`
/// and `members`, as [`effect_image`] sizes it, or at the resolution and with the room around the
/// art of the object's own Rasterize effect when that is its only one ([`rasterize_effect_image`]);
/// 0 when it paints nothing.
pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool) -> u64 {
if !below && let Some((art, r, _)) = rasterize_effect_art(d, n) {
// Measured as Object › Rasterize measures it.
let scale = r.ppi.unwrap_or(d.raster_effects_ppi) / 72.0;
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
let size = vectorcraft_render::drawn_bounds(d, &art).map(|b| {
let b = b.inflate(r.add_around, r.add_around);
((b.width() * scale).ceil().max(1.0), (b.height() * scale).ceil().max(1.0))
});
// Past Object › Rasterize's limits that image is not made, and the effect's image is.
if let Some((w, h)) = size
&& w * h <= super::menucmds::MAX_PIXELS
&& w <= side
&& h <= side
{
return (w * h) as u64;
}
}
effect_region(d, &effect_art(n, below, members), image_scale(d, n))
.map_or(0, |(r, scale)| ((r.width() * scale).round() * (r.height() * scale).round()) as u64)
}
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
@@ -339,15 +382,7 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
let staged = vectorcraft_render::rasterize_stage(d, n);
if let Some((_, map)) = &staged
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
{
return None;
}
let n = staged.as_ref().map_or(n, |(stage, _)| stage);
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
let (whole, r, map) = rasterize_effect_art(d, n)?;
let p = json!({
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
"colorModel": r.color_model.id(),
@@ -356,20 +391,39 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
"clippingMask": r.clipping_mask,
"addAround": r.add_around,
});
let mut whole = n.clone();
whole.appearance.effects.remove(at);
(whole.opacity, whole.blend) = (1.0, Default::default());
whole.extras_mut().mask = None;
// shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the
// image's transparency would need one too; upgrade when CMYK images carry alpha.
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
let mut image = image.into_node(d);
if let Some((_, map)) = staged {
if let Some(map) = map {
image.transform(map, false);
}
Some(image)
}
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
/// that move the image, without the Rasterize effect and without its transparency; that effect's
/// options; and the map those Transform effects move the image by. `None` when `n` has another
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
/// flatten the image.
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
let staged = vectorcraft_render::rasterize_stage(d, n);
if let Some((_, map)) = &staged
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
{
return None;
}
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
let n = stage.as_ref().unwrap_or(n);
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
let mut whole = n.clone();
whole.appearance.effects.remove(at);
(whole.opacity, whole.blend) = (1.0, Default::default());
whole.extras_mut().mask = None;
Some((whole, r, map))
}
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
/// image takes its place with its id, name and transparency (a layer keeps the image as its only
/// member).
+134 -6
View File
@@ -7,17 +7,20 @@
//! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All
//! (`text.spelling.ignoreAll`) skips a word in the active document only.
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::ops::Range;
use std::sync::atomic::{AtomicU64, Ordering};
use craft_proof::{IssueKind, Options, ProofLang};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject};
use vectorcraft_text::edit;
use super::menucmds::whole_or;
use super::textedit::text_mut;
use super::typecmd::refresh_bounds;
use super::typemenu::{all_texts, text_ids};
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
/// Most unknown words one check lists; past it the result says `more`.
pub const MAX_WORDS: usize = 10_000;
@@ -36,10 +39,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Check Spelling",
[],
None,
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one",
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object), from?: {id, byte} (go on from there: the words of that type object that start at byte or later, then the objects after it; id must be one of the objects checked), max?: 1..10000 (default 10000)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than max words, the rest left out: check again with from {id, byte: end} of the last word)}. text.editRange {id, start, end, insert} changes one",
has_doc,
check
),
cmd!(
"text.spelling.change",
"Change All",
[],
None,
"{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); a word that already reads as to is left alone, and with no other word there is no edit and no undo step; an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count of words replaced}",
has_doc,
change_words
),
cmd!(
query "text.spelling.suggest",
"Spelling Suggestions",
@@ -107,22 +119,42 @@ pub fn specs() -> Vec<CommandSpec> {
}
/// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked
/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them.
/// one), in paint order, each paragraph checked on its own, at most `max` of them, starting at
/// `from` when it is given.
fn check(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.spelling.check";
// Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than
// a check of the whole document.
let ids = match p.get("ids").filter(|v| !v.is_null()) {
let mut ids = match p.get("ids").filter(|v| !v.is_null()) {
Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)),
None => all_texts(&s.doc()?.doc),
};
let max = whole_or(p, "max", MAX_WORDS as u64, C)?;
let max = usize::try_from(max).ok().filter(|m| (1..=MAX_WORDS).contains(m)).ok_or_else(|| bad(C, format!("`max` must be 1 to {MAX_WORDS}")))?;
let st = s.doc()?;
// Where the last check stopped: the objects before it are skipped, and the bytes of its object
// before `byte`.
let mut from_byte = 0;
if let Some(from) = p.get("from").filter(|v| !v.is_null()) {
let (id, byte) = from_param(from, C)?;
let Some(pos) = ids.iter().position(|i| i.0 == id) else {
return Err(bad(C, format!("`from.id` {id} is not one of the type objects checked")));
};
let Some(NodeKind::Text(t)) = st.doc.node(NodeId(id)).map(|n| &n.kind) else {
return Err(bad(C, format!("`from.id` {id} is not a type object")));
};
let len = t.plain_text().len();
from_byte = usize::try_from(byte).ok().filter(|b| *b <= len).ok_or_else(|| bad(C, format!("`from.byte` is past the end of {id}'s text")))?;
ids.drain(..pos);
}
let mut words = vec![];
let mut more = false;
for id in ids {
let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue };
let text = t.plain_text();
let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len());
// Only the first object listed starts part way.
let from = std::mem::take(&mut from_byte);
let (found, cut) = misspellings_from(t, &st.spelling_ignored, from, max - words.len());
for m in found {
let Some(word) = text.get(m.range.clone()) else { continue };
words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() }));
@@ -135,6 +167,87 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "words": words, "more": more }))
}
/// `text.spelling.check`'s `from`: `{id, byte}`, both whole numbers.
fn from_param(from: &Value, command: &str) -> Result<(u64, u64)> {
let Some(o) = from.as_object() else { return Err(bad(command, "`from` must be {id, byte}")) };
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "byte")) {
return Err(bad(command, format!("`from` takes id and byte, not `{k}`")));
}
let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.id` must be a type object's id"))?;
let byte = o.get("byte").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.byte` must be a whole number"))?;
Ok((id, byte))
}
/// `text.spelling.change`: Change All, every listed word replaced in one edit. Each object's words
/// are changed back to front, so the bytes of the ones before stay true, and the object is laid out
/// once at the end rather than once for each word.
fn change_words(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.spelling.change";
let to = str_param(p, "to").ok_or_else(|| bad(C, "missing `to`"))?.to_string();
let list = p.get("words").and_then(Value::as_array).ok_or_else(|| bad(C, "`words` must be a list of {id, start, end}"))?;
let mut by_id: BTreeMap<NodeId, Vec<(usize, usize)>> = BTreeMap::new();
for w in list {
let (id, start, end) = word_param_range(w, C)?;
by_id.entry(NodeId(id)).or_default().push((start, end));
}
// Every word checked against its object before anything changes.
let st = s.doc()?;
for (id, ranges) in &mut by_id {
let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else {
return Err(bad(C, format!("{} is not a type object", id.0)));
};
let text = t.plain_text();
ranges.sort_unstable();
let mut last_end = 0;
for &(a, b) in ranges.iter() {
if a >= b || text.get(a..b).is_none() {
return Err(bad(C, format!("{a}..{b} is not a word of {}'s text", id.0)));
}
if a < last_end {
return Err(bad(C, format!("words of {} overlap at byte {a}", id.0)));
}
last_end = b;
}
// A word that already reads as `to` is left alone, so a list of only those makes no edit.
ranges.retain(|&(a, b)| text.get(a..b) != Some(to.as_str()));
}
by_id.retain(|_, ranges| !ranges.is_empty());
let changed: usize = by_id.values().map(Vec::len).sum();
if changed == 0 {
return Ok(json!({ "changed": 0 }));
}
s.edit("Change All", |d, _| {
for (id, ranges) in &by_id {
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
for &(a, b) in ranges.iter().rev() {
// Paragraph styles and ruby follow each edit, as in `text.editRange`.
t.splice_paras(a, b, &to);
edit::replace_range(&mut t.runs, a, b, &to);
t.ruby_after_replace(a, b, to.len());
}
refresh_bounds(t);
}
Ok(())
})?;
Ok(json!({ "changed": changed }))
}
/// One of `text.spelling.change`'s `words`: `{id, start, end}`, all whole numbers.
fn word_param_range(w: &Value, command: &str) -> Result<(u64, usize, usize)> {
let Some(o) = w.as_object() else { return Err(bad(command, "each of `words` must be {id, start, end}")) };
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "start" | "end")) {
return Err(bad(command, format!("each of `words` takes id, start and end, not `{k}`")));
}
let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "a word's `id` must be a type object's id"))?;
let byte = |k: &str| {
o.get(k)
.and_then(Value::as_u64)
.and_then(|b| usize::try_from(b).ok())
.ok_or_else(|| bad(command, format!("a word's `{k}` must be a whole number")))
};
Ok((id, byte("start")?, byte("end")?))
}
/// One word of a type object its dictionaries don't know ([`misspellings`]).
#[derive(Clone, Debug, PartialEq)]
pub struct Misspelling {
@@ -149,6 +262,13 @@ pub struct Misspelling {
/// All words). At most `max` of them; the flag says the list was cut short there. What
/// `text.spelling.check` lists for one object, and what Auto Spell Check underlines.
pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (Vec<Misspelling>, bool) {
misspellings_from(t, ignored, 0, max)
}
/// [`misspellings`] of the words that start at byte `from` or later. The paragraphs that end at
/// or before `from` are not checked; the paragraph that holds `from` is checked whole, since
/// craft-proof reads a paragraph's language from all of it.
pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize, max: usize) -> (Vec<Misspelling>, bool) {
let text = t.plain_text();
// Each run in its own language, at its bytes of the plain text.
let mut spans: Vec<(Range<usize>, ProofLang)> = Vec::with_capacity(t.runs.len());
@@ -166,6 +286,11 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (
let mut para_start = 0;
for para in text.split('\n') {
let para_end = para_start + para.len();
// No word of a paragraph that ends at `from` starts there or later.
if para_end <= from {
para_start = para_end + 1;
continue;
}
let para_spans: Vec<(Range<usize>, ProofLang)> = spans
.iter()
.filter_map(|(r, lang)| {
@@ -178,6 +303,9 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (
continue;
}
let (start, end) = (para_start + issue.start, para_start + issue.end);
if start < from {
continue;
}
let Some(word) = text.get(start..end) else { continue };
if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) {
continue;
+2 -1
View File
@@ -495,7 +495,8 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) {
None => return Ok(()),
Some(b) => match art_of(before) {
Some(old) if same(&old) => return Ok(()),
// Turning on Align to Pixel Grid writes the art back too, so the layer shows it snapped.
Some(old) if same(&old) && (before.symbol_pixel_aligned(&se.symbol) || !d.symbol_pixel_aligned(&se.symbol)) => return Ok(()),
old => (old.unwrap_or_default(), b.group),
},
};
+309 -3
View File
@@ -455,10 +455,11 @@ fn a_symbol_instance_fill_shadow_shadows_its_filled_art() {
assert!(expandable(&s), "the fill's shadow can be expanded");
run(&mut s, "effect.expandAppearance", json!({}));
let ch = node(&s, id).children().cloned().expect("the instance becomes a group");
let n = node(&s, id);
let ch = n.children().cloned().expect("the instance becomes a group");
assert!(matches!(ch[0].kind, NodeKind::Image(_)), "the shadow is an image under the art: {}", ch[0].kind_label());
assert!(matches!(ch[1].kind, NodeKind::SymbolInstance { .. }), "the art stays an instance: {}", ch[1].kind_label());
no_effects_left(&ch[1]);
n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the art is no longer an instance"));
no_effects_left(&n);
let after = render(&s);
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
run(&mut s, "edit.undo", json!({}));
@@ -508,6 +509,311 @@ fn a_nested_symbol_instance_takes_the_outer_fill_shadow() {
assert!(dark(render(&s).pixel(165, 100)), "the inner art casts the shadow: {:?}", render(&s).pixel(165, 100));
}
/// An instance of an Inner symbol of the square, with a new fill without paint on top that `inner`
/// gives effects, placed in the art of an Outer symbol; the Outer instance is selected, with a new
/// fill without paint on top. Returns the Outer instance and its new row's index.
fn nested_with_row(s: &mut Session, inner: impl FnOnce(&mut Session, NodeId, usize)) -> (NodeId, usize) {
let (inner_id, inner_row) = instance_with_row(s, "Inner", true);
inner(s, inner_id, inner_row);
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
run(s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(s, id).appearance.items.len() - 1;
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
(id, row)
}
/// The symbol instances and the images in `n`.
fn instances_and_images(n: &Node) -> (usize, usize) {
let mut found = (0, 0);
n.walk(&mut |part| match part.kind {
NodeKind::SymbolInstance { .. } => found.0 += 1,
NodeKind::Image(_) => found.1 += 1,
_ => {}
});
found
}
/// Replace the art of every symbol with an empty group.
fn empty_symbols(s: &mut Session) {
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
for (i, sym) in d.symbols.iter_mut().enumerate() {
sym.art = std::sync::Arc::new(Node::group(NodeId(91_000 + i as u64), vec![]));
}
}
/// When the outer instance's art expands, an instance in it whose own fill has a shadow becomes art
/// too, the shadow an image under it: no instance or effect is left, the look stays, and the result
/// no longer follows either symbol.
#[test]
fn a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands() {
let mut s = session();
let (id, row) = nested_with_row(&mut s, shadow_row);
offset_row(&mut s, id, row, 10.0);
let before = render(&s);
assert!(dark(before.pixel(175, 100)), "the inner art casts its shadow: {:?}", before.pixel(175, 100));
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
let (instances, images) = instances_and_images(&n);
assert_eq!(instances, 0, "the outer and inner instances become art");
assert!(images >= 1, "the inner shadow is an image");
no_effects_left(&n);
let after = render(&s);
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
empty_symbols(&mut s);
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
}
/// A shadow on the outer instance's fill alone: the instance becomes its art over the shadow's
/// image, and an instance in that art with a shadow of its own becomes art and an image in turn, in
/// one undo step.
#[test]
fn an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art() {
let mut s = session();
let (id, row) = nested_with_row(&mut s, shadow_row);
shadow_row(&mut s, id, row);
let before = render(&s);
assert!(expandable(&s));
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
let (instances, images) = instances_and_images(&n);
assert_eq!(instances, 0, "the outer and inner instances become art");
assert!(images >= 2, "the outer and inner shadows are images: {images}");
no_effects_left(&n);
let after = render(&s);
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
run(&mut s, "edit.undo", json!({}));
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back");
run(&mut s, "edit.redo", json!({}));
empty_symbols(&mut s);
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
}
/// A blur on the nested instance's fill: the nested instance becomes the image.
#[test]
fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() {
let mut s = session();
let blur = |s: &mut Session, id: NodeId, row: usize| {
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
};
let (id, row) = nested_with_row(&mut s, blur);
offset_row(&mut s, id, row, 10.0);
let before = render(&s);
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
let (instances, images) = instances_and_images(&n);
assert_eq!(instances, 0, "the outer and inner instances become art");
assert_eq!(images, 1, "the blurred inner art is one image");
no_effects_left(&n);
let after = render(&s);
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
}
/// A blue rectangle from x 140 to 200, drawn first, so a shadow right of the square falls on it.
fn blue_backdrop(s: &mut Session) {
run(s, "shape.rectangle", json!({"x": 140, "y": 0, "width": 60, "height": 200}));
run(s, "paint.setFill", json!({"color": "#0000ff"}));
}
/// A red Drop Shadow 20 pt to the right on row `row` of instance `id`, with no blur, painting with `mode`.
fn red_shadow_row(s: &mut Session, id: NodeId, row: usize, mode: &str) {
let params = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": mode, "color": "#ff0000"});
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "stylize.dropShadow", "params": params}));
}
/// The blend modes of the images in `n`, in the order the walk visits them.
fn image_modes(n: &Node) -> Vec<BlendMode> {
let mut modes = vec![];
n.walk(&mut |part| {
if matches!(part.kind, NodeKind::Image(_)) {
modes.push(part.blend);
}
});
modes
}
/// A Multiply shadow on the nested instance's fill: its image multiplies with the blue art below
/// as the shadow did, rather than painting red over it.
#[test]
fn a_nested_instance_multiply_shadow_image_keeps_its_mode() {
let mut s = session();
blue_backdrop(&mut s);
let (id, row) = nested_with_row(&mut s, |s, id, row| red_shadow_row(s, id, row, "multiply"));
offset_row(&mut s, id, row, 10.0);
let before = render(&s);
assert!(dark(before.pixel(170, 100)), "red multiplied with blue is dark: {:?}", before.pixel(170, 100));
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
assert_eq!(instances_and_images(&n).0, 0, "the outer and inner instances become art");
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
no_effects_left(&n);
let after = render(&s);
assert!(dark(after.pixel(170, 100)), "the image multiplies with the blue art: {:?}", after.pixel(170, 100));
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
}
/// A Multiply shadow on an instance's own fill: the image under its art paints with Multiply.
#[test]
fn an_instance_multiply_shadow_image_keeps_its_mode() {
let mut s = session();
blue_backdrop(&mut s);
let (id, row) = instance_with_row(&mut s, "Square", true);
red_shadow_row(&mut s, id, row, "multiply");
let before = render(&s);
assert!(dark(before.pixel(160, 100)), "red multiplied with blue is dark: {:?}", before.pixel(160, 100));
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
let after = render(&s);
assert!(dark(after.pixel(160, 100)), "the image multiplies with the blue art: {:?}", after.pixel(160, 100));
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
}
/// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it.
#[test]
fn a_hidden_nested_instance_fill_shadow_makes_no_image() {
let mut s = session();
let hidden = |s: &mut Session, id: NodeId, row: usize| {
shadow_row(s, id, row);
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "visible": false}));
};
let (id, row) = nested_with_row(&mut s, hidden);
offset_row(&mut s, id, row, 10.0);
assert!(!dark(render(&s).pixel(175, 100)), "the hidden fill casts no shadow");
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
assert_eq!(instances_and_images(&n), (0, 0), "the instances become art without an image");
no_effects_left(&n);
}
/// A nested instance with a shadow whose symbol is missing stays as it is while the outer art
/// expands around it.
#[test]
fn a_nested_instance_of_a_missing_symbol_stays_an_instance() {
let mut s = session();
let (id, row) = nested_with_row(&mut s, shadow_row);
offset_row(&mut s, id, row, 10.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.symbols.retain(|sym| sym.name != "Inner");
}
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, id);
assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image");
}
/// 1,100 blurred instances in the outer art, far fewer objects than the symbol limit: one Expand
/// Appearance makes 1,024 images of them, and the other 76 stay instances with their blur, which
/// the result reports.
#[test]
fn nested_instance_raster_effects_stop_at_the_image_limit() {
let mut s = session();
// Images of a pixel or two each.
run(&mut s, "document.rasterEffectsSettings", json!({"resolution": 1}));
let blur = |s: &mut Session, id: NodeId, row: usize| {
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
};
let (id, row) = nested_with_row(&mut s, blur);
offset_row(&mut s, id, row, 10.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let outer = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap();
let inner = (*d.symbols[outer].art).clone();
assert!(matches!(inner.kind, NodeKind::SymbolInstance { .. }), "the outer art is the inner instance");
let copies = (0..1_100)
.map(|_| {
let mut copy = inner.clone();
copy.id = d.alloc_id();
std::sync::Arc::new(copy)
})
.collect();
d.symbols[outer].art = std::sync::Arc::new(Node::group(d.alloc_id(), copies));
}
let r = run(&mut s, "effect.expandAppearance", json!({}));
assert_eq!(r["rasterLeft"], 76, "{r}");
assert!(r["warning"].as_str().is_some_and(|w| w.contains("1,024 images")), "{r}");
let n = node(&s, id);
assert_eq!(instances_and_images(&n), (76, 1_024), "1,024 instances become images and the rest stay");
n.walk(&mut |part| {
if matches!(part.kind, NodeKind::SymbolInstance { .. }) {
assert!(part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "blur.gaussian")), "a left instance keeps its blur");
}
});
}
/// Gives `id` a color adjustment and a blur, puts it in a group above 1,024 blurred squares, which
/// take every image one Expand Appearance makes, and expands the group. Returns `id` as it was
/// before expanding.
fn adjusted_and_left_by_the_image_limit(s: &mut Session, id: NodeId) -> Node {
// Images of a pixel or two each.
run(s, "document.rasterEffectsSettings", json!({"resolution": 1}));
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}}));
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
let sq = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(s, "effect.apply", json!({"ids": [sq.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
let before = node(s, id);
let group = {
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let blurred = d.node(sq).unwrap().clone();
d.remove(sq).unwrap();
let mut members: Vec<_> = (0..1_024)
.map(|_| {
let mut copy = blurred.clone();
copy.id = d.alloc_id();
std::sync::Arc::new(copy)
})
.collect();
members.push(std::sync::Arc::new(before.clone()));
let group = d.alloc_id();
*d.node_mut(id).unwrap() = Node::group(group, members);
group
};
let r = run(s, "effect.expandAppearance", json!({"ids": [group.0]}));
assert_eq!(r["rasterLeft"], 1, "{r}");
before
}
/// A symbol instance with a color adjustment and a blur, left by the image limit, stays an instance
/// of its symbol, with both effects.
#[test]
fn a_color_adjusted_instance_left_by_the_image_limit_stays_an_instance() {
let mut s = session();
run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Adjusted Square"}))["id"].as_u64().unwrap());
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
assert!(matches!(before.kind, NodeKind::SymbolInstance { .. }));
assert_eq!(node(&s, id), before, "the instance stays as it is, with its adjustment and blur");
}
/// An embedded image with a color adjustment and a blur, left by the image limit, stays as it is,
/// and the document keeps no recolored copy of its pixels.
#[test]
fn a_color_adjusted_image_left_by_the_image_limit_adds_no_pixels() {
let mut s = session();
let mut png = vec![];
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
let id = NodeId(r["ids"][0].as_u64().unwrap());
let images: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect();
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
assert!(matches!(before.kind, NodeKind::Image(_)));
assert_eq!(node(&s, id), before, "the image stays as it is, with its adjustment and blur");
// Besides the squares' images, the document holds the image's pixels alone.
let after: Vec<String> = s.doc().unwrap().doc.images.keys().filter(|k| !k.starts_with("raster-effect-")).cloned().collect();
assert_eq!(after, images, "no recolored copy stays in the document");
}
/// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the
/// shadow on the art's fill, not its stroke, and PDF export makes an image of it.
#[test]
+53
View File
@@ -34,6 +34,59 @@ fn the_font_list_names_every_available_family_with_its_styles() {
assert!(s.execute("text.fontList", &json!({"family": "No Such Font"})).is_err());
}
/// Show Similar Fonts (`text.similarFonts`): every listed family, the asked one first, in the
/// order the font menus show; bad params are refused.
#[test]
fn similar_fonts_lists_every_family_by_likeness() {
let mut s = Session::new();
let db = FontDb::global();
let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap();
assert_eq!(r["family"], "Source Sans 3");
let order = names(&r["families"]);
assert_eq!(order.first().map(String::as_str), Some("Source Sans 3"));
let mut sorted = order.clone();
sorted.sort();
let mut listed = db.menu_family_list().to_vec();
listed.sort();
// Other tests running at the same time add and remove composite fonts; the installed families are compared.
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once");
// The two answers are compared whole when the available fonts did not change while both were
// made (the same `FontDb::generation`), and by their installed families when they changed
// during every try.
let mut answers = (vec![], vec![], false);
for _ in 0..20 {
let generation = db.generation();
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
let unchanged = db.generation() == generation;
answers = (all, two, unchanged);
if unchanged {
break;
}
}
let (all, two, unchanged) = answers;
assert_eq!(two.len(), 2);
if unchanged {
assert_eq!(two, all[..2], "the first families, in order");
} else {
let (two, all) = (installed_only(&two), installed_only(&all));
assert_eq!(two[..], all[..two.len()], "the first installed families, in order");
}
for (params, error) in [
(json!({}), "`family` is required"),
(json!({"family": " "}), "`family` is required"),
(json!({"family": 3}), "`family` must be a string"),
(json!({"family": "No Such Font"}), "font family `No Such Font` is not available"),
(json!({"family": "Inter", "limit": 0}), "`limit` must be a whole number from 1 to 100000"),
(json!({"family": "Inter", "limit": 2.5}), "`limit` must be a whole number from 1 to 100000"),
(json!({"family": "Inter", "limit": "2"}), "`limit` must be a whole number from 1 to 100000"),
] {
let e = s.execute("text.similarFonts", &params).unwrap_err().to_string();
assert!(e.contains(error), "{params}: {e}");
}
}
#[test]
fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
let mut s = Session::new();
+58
View File
@@ -2168,6 +2168,64 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read()
}
}
/// A confined caller's SVG and SVGZ with Preserve Editing Capabilities carry a native document
/// without the Export for Screens folder when it is outside the read roots, with the other export
/// settings and the art; the open document keeps the folder. A folder inside the roots, and any
/// folder without roots, stays in the attachment.
#[test]
fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-export-folder-away");
let home = Folder::new("svg-export-folder-home");
let outside = away.0.to_string_lossy().into_owned();
let inside = home.file("screens");
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
let set_folder = |s: &mut Session, folder: &str| {
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap();
};
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
// The native document an SVG's text carries.
let attached = |text: &str| {
let data = vectorcraft_svg::editing_data(text).expect("editing data");
vectorcraft_format::load(&vectorcraft_format::base64_decode(&data).unwrap()).unwrap()
};
let check = |d: &Document, folder: Option<&str>, what: &str| {
assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}");
assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}");
assert!(d.node(rect).is_some(), "{what}: no art");
};
// Every way an SVG is asked for with Preserve Editing, its text and its native document.
let every = |s: &mut Session, confined: bool, folder: Option<&str>| {
let run = |s: &mut Session, cmd: &str, p: Value| {
let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) };
r.unwrap()
};
for format in ["svg", "svgz"] {
let r = run(s, "document.serialize", json!({"format": format, "preserveEditing": true}));
check(&attached(&svg_text(&r)), folder, &format!("{format} serialize"));
let r = run(s, "document.serialize", json!({"format": format, "svg": {"preserveEditing": true}}));
check(&attached(&svg_text(&r)), folder, &format!("{format} options object"));
let path = home.file(&format!("export.{format}"));
run(s, "document.export", json!({"format": format, "path": path, "preserveEditing": true}));
let bytes = std::fs::read(&path).unwrap();
check(&attached(&vectorcraft_svg::text_of(&bytes).unwrap()), folder, &format!("{format} export"));
}
};
set_folder(&mut s, &outside);
every(&mut s, true, None);
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str()));
every(&mut s, false, Some(&outside));
// Without Preserve Editing the SVG carries no native document.
let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
assert!(vectorcraft_svg::editing_data(&svg_text(&r)).is_none(), "{r}");
set_folder(&mut s, &inside);
every(&mut s, true, Some(&inside));
}
/// A confined caller's SVG of a placed document whose art links an image: the file draws that art
/// and names the image's file, so a file outside the read roots refuses it and one inside them is
/// written. Any output that names no file is written.
+245
View File
@@ -1588,6 +1588,235 @@ fn crop_image_to_a_rect_between_pixels_keeps_the_rect() {
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
}
/// Crop Image's `ppi` resamples the cut pixels to that resolution; the image keeps the box's size.
#[test]
fn crop_image_resamples_the_cut_to_the_resolution_asked_for() {
let (mut s, img, px) = busy_image_at_two_points_a_pixel();
// The image is 36 ppi (2 pt a pixel); 18 ppi halves the cut's 30 × 20 pixels.
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
let b = bounds(&s, img);
assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image();
// Resampled in 16 bits a channel: within a level of the 8-bit resampling.
let want = image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3);
assert_eq!(out.dimensions(), want.dimensions());
assert!(out.as_raw().iter().zip(want.as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1));
}
/// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not
/// tint the partly transparent edge of what is opaque.
#[test]
fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() {
// Opaque white on the left half, fully transparent red on the right.
let px = image::RgbaImage::from_fn(40, 20, |x, _| if x < 20 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([255, 0, 0, 0]) });
let mut png = Vec::new();
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let img = selected(&s)[0];
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
// 36 ppi to 15 ppi over pixels 5 to 35 across: the edge pixels mix white and clear.
s.execute("object.cropImage", &json!({"rect": [10, 0, 60, 40], "ppi": 15})).unwrap();
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
assert!(out.pixels().any(|p| p[3] > 0 && p[3] < 255), "the edge is partly transparent");
for p in out.pixels().filter(|p| p[3] > 0) {
assert!(p[1] >= 250 && p[2] >= 250, "white, not tinted red: {p:?}");
}
}
/// Resampling keeps the color of pixels that are nearly transparent: a uniform color at the lowest
/// alpha comes out as that color, not black.
#[test]
fn crop_image_resampling_keeps_the_color_of_nearly_transparent_pixels() {
let px = image::RgbaImage::from_pixel(100, 80, image::Rgba([100, 50, 25, 1]));
let mut png = Vec::new();
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "faint.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let img = selected(&s)[0];
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
for p in out.pixels() {
let near = |a: u8, b: u8| a.abs_diff(b) <= 1;
assert!(p[3] == 1 && near(p[0], 100) && near(p[1], 50) && near(p[2], 25), "{p:?}");
}
}
/// A box between pixels drawn at a resolution asked for holds what is inside the box only, at its
/// place: the edge of the image's content lands where it was in the box.
#[test]
fn crop_image_between_pixels_keeps_the_content_at_its_place() {
// White pixels 0 to 49 across, black from 50: at 2 pt a pixel, the edge is at x = 100 pt.
let px = image::RgbaImage::from_fn(100, 80, |x, _| if x < 50 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([0, 0, 0, 255]) });
let mut png = Vec::new();
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let img = selected(&s)[0];
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
// 101 × 31 pt from (21, 11), off the pixel grid, at 35 ppi: 49 × 15 px. The edge is 79 pt into
// the 101 pt box, so each row holds 49 × 79 / 101 pixels' worth of white.
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 101, 31], "ppi": 35})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (49, 15), "{r}");
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
let white: f64 = out.pixels().map(|p| f64::from(p[1]) / 255.0).sum::<f64>() / f64::from(out.height());
let want = 49.0 * 79.0 / 101.0;
assert!((white - want).abs() < 0.1, "{white} pixels of white a row, want {want}");
let b = bounds(&s, img);
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 101.0) && close(b.height(), 31.0), "{b:?}");
}
/// A box between pixels is drawn at the resolution asked for, and lands on the box.
#[test]
fn crop_image_between_pixels_draws_at_the_resolution_asked_for() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40], "ppi": 18})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
let b = bounds(&s, img);
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
// 100 × 30 pt at 20 ppi is 27.8 × 8.3 px: the 28 × 8 px drawn are fitted to the box.
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 100, 30], "ppi": 20})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (28, 8), "{r}");
let b = bounds(&s, img);
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 100.0) && close(b.height(), 30.0), "{b:?}");
}
/// A box over the whole image with a new resolution resamples it; with the image's own there is
/// nothing to do.
#[test]
fn crop_image_over_the_whole_image_only_resamples_it() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
let before = undo_len(&s);
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 36}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
assert_eq!(undo_len(&s), before);
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 9})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (25, 20), "{r}");
assert_eq!(undo_len(&s), before + 1, "one undo step");
let b = bounds(&s, img);
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 160.0), "{b:?}");
}
/// An image scaled more down than across is resampled on both sides at the resolution of its denser
/// side, so its pixels come out square.
#[test]
fn crop_image_resamples_pixels_that_are_not_square() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
// 2 pt a pixel across (36 ppi) and 1 pt a pixel down (72 ppi), 200 × 80 pt.
s.execute("object.scale", &json!({"sx": 100, "sy": 50, "origin": [0, 0]})).unwrap();
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 80], "ppi": 72})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (200, 80), "{r}");
let b = bounds(&s, img);
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 80.0), "{b:?}");
}
/// Crop Image refuses a resolution that isn't a positive number, one above the image's own, and one
/// with trim; the image stays as it was.
#[test]
fn crop_image_refuses_a_resolution_it_cannot_give() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
let before = (undo_len(&s), node(&s, img));
let refused = |s: &mut Session, p: Value, want: &str| {
let r = s.execute("object.cropImage", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
};
for v in [json!(0), json!(-72), json!("high"), json!(true)] {
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), &format!("ppi must be a positive number, not {v}"));
}
for v in [0.5, 1e-310, 2401.0] {
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), "ppi must be between 1 and 2400");
}
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": 72}), "ppi can't be more than 36 for this image");
refused(&mut s, json!({"trim": true, "ppi": 18}), "trim keeps the image's pixels as they are: leave out ppi");
assert_eq!((undo_len(&s), node(&s, img)), before);
// A null ppi keeps the image's own, as a missing one does.
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": null})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}");
}
/// A turned image keeps its own resolution as the limit (not the density across its bounding box),
/// and its drawn cut is resampled to the box's size at the resolution asked for.
#[test]
fn crop_image_of_a_turned_image_resamples_its_drawing() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let b = bounds(&s, img);
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 37}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 36 for this image"), "{r:?}");
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 18})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (18, 9), "{r}");
let c = bounds(&s, img);
assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}");
}
/// A turned image cropped at its own resolution, asked for, gets that resolution, not the lower
/// density of the box around it.
#[test]
fn crop_image_of_a_turned_image_at_its_own_resolution_keeps_it() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
let b = bounds(&s, img);
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 36})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (36, 18), "{r}");
// Over the whole box around it, its own resolution draws it square to the page.
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
let b = bounds(&s, img);
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()], "ppi": 36})).unwrap();
assert_eq!(r["width"].as_u64().unwrap(), (b.width() / 2.0).round() as u64, "{r}");
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()]}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
}
/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it.
#[test]
fn crop_image_takes_a_linked_image_up_to_300_ppi() {
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
s.edit("Link", |d, _| {
let NodeKind::Image(im) = &mut d.node_mut(img).unwrap().kind else { panic!("not an image") };
im.link = Some(vectorcraft_doc::LinkInfo::new("art.png"));
Ok(())
})
.unwrap();
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 301}));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 300 for this image"), "{r:?}");
// 72 ppi: a pixel a point.
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 72})).unwrap();
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (60, 40), "{r}");
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
assert!(im.link.is_none());
}
/// `tool.setOption` refuses a Crop Image resolution, reference point or link it can't use, and
/// changes nothing.
#[test]
fn crop_image_tool_options_refuse_values_they_cannot_use() {
let (mut s, _, _) = busy_image_at_two_points_a_pixel();
s.select_tool("cropImage", ViewInfo::default()).unwrap();
s.set_tool_option_cmd(&json!({"values": {"ppi": 18, "reference": 0, "linked": true}})).unwrap();
// 72 ppi is above the selected 36 ppi image's own.
for (key, value) in
[("ppi", json!("high")), ("ppi", json!(-1)), ("ppi", json!(0.5)), ("ppi", json!(72)), ("reference", json!(9)), ("linked", json!(1))]
{
assert!(s.set_tool_option_cmd(&json!({"key": key, "value": value})).is_err(), "{key}: {value}");
}
let o = s.tool_options();
assert_eq!((o["ppi"].clone(), o["reference"].clone(), o["linked"].clone()), (json!(18.0), json!(0), json!(true)), "{o}");
s.set_tool_option_cmd(&json!({"key": "ppi", "value": null})).unwrap();
assert!(s.tool_options().get("ppi").is_none());
}
/// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a
/// null `rect` crops to the artboard as a missing one does.
#[test]
@@ -5331,6 +5560,22 @@ fn crop_image_trim_checks_the_rgba_size_before_decoding() {
assert!(within.contains("the image's pixels can't be read"), "{within}");
}
#[test]
fn crop_image_resampling_is_held_to_the_raster_allowance() {
use crate::cmd::menucmds::check_resample_size;
let max = crate::cmd::fileio::MAX_RASTER_ALLOC;
// 40 bytes a pixel resampled to the same size (12 + 16 + 12).
let side = ((max / 40) as f64).sqrt() as u32;
assert!(check_resample_size(side, side, side, side).is_ok());
let e = check_resample_size(side + 1, side + 1, side + 1, side + 1).unwrap_err().to_string();
assert!(e.contains(&format!("an image of {0} × {0} pixels is too large to resample", side + 1)), "{e}");
// A large source counts even when the result is small.
let wide = ((max / 12) as f64).sqrt() as u32 + 1;
assert!(check_resample_size(wide, wide, 1, 1).is_err());
assert!(check_resample_size(u32::MAX, u32::MAX, u32::MAX, u32::MAX).is_err());
assert!(check_resample_size(100, 100, 50, 50).is_ok());
}
#[test]
fn crop_image_trim_leaves_a_cmyk_image_alone() {
// CMYK images keep their ink amounts and have no alpha: nothing to cut, and not an error.
+80
View File
@@ -1436,6 +1436,40 @@ fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() {
assert!(whole(&[(e, f)]), "{e} {f}");
}
/// An instance snapped to whole points takes the art of its linked opacity mask along by the same
/// amount, as a move does; the art of an unlinked mask stays where it is.
#[test]
fn an_instance_snapped_to_the_grid_moves_its_linked_mask() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
s.execute("symbol.new", &json!({"name": "Px"})).unwrap();
let place = |s: &mut Session, x: f64, linked: bool| {
let inst = s.execute("symbol.place", &json!({"name": "Px", "x": x, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
let m = path(s, "M80.25 180.5 L160.25 180.5 L160.25 240.5 L80.25 240.5 Z", 1.0);
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = d.remove(NodeId(m)).unwrap();
let mask = vectorcraft_doc::OpacityMask { linked, ..vectorcraft_doc::OpacityMask::new((*art).clone(), true) };
d.node_mut(NodeId(inst)).unwrap().extras_mut().mask = Some(Box::new(mask));
inst
};
let (linked, unlinked) = (place(&mut s, 100.3, true), place(&mut s, 300.3, false));
let mask_points = |s: &Session, inst: u64| {
let d = &s.doc().unwrap().doc;
let mask = d.node(NodeId(inst)).unwrap().extras().mask.clone().unwrap();
mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::<Vec<_>>()
};
let (xf_before, mask_before, unlinked_before) = (instance_xf(&s, linked), mask_points(&s, linked), mask_points(&s, unlinked));
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
let [.., e0, f0] = xf_before.as_coeffs();
let [.., e, f] = instance_xf(&s, linked).as_coeffs();
assert!(whole(&[(e, f)]) && (e, f) != (e0, f0), "{e} {f}");
let moved: Vec<_> = mask_before.iter().map(|(x, y)| (x + e - e0, y + f - f0)).collect();
let after = mask_points(&s, linked);
assert!(moved.iter().zip(&after).all(|(a, b)| close(*a, *b)), "{after:?} != {moved:?}");
assert!(whole(&placed_points(&s, unlinked)));
assert_eq!(mask_points(&s, unlinked), unlinked_before);
}
/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored
/// on the pixel grid, so its instances stay on it.
#[test]
@@ -1459,3 +1493,49 @@ fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() {
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
}
/// Turning it on while the symbol is open in symbol editing mode shows its art on the pixel grid
/// on the editing layer at once, and its instance stays on it after editing ends.
#[test]
fn turning_it_on_in_symbol_editing_mode_snaps_the_editing_layer() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap();
let st = s.doc().unwrap();
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
let before = points(&s, part);
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
let d = &s.doc().unwrap().doc;
let xf = d.symbol_edit.as_ref().unwrap().xf;
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
let stored: Vec<_> = art.path_data().unwrap().anchors().map(|(_, _, a)| xf * a.p).map(|p| (p.x, p.y)).collect();
let shown = points(&s, part);
assert!(shown.iter().zip(&stored).all(|(a, b)| close(*a, *b)) && shown != before, "{shown:?} != {stored:?}");
s.execute("symbol.exitEditing", &json!({})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
}
/// An instance of a pixel-aligned symbol on the editing layer of another symbol is part of that
/// symbol's art, so turning it on leaves the instance and the other symbol's art where they are.
#[test]
fn an_instance_on_another_symbols_editing_layer_is_left_as_it_is() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a]})).unwrap();
let b = s.execute("symbol.new", &json!({"name": "Outer"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.edit", &json!({"ids": [b]})).unwrap();
let st = s.doc().unwrap();
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
let inner = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
let outer_art = st.doc.symbols.iter().find(|x| x.name == "Outer").unwrap().art.clone();
let shown = instance_xf(&s, inner);
assert!(!whole(&placed_points(&s, inner)));
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
assert_eq!(instance_xf(&s, inner), shown);
let d = &s.doc().unwrap().doc;
assert!(std::sync::Arc::ptr_eq(&d.symbols.iter().find(|x| x.name == "Outer").unwrap().art, &outer_art));
}
+128
View File
@@ -345,6 +345,134 @@ fn misspellings_of_one_object_are_what_the_check_lists() {
assert_eq!(found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), [listed[0].clone(), listed[2].clone()]);
}
/// The (id, start, word) of each word a check lists, and its `more`.
fn listed(s: &mut Session, p: Value) -> (Vec<(u64, u64, String)>, bool) {
let r = run(s, "text.spelling.check", p);
let words = r["words"]
.as_array()
.unwrap()
.iter()
.map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string()))
.collect();
(words, r["more"].as_bool().unwrap())
}
/// A check cut short at `max` goes on with `from` at the end of the last word listed: the rest of
/// that type object first, then the objects after it, and nothing listed twice.
#[test]
fn a_check_goes_on_from_where_the_last_one_stopped() {
let mut s = session();
let a = text(&mut s, 50.0, "qzxvw one wvxzq two\nthree qqzzx");
let b = text(&mut s, 100.0, "zzqqx");
let (first, more) = listed(&mut s, json!({"max": 2}));
assert_eq!((first.clone(), more), (vec![(a.0, 0, "qzxvw".into()), (a.0, 10, "wvxzq".into())], true));
// From the end of the second word: the third, in the next paragraph of the same object, not
// the start of the next object.
let (rest, more) = listed(&mut s, json!({"from": {"id": a.0, "byte": 15}, "max": 2}));
assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into()), (b.0, 0, "zzqqx".into())], false));
// A byte inside a word starts from the next word.
let (rest, _) = listed(&mut s, json!({"from": {"id": a.0, "byte": 1}}));
assert_eq!(rest.first(), Some(&(a.0, 10, "wvxzq".to_string())));
// `from` follows the ids given, groups' type included.
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 26}, "max": 1}));
assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into())], true));
let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 31}, "max": 1}));
assert_eq!((rest, more), (vec![(b.0, 0, "zzqqx".into())], false));
let bad = [
json!({"from": {"id": a.0}}),
json!({"from": {"id": a.0, "byte": -1}}),
json!({"from": {"id": a.0, "byte": 1000}}),
json!({"from": {"id": a.0, "byte": 0, "x": 1}}),
json!({"from": a.0}),
json!({"ids": [b.0], "from": {"id": a.0, "byte": 0}}),
json!({"max": 0}),
json!({"max": 10_001}),
json!({"max": "2"}),
];
for p in bad {
assert!(s.execute("text.spelling.check", &p).is_err(), "{p} is refused");
}
}
/// One type object with one unknown word more than a check lists: going on from the last word
/// listed reaches the last one.
#[test]
fn a_check_past_the_limit_in_one_object_goes_on_to_its_last_word() {
use crate::cmd::spelling::MAX_WORDS;
let mut s = session();
let t = text(&mut s, 50.0, &vec!["qzxvw"; MAX_WORDS + 1].join(" "));
let r = run(&mut s, "text.spelling.check", json!({}));
let words = r["words"].as_array().unwrap();
assert_eq!((words.len(), &r["more"]), (MAX_WORDS, &json!(true)));
let end = words.last().unwrap()["end"].as_u64().unwrap();
let (rest, more) = listed(&mut s, json!({"from": {"id": t.0, "byte": end}}));
assert_eq!((rest, more), (vec![(t.0, end + 1, "qzxvw".into())], false));
}
/// The plain text of type object `id`.
fn plain(s: &Session, id: NodeId) -> String {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
_ => panic!("not type"),
}
}
/// Change All's command replaces every word listed, in several objects, as one undo step, and
/// refuses a list with any word not in its object's text, changing nothing.
#[test]
fn change_all_replaces_every_word_listed_in_one_undo_step() {
let mut s = session();
let a = text(&mut s, 50.0, "qzxvw one qzxvw\nqzxvw");
let b = text(&mut s, 100.0, "é qzxvw");
let depth = s.doc().unwrap().history.undo.len();
let words = json!([{"id": a.0, "start": 16, "end": 21}, {"id": a.0, "start": 0, "end": 5}, {"id": b.0, "start": 3, "end": 8}, {"id": a.0, "start": 10, "end": 15}]);
let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}));
assert_eq!(r["changed"], 4);
assert_eq!((plain(&s, a), plain(&s, b)), ("fixed one fixed\nfixed".to_string(), "é fixed".to_string()));
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!((plain(&s, a), plain(&s, b)), ("qzxvw one qzxvw\nqzxvw".to_string(), "é qzxvw".to_string()));
let bad = [
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 3, "end": 8}]}),
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 20, "end": 99}]}),
json!({"to": "x", "words": [{"id": b.0, "start": 1, "end": 4}]}),
json!({"to": "x", "words": [{"id": a.0, "start": 5, "end": 5}]}),
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5, "x": 1}]}),
json!({"to": "x", "words": [{"id": a.0, "start": -1, "end": 5}]}),
json!({"to": "x", "words": [{"id": 999_999, "start": 0, "end": 5}]}),
json!({"to": "x", "words": {"id": a.0}}),
json!({"words": []}),
];
for p in bad {
assert!(s.execute("text.spelling.change", &p).is_err(), "{p} is refused");
}
assert_eq!(plain(&s, a), "qzxvw one qzxvw\nqzxvw", "nothing changed by a refused list");
assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "x", "words": []}))["changed"], 0);
}
/// A listed word that already reads as `to` is left alone: with no other word, no edit and no
/// undo step, so the redo history stays.
#[test]
fn change_all_skips_words_that_already_read_as_the_replacement() {
let mut s = session();
let a = text(&mut s, 50.0, "fixed qzxvw");
run(&mut s, "text.editRange", json!({"id": a.0, "start": 6, "end": 11, "insert": "other"}));
run(&mut s, "edit.undo", json!({}));
let (undo, redo) = {
let h = &s.doc().unwrap().history;
(h.undo.len(), h.redo.len())
};
let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": [{"id": a.0, "start": 0, "end": 5}]}));
assert_eq!(r["changed"], 0);
let h = &s.doc().unwrap().history;
assert_eq!((h.undo.len(), h.redo.len()), (undo, redo), "no undo step, and redo kept");
let words = json!([{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 6, "end": 11}]);
assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}))["changed"], 1);
assert_eq!(plain(&s, a), "fixed fixed");
}
/// Each change to the custom dictionary moves its generation on, whether it is saved or not, so
/// what Auto Spell Check found before is checked again.
#[test]
+12
View File
@@ -1347,6 +1347,18 @@ impl Session {
}
// Every value is checked before any is set, so an invalid one changes nothing.
vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?;
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
// The most the selected image can be cropped to, when one is selected.
let max = self.doc().ok().and_then(|st| {
let (id, _) = crop::selected_image(&st.doc, &st.selection)?;
match &st.doc.node(id)?.kind {
vectorcraft_doc::NodeKind::Image(im) => Some(crop::image_ppi(im).1),
_ => None,
}
});
crop::check_options(&values, max)?;
}
// The Place queue is read later, by a click outside any automation scope: its files must
// be readable now, under the roots of whoever sets it.
if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) {
+1 -1
View File
@@ -854,7 +854,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.cropImage",
"Crop Image",
"",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box. → {tool}; a tool that cannot be chosen returns the error",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is and it can be cropped to it), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error",
),
("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"),
(
+1 -1
View File
@@ -70,7 +70,7 @@ pub use stylistic_sets::StylisticSet;
use traits::Alias;
#[cfg(test)]
use traits::{FaceKeys, face_names};
pub use traits::{FontClass, FontMatch, FontTraits};
pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits};
#[cfg(test)]
pub(crate) use traits::{alias_lists, face_styles, on_faces_published};
pub use wanted::{WantedFont, WantedFonts};
+4 -1
View File
@@ -8,7 +8,10 @@ pub(super) struct CatalogFamily {
/// Non-English family name from the name table, when the scan found one.
pub(super) native: Option<String>,
pub(super) faces: Vec<CatalogFace>,
/// The family's kind (from its first face found); variable when any face found is.
/// The family's kind (from its first face found); variable when any face found is. Its
/// likeness is the one of the face found nearest an upright Regular ([`regular_rank`]).
///
/// [`regular_rank`]: super::traits::regular_rank
pub(super) traits: Option<FontTraits>,
}
+4 -1
View File
@@ -16,7 +16,7 @@ use super::scan::{file_face_names, is_font_file};
#[cfg(test)]
use super::traits::faces_published;
#[cfg(not(target_arch = "wasm32"))]
use super::traits::{Alias, FaceStyle};
use super::traits::{Alias, FaceStyle, regular_rank};
use super::{Arc, AtomicU64, FontDb, FontPaths, HashMap, Mutex, Ordering, Path, PathBuf, RwLock, StringId};
#[cfg(not(target_arch = "wasm32"))]
use super::{ScanStamp, modified};
@@ -430,6 +430,9 @@ impl FontDb {
let entry = catalog.entry(family.to_ascii_lowercase()).or_default();
let kind = entry.traits.get_or_insert(traits);
kind.variable |= traits.variable;
if regular_rank(&traits.likeness) < regular_rank(&kind.likeness) {
kind.likeness = traits.likeness;
}
if entry.name.is_empty() {
entry.name = family;
}
+5
View File
@@ -356,6 +356,11 @@ impl FontFace {
pub fn x_height(&self) -> f64 {
self.x_height
}
/// The height of the capital letters in font units, positive (estimated from the ascent when
/// the font has no OS/2 value).
pub fn cap_height(&self) -> f64 {
self.cap_height
}
/// The line gap the font asks for between lines, in font units (from the same table as
/// [`vertical_metrics`](Self::vertical_metrics); 0 when it has none).
pub fn line_gap(&self) -> f64 {
+99 -13
View File
@@ -9,7 +9,7 @@ use super::names::SYSTEM_FALLBACKS;
use super::names::{norm, norm_chars, script_families};
#[cfg(not(target_arch = "wasm32"))]
use super::scan::{enumerate_faces, font_files};
use super::traits::{Alias, FontMatch, FontTraits};
use super::traits::{Alias, FontMatch, FontTraits, regular_rank};
use super::{
Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX,
Ordering, Size,
@@ -18,6 +18,45 @@ use super::{
/// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads.
const MAX_POSTSCRIPT_FACES: usize = 16;
/// Keeps `other`'s variable flag in `traits`, and its likeness when it is nearer an upright
/// Regular.
fn merge_traits(traits: &mut FontTraits, other: &FontTraits) {
traits.variable |= other.variable;
if regular_rank(&other.likeness) < regular_rank(&traits.likeness) {
traits.likeness = other.likeness;
}
}
/// The traits of the loaded faces of each family, or of `only` that family, keyed by the family's
/// name in ASCII lowercase: the first face's, with the other faces merged in ([`merge_traits`]).
fn loaded_traits(faces: &[Arc<FontFace>], only: Option<&str>) -> std::collections::HashMap<String, FontTraits> {
let mut found = std::collections::HashMap::<String, FontTraits>::new();
for f in faces.iter().filter(|f| only.is_none_or(|o| f.family.eq_ignore_ascii_case(o))) {
match found.entry(f.family.to_ascii_lowercase()) {
std::collections::hash_map::Entry::Vacant(e) => {
e.insert(f.traits);
}
std::collections::hash_map::Entry::Occupied(mut e) => merge_traits(e.get_mut(), &f.traits),
}
}
found
}
/// A family's traits from its `loaded` faces with what the scan in `catalog` found for `key` (its
/// name in ASCII lowercase) merged in, or the scan's alone when none is loaded.
fn scanned_traits(loaded: Option<FontTraits>, catalog: &Catalog, key: &str) -> FontTraits {
let scanned = catalog.get(key).and_then(|c| c.traits);
match loaded {
None => scanned.unwrap_or_default(),
Some(mut traits) => {
if let Some(found) = scanned {
merge_traits(&mut traits, &found);
}
traits
}
}
}
impl FontDb {
/// The family's own name and the style for a name given in a document: any of a family's
/// names (`ヒラギノ角ゴシック` is Hiragino Sans), a legacy family name (`Hiragino Sans W6` with its
@@ -86,26 +125,73 @@ impl FontDb {
/// loaded face, else from the system font scan. Variable when any of its faces, loaded or
/// scanned, is: a family may install static files beside a variable one. Cheap: no font file
/// is read, and a loaded family doesn't start the scan. A composite font takes its base font's.
/// Its likeness is the one of its face nearest an upright Regular, loaded or scanned.
pub fn family_traits(&self, family: &str) -> FontTraits {
if let Some((base, _)) = self.composite_base(family) {
return self.family_traits(&base);
}
let loaded = {
let faces = self.read_faces();
let mut of_family = faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family));
of_family.next().map(|first| FontTraits { variable: first.traits.variable || of_family.any(|f| f.traits.variable), ..first.traits })
};
let scanned = |catalog: &Catalog| catalog.get(&family.to_ascii_lowercase()).and_then(|c| c.traits);
let key = family.to_ascii_lowercase();
let loaded = loaded_traits(&self.read_faces(), Some(family)).remove(&key);
match loaded {
None => scanned(&self.read_catalog()).unwrap_or_default(),
Some(traits) if traits.variable => traits,
Some(traits) => {
let variable = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)).is_some_and(|t| t.variable);
FontTraits { variable, ..traits }
}
None => scanned_traits(None, &self.read_catalog(), &key),
// What the scan found so far, without starting it.
Some(_) => scanned_traits(loaded, &self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner), &key),
}
}
/// The name [`family_traits`](Self::family_traits) takes `family`'s traits by, in ASCII
/// lowercase: a composite font's base font's.
fn traits_key(&self, family: &str) -> String {
match self.composite_base(family) {
Some((base, _)) => self.traits_key(&base),
None => family.to_ascii_lowercase(),
}
}
/// `families` ordered by how alike they look to `family` (Show Similar Fonts): `family` itself
/// first when listed, then the families that set the same script as it (Japanese, Thai or
/// neither, as [`FontTraits`] tells), then the others, each group nearest first by
/// [`FontLikeness::distance`](super::FontLikeness::distance) of their
/// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`])
/// counting 2 further. Families equally far keep their order in `families`. Reads no font
/// file, as `family_traits` does not.
pub fn similar_families(&self, family: &str, families: &[String]) -> Vec<String> {
let base = self.family_traits(family);
let script = |t: &FontTraits| {
if t.japanese {
0
} else if t.thai {
1
} else {
2
}
};
// Every family's traits from one pass over the loaded faces and one look at the scan, as
// `family_traits` finds them; composite fonts are resolved before any lock is held.
let keys: Vec<String> = families.iter().map(|f| self.traits_key(f)).collect();
let loaded = loaded_traits(&self.read_faces(), None);
let catalog = if keys.iter().all(|k| loaded.contains_key(k)) {
self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)
} else {
self.read_catalog()
};
let mut keyed: Vec<(bool, f32, &String)> = families
.iter()
.zip(&keys)
.map(|(f, key)| {
let traits = scanned_traits(loaded.get(key).copied(), &catalog, key);
let d = if f.eq_ignore_ascii_case(family) {
-1.0
} else {
base.likeness.distance(&traits.likeness) + if traits.class == base.class { 0.0 } else { 2.0 }
};
(script(&traits) != script(&base), d, f)
})
.collect();
keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
keyed.into_iter().map(|(_, _, f)| f.clone()).collect()
}
/// [`face`](Self::face) by any of the family's names ([`canonical`](Self::canonical)), and how
/// it matched. A composite font matches as its base font does ([`Self::composite_base`]).
pub fn resolve(&self, family: &str, style: &str) -> Option<(Arc<FontFace>, FontMatch)> {
+20 -10
View File
@@ -160,6 +160,8 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa
use std::io::SeekFrom;
/// The largest table read from a (possibly damaged) file.
const MAX_NAME_TABLE: u32 = 1 << 20;
/// The `post` table's header: version, italic angle, underline and fixed-pitch fields.
const POST_HEADER: u32 = 32;
let mut read = 0u64;
let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {
read = read.checked_add(u64::try_from(len).ok()?).filter(|r| *r <= max_read)?;
@@ -186,26 +188,34 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa
if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {
return None;
}
let mut table = |tag: &[u8; 4]| -> Option<Vec<u8>> {
// A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` gives nothing.
let mut table_within = |tag: &[u8; 4], most: u32| -> Option<Vec<u8>> {
let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?;
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?);
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?.min(most));
if len > MAX_NAME_TABLE {
return None;
}
read_at(offset.into(), len as usize)
};
let name = table(b"name")?;
let name = table_within(b"name", u32::MAX)?;
// A variable font's named instances are styles too.
let fvar = table(b"fvar");
let fvar = table_within(b"fvar", u32::MAX);
// Its OS/2 table (the font's classification, for the menus' filters), when it has one.
let os2 = table(b"OS/2");
let os2 = table_within(b"OS/2", u32::MAX);
// Its units per em and italic angle, for Show Similar Fonts ([`super::FontLikeness`]):
// the `head` table and the `post` table's 32-byte header, as a version 3 table (one
// without glyph names).
let head = table_within(b"head", u32::MAX);
let post = table_within(b"post", POST_HEADER).filter(|p| p.len() == POST_HEADER as usize).map(|mut p| {
p[..4].copy_from_slice(&0x0003_0000_u32.to_be_bytes());
p
});
// A font holding just these tables, to read them as the font itself would.
let mut tables: Vec<(&[u8; 4], &[u8])> = vec![(b"name", &name)];
if let Some(fvar) = &fvar {
tables.push((b"fvar", fvar));
}
if let Some(os2) = &os2 {
tables.push((b"OS/2", os2));
for (tag, data) in [(b"fvar", &fvar), (b"OS/2", &os2), (b"head", &head), (b"post", &post)] {
if let Some(data) = data {
tables.push((tag, data.as_slice()));
}
}
let font = sfnt_of(&tables)?;
Some(face_styles(&skrifa::FontRef::new(&font).ok()?))
+130 -6
View File
@@ -101,6 +101,111 @@ pub struct FontTraits {
/// The face has variation axes (an `fvar` table of at most 64 axes); for a family, one of
/// its faces has.
pub variable: bool,
/// What Show Similar Fonts compares; for a family, its face nearest an upright Regular.
pub likeness: FontLikeness,
}
/// The numbers a font menu's Show Similar Fonts compares faces by ([`FontLikeness::distance`]),
/// read from the face's OS/2, `head` and `post` tables only, so that the system font scan reads
/// the same numbers without loading the font ([`super::scan::file_face_names`]). Each is 0 (the
/// italic angle `None`) when the face does not say (no such table, or an OS/2 table too old to
/// hold the value).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FontLikeness {
/// The OS/2 PANOSE digits (0 is "any" and 1 "no fit" in each digit).
pub panose: [u8; 10],
/// The OS/2 weight class, at most 1000; a named instance's `wght` setting.
pub weight: u16,
/// The OS/2 width class, 1 to 9.
pub width: u8,
/// The OS/2 x-height and cap height in thousandths of the em.
pub x_height: u16,
pub cap_height: u16,
/// The OS/2 average character width in thousandths of the em.
pub avg_width: u16,
/// The `post` table's italic angle in tenths of a degree (negative: leaning right); a named
/// instance's `slnt` setting.
pub italic_angle: Option<i16>,
/// The face is italic or oblique: by its OS/2 selection flags or a nonzero italic angle; a
/// named instance by its `ital` or `slnt` setting or its name. Not compared; it picks a
/// family's face nearest an upright Regular.
pub italic: bool,
}
impl FontLikeness {
/// From a face's tables, with a named instance's `variations` (its axis settings in user
/// units; empty for the face itself): its `weight` (`wght` setting) in place of the OS/2
/// weight class, its `slnt` setting in place of the italic angle, and whether it is
/// `italic`. The heights and the average width need the `head` table's units per em (16 to
/// 16384).
fn of(font: &skrifa::FontRef<'_>, variations: &[Variation], weight: Option<f32>, italic: Option<bool>) -> Self {
use skrifa::raw::TableProvider;
let em = font.head().ok().map(|h| h.units_per_em()).filter(|u| (16..=16384).contains(u)).map(f32::from);
// Thousandths of the em, 0 for nothing (and for a value at or below 0).
let per_mille = |v: i16| match em {
Some(em) if v > 0 => (f32::from(v) / em * 1000.0).round().min(4000.0) as u16,
_ => 0,
};
let mut likeness = Self::default();
if let Ok(o) = font.os2() {
for (digit, value) in likeness.panose.iter_mut().zip(o.panose_10()) {
*digit = *value;
}
likeness.weight = o.us_weight_class().min(1000);
likeness.width = u8::try_from(o.us_width_class()).ok().filter(|w| (1..=9).contains(w)).unwrap_or(0);
likeness.x_height = o.sx_height().map_or(0, per_mille);
likeness.cap_height = o.s_cap_height().map_or(0, per_mille);
likeness.avg_width = per_mille(o.x_avg_char_width());
// fsSelection's ITALIC (bit 0) and OBLIQUE (bit 9) flags.
likeness.italic = o.fs_selection().bits() & 0x0201 != 0;
}
if let Some(w) = weight.filter(|w| w.is_finite()) {
likeness.weight = w.round().clamp(1.0, 1000.0) as u16;
}
let angle = |a: f32| (a.is_finite() && a.abs() <= 90.0).then(|| (a * 10.0).round() as i16);
likeness.italic_angle = match variations.iter().find(|(tag, _)| tag == b"slnt") {
Some((_, slant)) => angle(*slant),
None => font.post().ok().and_then(|p| angle(p.italic_angle().to_f32())),
};
likeness.italic = italic.unwrap_or(likeness.italic || likeness.italic_angle.is_some_and(|a| a != 0));
likeness
}
/// How unlike two faces look: 0 for faces whose numbers are all the same, more the further
/// apart they are. A number one of the faces does not give is left out. PANOSE digits are
/// compared only between faces of the same PANOSE family kind; faces of different kinds count
/// 3 apart. The weights and scales are VectorCraft's own.
pub fn distance(&self, other: &Self) -> f32 {
let mut d = 0.0;
let (kind, other_kind) = (self.panose[0], other.panose[0]);
if kind > 1 && other_kind > 1 {
if kind == other_kind {
for (a, b) in self.panose.iter().zip(&other.panose).skip(1) {
if *a > 1 && *b > 1 {
d += f32::from(a.abs_diff(*b)) * 0.15;
}
}
} else {
d += 3.0;
}
}
if self.weight != 0 && other.weight != 0 {
d += f32::from(self.weight.abs_diff(other.weight)) / 200.0;
}
if self.width != 0 && other.width != 0 {
d += f32::from(self.width.abs_diff(other.width)) * 0.5;
}
for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)]
{
if a != 0 && b != 0 {
d += f32::from(a.abs_diff(b)) / 1000.0 * scale;
}
}
if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) {
d += f32::from(a.abs_diff(b)) / 50.0;
}
d
}
}
impl FontTraits {
@@ -216,10 +321,20 @@ impl FontTraits {
FontClass::Other
};
let variable = (1..=MAX_AXES).contains(&font.axes().len());
FontTraits { japanese, thai, class, variable }
FontTraits { japanese, thai, class, variable, likeness: FontLikeness::of(font, &[], None, None) }
}
}
/// How far a face is from an upright Regular by its `likeness`: an italic or oblique face
/// ([`FontLikeness::italic`]) after every upright one, then by how far its weight is from 400 (a
/// face that gives no weight last), then by the numbers themselves, so that the same faces give
/// the same answer whichever is found or loaded first. The lower, the nearer. A family's likeness
/// ([`FontTraits::likeness`]) is its lowest-ranked face's, whether the faces are scanned or loaded.
pub(super) fn regular_rank(likeness: &FontLikeness) -> (bool, u16, FontLikeness) {
let off = if likeness.weight == 0 { u16::MAX } else { likeness.weight.abs_diff(400) };
(likeness.italic, off, *likeness)
}
/// What a name other than a family's own one stands for ([`FontDb::canonical`]).
#[derive(Clone, Debug)]
pub(super) struct Alias {
@@ -342,11 +457,7 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec<FaceStyle> {
let Some((family, style)) = face_names(f) else { return vec![] };
let native_family = native_family_name(f, &family);
let mut keys = FaceKeys::of(f, &family, &style);
let traits = FontTraits::of(f, &keys);
let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone());
for i in &mut instances {
i.traits = traits;
}
let mut traits = FontTraits::of(f, &keys);
// A variable font's default face renders at its `wght` default, whatever its name table and
// OS/2 table say (Noto Sans Hebrew: named `Light`, weight class 300, default instance Regular
// at 400): weigh it so, and name it by its default instance when that is another weight.
@@ -357,6 +468,19 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec<FaceStyle> {
.map(|a| a.default_value())
.filter(|w| w.is_finite())
.map(|w| w.clamp(1.0, 1000.0));
// Its likeness is likewise taken at its axes' defaults (`wght` and `slnt`).
if f.axes().len() <= MAX_AXES {
let defaults: Vec<Variation> = f.axes().iter().map(|a| (a.tag().to_be_bytes(), a.default_value())).collect();
traits.likeness = FontLikeness::of(f, &defaults, weight, None);
}
let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone());
// Each named instance shares the face's kind; its likeness is measured at its own axis settings.
// Without an `ital` or `slnt` axis, an instance of an italic face is italic too.
for i in &mut instances {
let slant_axis = i.variations.iter().any(|(tag, _)| tag == b"ital" || tag == b"slnt");
let italic = i.italic || (!slant_axis && traits.likeness.italic);
i.traits = FontTraits { likeness: FontLikeness::of(f, &i.variations, i.weight, Some(italic)), ..traits };
}
let style = renamed.unwrap_or(style);
let face = FaceStyle { family, native_family, style, keys, variations: vec![], weight, italic: false, traits };
std::iter::once(face).chain(instances).collect()
+4 -4
View File
@@ -41,10 +41,10 @@ pub use features::{
EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by,
};
pub use fontdb::{
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphCategory, GlyphCategoryKind,
GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont,
WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined,
style_weight, system_font_dirs, user_font_dirs,
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphCategory,
GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind,
WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs,
set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
};
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
+1
View File
@@ -28,6 +28,7 @@ mod path_joins;
mod ruby;
mod scripts;
mod shape_plans;
mod similar;
mod snap;
mod svg_glyphs;
mod sysfonts;
+119
View File
@@ -0,0 +1,119 @@
//! Show Similar Fonts: the numbers a face is compared by ([`FontLikeness`]), a family's likeness
//! from its face nearest an upright Regular, and families ordered by likeness.
use skrifa::raw::TableProvider;
use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font};
use crate::*;
/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without
/// heights in their OS/2 tables.
fn db() -> FontDb {
let db = FontDb::with_font_dirs(vec![]);
for heights in [true, false] {
assert_eq!(db.add_font(height_font(heights).expect("the test font builds")), 1);
}
db
}
fn names(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect()
}
#[test]
fn a_face_is_compared_by_its_tables() {
let db = db();
let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness;
assert_eq!(regular.weight, 400);
assert_eq!(regular.italic_angle, Some(0));
assert!(regular.panose[0] > 1, "a PANOSE family kind: {regular:?}");
assert!(regular.x_height > 300 && regular.cap_height > regular.x_height, "{regular:?}");
// The OS/2 average character width, in thousandths of the em.
let bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSans3-Regular.ttf")).expect("bundled");
let font = skrifa::FontRef::new(&bytes).expect("it parses");
let (avg, em) = (font.os2().expect("an OS/2 table").x_avg_char_width(), font.head().expect("a head table").units_per_em());
assert_eq!(f32::from(regular.avg_width), (f32::from(avg) / f32::from(em) * 1000.0).round());
let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness;
assert!(italic.italic_angle.is_some_and(|a| a < 0), "leans right: {italic:?}");
assert!(italic.italic && !regular.italic);
let bold = db.face("Source Sans 3", "Bold").expect("bundled").traits.likeness;
assert_eq!(bold.weight, 700);
// The OS/2 heights, in thousandths of its 1,000-unit em.
let heights = db.family_traits(HEIGHT_FAMILY).likeness;
assert_eq!((heights.x_height, heights.cap_height), (HEIGHT_X as u16, HEIGHT_CAP as u16));
// Without them (a version 1 OS/2 table), the heights are left out.
let heightless = db.family_traits(HEIGHTLESS_FAMILY).likeness;
assert_eq!((heightless.x_height, heightless.cap_height), (0, 0), "{heightless:?}");
assert_eq!(heightless.avg_width, regular.avg_width);
}
/// A variable font's named instance takes its `wght` setting as its weight; the default face its
/// default weight.
#[test]
fn a_named_instance_is_weighed_by_its_axis_setting() {
let db = FontDb::with_font_dirs(vec![]);
assert_eq!(db.add_font(variable_font().expect("the test font builds")), 3);
let regular = db.face(VARIABLE_FAMILY, "Regular").expect("the default face").traits.likeness;
let semibold = db.face(VARIABLE_FAMILY, "SemiBold").expect("a named instance").traits.likeness;
let bold = db.face(VARIABLE_FAMILY, "Bold").expect("a named instance").traits.likeness;
assert_eq!((regular.weight, semibold.weight, bold.weight), (400, 550, 700));
// The family is compared by its Regular face.
assert_eq!(db.family_traits(VARIABLE_FAMILY).likeness, regular);
}
/// A face without an italic angle is compared by the other numbers only.
#[test]
fn a_missing_italic_angle_is_left_out() {
let db = db();
let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness;
assert_eq!(italic.distance(&FontLikeness { italic_angle: None, ..italic }), 0.0);
assert!(italic.distance(&FontLikeness { italic_angle: Some(0), ..italic }) > 0.0);
}
/// A family is compared by its face nearest an upright Regular, not by the first one loaded.
#[test]
fn a_family_is_compared_by_its_regular_face() {
let db = db();
let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness;
assert_eq!(db.family_traits("Source Sans 3").likeness, regular);
assert_eq!(db.family_traits("source sans 3").likeness, regular, "by any case");
}
#[test]
fn likeness_is_a_distance() {
let db = db();
let (sans, serif, mono) =
(db.family_traits("Source Sans 3").likeness, db.family_traits("Source Serif 4").likeness, db.family_traits("JetBrains Mono").likeness);
assert_eq!(sans.distance(&sans), 0.0);
assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric");
assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0);
// A number a face does not give is left out, not counted as 0.
let unknown = FontLikeness::default();
assert_eq!(sans.distance(&unknown), 0.0);
let lighter = FontLikeness { weight: 300, ..sans };
assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart");
}
/// The family itself first, then nearest first: a copy of Source Sans 3 Regular comes before every
/// other family, and the order never moves away from the family and back.
#[test]
fn families_are_ordered_by_likeness() {
let db = db();
let families = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]);
let order = db.similar_families("Source Sans 3", &families);
assert_eq!(order.len(), families.len());
assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}");
let base = db.family_traits("Source Sans 3");
let far = |f: &str| {
let t = db.family_traits(f);
base.likeness.distance(&t.likeness) + if t.class == base.class { 0.0 } else { 2.0 }
};
for pair in order[1..].windows(2) {
assert!(far(&pair[0]) <= far(&pair[1]), "{order:?}");
}
// Asked by another case, or for a family not in the list.
assert_eq!(db.similar_families("SOURCE SANS 3", &families)[0], "Source Sans 3");
let without = db.similar_families("Source Sans 3", &families[..4]);
assert_eq!(without[0], HEIGHTLESS_FAMILY);
assert!(db.similar_families("Source Sans 3", &[]).is_empty());
}
+25 -2
View File
@@ -428,6 +428,29 @@ fn a_family_with_a_variable_file_beside_static_ones_is_variable() {
assert!(db.family_traits(FAMILY).variable);
}
/// Show Similar Fonts: the scan reads the numbers a face is compared by as loading the face does,
/// and a family's are its Regular face's whichever file is found first.
#[test]
fn the_scan_reads_a_familys_likeness_without_loading_it() {
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-likeness", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("Sysfont-Italic.ttf"), renamed("SourceSans3-It.ttf")).unwrap();
std::fs::write(dir.join("Sysfont-Regular.ttf"), renamed("SourceSans3-Regular.ttf")).unwrap();
let scanned = FontDb::with_font_dirs(vec![dir.clone()]);
let likeness = scanned.family_traits(FAMILY).likeness;
assert!(!scanned.is_loaded(FAMILY), "the scan's numbers, nothing loaded");
let loaded = FontDb::with_font_dirs(vec![]);
assert_eq!(loaded.add_font(renamed("SourceSans3-Regular.ttf")), 1);
assert_eq!(likeness, loaded.face(FAMILY, "Regular").unwrap().traits.likeness);
assert!(likeness.avg_width > 0 && likeness.x_height > 0 && likeness.italic_angle == Some(0), "{likeness:?}");
// With only the italic loaded, the scanned Regular face still gives the family's numbers.
assert_eq!(scanned.add_font(renamed("SourceSans3-It.ttf")), 1);
assert!(scanned.is_loaded(FAMILY));
assert_eq!(scanned.family_traits(FAMILY).likeness, likeness);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn registered_fonts_outside_the_font_folders_are_their_full_paths() {
let dir = std::env::temp_dir().join("Fonts");
@@ -697,8 +720,8 @@ fn a_search_reads_at_most_its_share_of_a_font_file() {
let r = (0..tables).map(|i| 12 + 16 * i).find(|&r| &face[r..r + 4] == tag).unwrap();
u64::from(u32::from_be_bytes(face[r + 12..r + 16].try_into().unwrap()))
};
// What one face costs: its table directory and its name and OS/2 tables.
let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2");
// What one face costs: its table directory, its name, OS/2 and head tables and the post table's header.
let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2") + len(b"head") + 32;
let n = 300;
let base = 12 + 4 * n;
let mut ttc = b"ttcf".to_vec();
+263 -5
View File
@@ -1,7 +1,7 @@
//! Portable 3D effect geometry: Revolve, Extrude & Bevel, Inflate and Rotate. No windowing, GPU or
//! document dependencies.
//!
//! Open profiles optionally close their circular ends with caps. Faces are projected and sorted back to front,
//! Open profiles optionally close their circular ends with caps, and a partial sweep its cut sides. Faces are projected and sorted back to front,
//! then flat or smoothly shaded with vector gradients. This preview uses a painter's algorithm, not a depth buffer:
//! intersecting profiles can have ambiguous visibility and are not solid modelling inputs.
#![forbid(unsafe_code)]
@@ -102,9 +102,14 @@ pub struct Revolve {
pub shade: bool,
/// Interpolate profile normals using vector gradients. Enabled by default.
pub smooth_shading: bool,
/// Close circular endpoint rings of open profiles. Partial sweeps get sectors;
/// the angular cut sides are left open. Enabled by default.
/// Close circular endpoint rings of open profiles (sectors on a partial sweep), and the two
/// angular cut sides of a partial sweep: each is one flat face of the region between an open
/// profile and the axis, and of a closed profile's own area with its holes left open. Off, the
/// surface is hollow. Enabled by default.
pub cap_ends: bool,
/// The profile's fill rule, which decides the holes the cut sides leave open in [`revolve`] and
/// [`revolve_shadowed`]. Nonzero by default.
pub fill_rule: FillRule,
/// Samples for each curved profile segment, from [`revolve_curve_samples`] for the surfaces of
/// one object. `None` plans them from the profile alone.
pub curve_samples: Option<usize>,
@@ -140,6 +145,7 @@ impl Default for Revolve {
shade: true,
smooth_shading: true,
cap_ends: true,
fill_rule: FillRule::NonZero,
curve_samples: None,
map_surface: false,
}
@@ -729,7 +735,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi
/// Evaluate a profile in document space. All subpaths share one axis from `bounds`.
/// Invalid or excessively complex inputs return an error, never a partial surface.
pub fn revolve(path: &PathData, bounds: Rect, options: Revolve) -> Result<Vec<Face>, String> {
revolve_faces(path, FillRule::NonZero, bounds, options, None)
revolve_faces(path, options.fill_rule, bounds, options, None)
}
/// [`revolve`]'s faces as facets, back to front, for the classic surfaces: each keeps its
@@ -772,7 +778,10 @@ pub fn revolve_curve_samples<'a>(paths: impl IntoIterator<Item = &'a PathData>,
if lines.saturating_add(curves.saturating_mul(MIN_CURVE_SAMPLES)) > points {
return Err(TOO_COMPLEX_PROFILE.into());
}
let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)) / per_edge).min(points);
// A partial sweep with caps closes each of its two cut sides with a face for each outline,
// planned here as one for each contour.
let cut_sides = if o.cap_ends && o.angle > 0.0 && o.angle < 360.0 { contours.saturating_mul(2) } else { 0 };
let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)).saturating_sub(cut_sides) / per_edge).min(points);
if curves == 0 {
return if lines > edges { Err(TOO_COMPLEX_SURFACE.into()) } else { Ok(CURVE_SAMPLES) };
}
@@ -1055,6 +1064,249 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i
Ok(())
}
/// Twice the signed area of the polygon `ring`.
fn ring_area(ring: &[Point]) -> f64 {
ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.x * q.y - q.x * p.y).sum()
}
/// The region a cut side of a partial sweep closes for one contour's profile `points`, in the
/// profile's plane and in the order the profile runs: a closed contour's own area, or an open one
/// closed along the axis at `axis` from its last end back to its first. An open contour whose ends
/// meet is taken as closed. The region is given as the loops the nonzero rule fills, so one that
/// crosses itself, such as a bow tie, gives a loop for each part it encloses. None when the contour
/// encloses no area.
fn cut_region(points: &[Point], closed: bool, axis: f64) -> Vec<Vec<Point>> {
let ring = cut_ring(points, closed, axis);
if ring.len() < 3 {
return vec![];
}
let crossed = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&ring, true)]);
// A loop thinner than 0.000001 pt is left out, as the solids' rings leave out such debris.
match vectorcraft_pathops::try_unite_all_with(&[(&crossed, FillRule::NonZero)], 1e-6) {
Ok(loops) => loops
.subpaths
.iter()
.map(|s| s.anchors.iter().map(|a| a.p).collect::<Vec<_>>())
.filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10)
.collect(),
// Past the boolean's limits the region is kept as the profile draws it, as the solids'
// rings keep theirs.
Err(_) if ring_area(&ring).abs() > 1e-10 => vec![ring],
Err(_) => vec![],
}
}
/// The ring around the region of one contour's profile `points` ([`cut_region`]), without repeated
/// points or a last point that repeats the first.
fn cut_ring(points: &[Point], closed: bool, axis: f64) -> Vec<Point> {
let (Some(&first), Some(&last)) = (points.first(), points.last()) else { return vec![] };
let mut ring = points.to_vec();
if !closed && first.distance(last) > 1e-10 {
ring.extend([Point::new(axis, last.y), Point::new(axis, first.y)]);
}
ring.dedup_by(|a, b| a.distance(*b) <= 1e-10);
while ring.len() > 1 && ring.first().zip(ring.last()).is_some_and(|(a, b)| a.distance(*b) <= 1e-10) {
ring.pop();
}
ring
}
/// The steps at whose ends the two cut sides of a partial sweep lie, each with its outward normal
/// before the view's rotation: the start faces back against the sweep, the end on along it.
fn cut_sides(at: &Sweeping) -> [(usize, V3); 2] {
// The profile lies on one side of the axis: the sweep turns it forward on the left and back on
// the right.
let side = if at.o.edge == Edge::Left { 1.0 } else { -1.0 };
let (s, c) = at.sweep.sin_cos();
[(0, V3(0.0, 0.0, -side)), (at.steps, V3(-s * side, 0.0, c * side))]
}
/// Whether `p` lies inside the polygon `ring`.
fn ring_contains(ring: &[Point], p: Point) -> bool {
let mut inside = false;
for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()) {
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
inside = !inside;
}
}
inside
}
/// The regions `regions` (turned as [`oriented`] gives them) grouped into the faces of one cut
/// side: each outline, counterclockwise, first, with the holes, clockwise, that the smallest outline
/// around them holds.
fn cut_groups(regions: &[Vec<Point>]) -> Vec<Vec<&Vec<Point>>> {
let bounds = |r: &[Point]| r.iter().fold(Rect::new(f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |b, p| b.union_pt(*p));
// Each outline with its bounds and area, and the holes it holds.
let mut groups: Vec<(Rect, f64, Vec<&Vec<Point>>)> =
regions.iter().filter(|r| ring_area(r) > 0.0).map(|r| (bounds(r), ring_area(r), vec![r])).collect();
for hole in regions.iter().filter(|r| ring_area(r) < 0.0) {
let Some(&p) = hole.first() else { continue };
let owner =
groups.iter_mut().filter(|(b, _, g)| b.contains(p) && g.first().is_some_and(|o| ring_contains(o, p))).min_by(|a, b| a.1.total_cmp(&b.1));
if let Some((_, _, g)) = owner {
g.push(hole);
}
}
groups.into_iter().map(|(_, _, g)| g).collect()
}
/// One face of the cut side of a partial sweep at the end of step `step`: an outline among the
/// regions ([`cut_groups`]) and its holes, turned there and drawn as one flat, evenly shaded face,
/// filled with the nonzero rule, so its holes stay open. The outline gives the face's shading,
/// depth and polygon. `None` when it is seen edge on.
fn cut_face(at: &Sweeping, regions: &[&Vec<Point>], step: usize, eye: Option<f64>, light: V3) -> Result<Option<Face>, String> {
let origin = Point::new(at.axis, at.center_y);
let turned: Vec<Vec<V3>> = regions.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect();
let Some(vertices) = turned.first() else { return Ok(None) };
let Some(mut face) = project_face(vertices, None, at.o, origin, eye, light)? else { return Ok(None) };
let project = |v: &V3| {
let factor = perspective_scale(eye, v.2);
Point::new(origin.x + v.0 * factor, origin.y + v.1 * factor)
};
let drawn: Vec<Vec<Point>> = turned.iter().map(|c| c.iter().map(project).collect()).collect();
if drawn.iter().flatten().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
return Err("Revolve projection is not finite".into());
}
face.outline = Some(PathData::new(drawn.iter().map(|c| vectorcraft_geom::SubPath::polyline(c, true)).collect()));
Ok(Some(face))
}
/// Both cut sides of a partial sweep drawn, a face for each outline among `regions` with its holes
/// ([`cut_face`]), those seen edge on left out; none for no regions.
fn cut_faces(at: &Sweeping, regions: &[Vec<Point>], eye: Option<f64>, light: V3) -> Result<Vec<Face>, String> {
let groups = cut_groups(regions);
let mut out = vec![];
for (step, _) in cut_sides(at) {
for group in &groups {
out.extend(cut_face(at, group, step, eye, light)?);
}
}
Ok(out)
}
/// The profiles whose regions the cut sides of a partial sweep close, contour by contour, each with
/// whether its contour is closed: those of the profile drawn, and those of the profile kept for a
/// mesh. Each profile is added as its faces are swept, with any anchor [`ring_cut`] adds, so the
/// cut sides have a corner at every corner of the edges they share with the side.
struct CutRegions {
/// A partial sweep with caps: there are cut sides to close.
on: bool,
drawn: Vec<(Vec<Point>, bool)>,
kept: Vec<(Vec<Point>, bool)>,
}
/// The loops of one contour's region turned so the region runs counterclockwise in the profile's
/// plane: filled with the nonzero rule, it fills. Its largest loop decides, and loops inside it that
/// run the other way stay holes of it.
fn outlined(mut loops: Vec<Vec<Point>>) -> Vec<Vec<Point>> {
let largest = loops.iter().map(|l| ring_area(l)).max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or_default();
if largest < 0.0 {
loops.iter_mut().for_each(|l| l.reverse());
}
loops
}
/// The regions the cut sides of a partial sweep close for the profiles `contours`, as loops that
/// the nonzero rule fills: outlines run counterclockwise in the profile's plane and holes clockwise.
/// Each open contour closes its own region ([`cut_region`]). The closed contours together close
/// what `rule` fills of them, so a contour that walls a hole leaves it open, and the parts where
/// contours overlap are filled or left open as `rule` fills them; a closed contour alone closes its
/// own region. Every corner of the closed contours' profiles on the region's edge stays a corner
/// of it. An error when the closed contours pass the limits of combining them.
fn cut_loops(contours: &[(Vec<Point>, bool)], rule: FillRule, axis: f64) -> Result<Vec<Vec<Point>>, String> {
let mut out = vec![];
let mut rings = vec![];
for (points, closed) in contours {
if *closed {
rings.push(points);
} else {
out.extend(outlined(cut_region(points, false, axis)));
}
}
match rings.as_slice() {
[] => {}
[one] => out.extend(outlined(cut_region(one, true, axis))),
_ => {
let subpaths =
rings.iter().map(|r| cut_ring(r, true, axis)).filter(|r| r.len() >= 3).map(|r| vectorcraft_geom::SubPath::polyline(&r, true));
let path = PathData::new(subpaths.collect());
let filled = vectorcraft_pathops::try_unite_all_with(&[(&path, rule)], 1e-6).map_err(|_| TOO_COMPLEX_PROFILE.to_string())?;
// The union gives outlines counterclockwise and holes clockwise. A loop thinner than
// 0.000001 pt is left out, as in [`cut_region`].
out.extend(
filled
.subpaths
.iter()
.map(|s| s.anchors.iter().map(|a| a.p).collect::<Vec<_>>())
.filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10),
);
}
}
Ok(out)
}
impl CutRegions {
/// The regions of a sweep with sanitized options `o`, none yet.
fn new(o: Revolve) -> Self {
Self { on: o.cap_ends && o.angle > 0.0 && o.angle < 360.0, drawn: vec![], kept: vec![] }
}
/// Add a contour's profile `s`, drawn or kept for a mesh as `kept` says.
fn add(&mut self, s: &Swept, closed: bool, kept: bool) {
if self.on {
let to = if kept { &mut self.kept } else { &mut self.drawn };
to.push((s.points.clone(), closed));
}
}
/// Close the cut sides of sweep `at` about `axis`, the holes `rule` leaves left open: keep them
/// for the mesh, if any, of `kept` (whether faces are drawn, the mesh, and the error that
/// stopped it, as [`lose_mesh`] takes them) within `face_limit` faces, and give them drawn
/// ([`cut_faces`]).
fn close(
&self,
at: &Sweeping,
(rule, axis): (FillRule, f64),
kept: (bool, &mut Option<&mut Vec<solid::Face3>>, &mut Option<String>),
face_limit: usize,
eye: Option<f64>,
light: V3,
) -> Result<Vec<Face>, String> {
let (draw, mesh, lost) = kept;
let result = match mesh.as_deref_mut() {
Some(m) => cut_loops(&self.kept, rule, axis).and_then(|loops| {
keep_cuts(at, &loops, |contours, normal| {
m.push((contours, normal));
if m.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) }
})
}),
None => Ok(()),
};
if let Err(e) = result {
lose_mesh(draw, mesh, lost, e)?;
}
if !draw {
return Ok(vec![]);
}
cut_faces(at, &cut_loops(&self.drawn, rule, axis)?, eye, light)
}
}
/// Keep for a mesh the two cut sides of a partial sweep: the loops `loops` of their regions
/// ([`cut_loops`]) turned to each side. Outlines run one way round and holes the other, so the mesh
/// leaves the holes open. `keep` keeps one face with its outward normal.
fn keep_cuts(at: &Sweeping, loops: &[Vec<Point>], mut keep: impl FnMut(Vec<Vec<V3>>, V3) -> Result<(), String>) -> Result<(), String> {
if loops.is_empty() {
return Ok(());
}
for (step, normal) in cut_sides(at) {
let contours = loops.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect();
keep(contours, at.o.rotate(normal))?;
}
Ok(())
}
/// Keep no more faces for a mesh after error `e`, which is the result when no face is drawn.
fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec<solid::Face3>>, lost: &mut Option<String>, e: String) -> Result<(), String> {
if !draw {
@@ -1152,6 +1404,9 @@ fn revolve_sweep(
// its edges are cut into.
let (mut count, mut kept_count) = (0, 0);
let mut curve_budget = 0;
// With caps, a partial sweep closes its two cut sides: the regions of every contour drawn, and
// those kept for the mesh with whether each walls a hole.
let mut cuts = CutRegions::new(o);
for (contour, sp) in path.subpaths.iter().enumerate() {
let (mut drawn, mut kept) = (Swept::default(), Swept::default());
if let Some(first) = sp.anchors.first() {
@@ -1274,6 +1529,7 @@ fn revolve_sweep(
};
if let Some(m) = mesh.as_deref_mut() {
let turn = prepare(&mut kept);
cuts.add(&kept, sp.closed, true);
let caps: Vec<usize> = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect();
let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal));
if let Err(e) = kept {
@@ -1284,6 +1540,7 @@ fn revolve_sweep(
continue;
}
let turn = prepare(&mut drawn);
cuts.add(&drawn, sp.closed, false);
let profile = &drawn.points;
let along = along_profile(profile, axis, sp.closed);
for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() {
@@ -1344,6 +1601,7 @@ fn revolve_sweep(
}
}
}
cuts.close(&at, (rule, axis), (draw, &mut mesh, &mut lost), face_limit, eye, light)?.into_iter().try_for_each(|face| emit(Some(face), 1))?;
faces.sort_by(|a, b| a.depth.total_cmp(&b.depth));
Ok((faces, lost))
}
+5 -4
View File
@@ -118,8 +118,9 @@ pub fn inflate_meshed(
}
/// Revolve's surface ([`crate::revolve`]) as a mesh. As the effect draws it, a sweep of less than
/// 360° caps its ends with sectors and leaves its two cut sides open ([`Revolve::cap_ends`]). The
/// walls of holes under `rule`, such as the counter of an O, face into the hole.
/// 360° caps its ends with sectors and closes its two cut sides with flat faces ([`Revolve::cap_ends`]).
/// The walls of holes under `rule`, such as the counter of an O, face into the hole, and the cut
/// sides leave those holes open.
pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result<Mesh, String> {
let mut faces = vec![];
crate::revolve_faces(path, rule, bounds, options, Some(&mut faces))?;
@@ -127,7 +128,7 @@ pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revo
}
/// The area-weighted normal of `contours` (Newell's method).
fn newell(contours: &[Vec<V3>]) -> V3 {
pub(crate) fn newell(contours: &[Vec<V3>]) -> V3 {
let mut n = V3::default();
for c in contours {
for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) {
@@ -210,7 +211,7 @@ fn spend(work: &mut usize, steps: usize) -> Result<(), String> {
/// The triangles covering one face: `contours` (outlines one way round, holes the other) on the
/// plane across `normal` (its Newell normal).
fn triangulate(contours: &[Vec<V3>], normal: V3, work: &mut usize) -> Result<Vec<[V3; 3]>, String> {
pub(crate) fn triangulate(contours: &[Vec<V3>], normal: V3, work: &mut usize) -> Result<Vec<[V3; 3]>, String> {
// Cut the face on the coordinate plane it is least slanted to, turned so outlines run
// counterclockwise.
let (ax, ay, az) = (normal.0.abs(), normal.1.abs(), normal.2.abs());
+6 -2
View File
@@ -239,7 +239,7 @@ fn a_revolved_profile_is_a_closed_cylinder() {
}
#[test]
fn a_partial_revolve_caps_its_ends_with_sectors() {
fn a_partial_revolve_caps_its_ends_with_sectors_and_closes_its_cut_sides() {
let mut b = BezPath::new();
b.move_to((20.0, 0.0));
b.line_to((20.0, 100.0));
@@ -247,8 +247,12 @@ fn a_partial_revolve_caps_its_ends_with_sectors() {
let r = p.bounds().unwrap();
let o = Revolve { angle: 90.0, offset: 10.0, segments: 64, ..Revolve::default() };
let m = revolve_mesh(&p, FillRule::NonZero, r, o).unwrap();
let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0);
// The side and the two end sectors, and the two cut sides, each 10 pt from the axis by 100 pt.
let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0) + 2.0 * 10.0 * 100.0;
assert!((area(&m) - exact).abs() / exact < 0.01, "{} vs {exact}", area(&m));
assert!(closed(&m), "the quarter of a cylinder is a closed solid");
let hollow = revolve_mesh(&p, FillRule::NonZero, r, Revolve { cap_ends: false, ..o }).unwrap();
assert!(!closed(&hollow));
}
#[test]
+2 -2
View File
@@ -335,11 +335,11 @@ pub fn inflate_shadowed(
}
/// Revolve's surface ([`crate::revolve`]) and, from the same sweep, the faces
/// [`ShadowCaster::revolve`] adds for it with the nonzero fill rule. An error where
/// [`ShadowCaster::revolve`] adds for it with the fill rule of `options`. An error where
/// [`crate::revolve`] gives one.
pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec<Face>, SolidFaces), String> {
let mut kept = vec![];
let (faces, lost) = crate::revolve_sweep(path, FillRule::NonZero, bounds, options, true, Some(&mut kept))?;
let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept))?;
let projection = Some(crate::revolve_projection(bounds, options.sanitized()));
Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection }))
}
+1
View File
@@ -2,6 +2,7 @@ use super::*;
mod caps;
mod classic;
mod cut_sides;
mod lighting;
mod multiple_lights;
mod profile_limits;
+297
View File
@@ -0,0 +1,297 @@
use crate::*;
use vectorcraft_geom::Shape;
/// Swept with Cap on, unshaded and seen from the front.
fn options() -> Revolve {
Revolve { cap_ends: true, shade: false, ..Default::default() }
}
fn profile(data: &str) -> PathData {
PathData::from_bezpath(&BezPath::from_svg(data).unwrap())
}
fn area(face: &Face) -> f64 {
face.path().to_bezpath().area().abs()
}
/// The faces of the cut sides among `faces`: the flat faces in a plane through the axis, which these
/// tests keep upright. The strips of the swept side lie off the axis, and the endpoint caps across it.
fn cut_sides(faces: &[Face]) -> Vec<&Face> {
faces.iter().filter(|f| !f.cap && f.plane.is_some_and(|p| p.offset.abs() < 1e-6 && p.normal[1].abs() < 1e-9)).collect()
}
#[test]
fn a_half_turn_closes_both_cut_sides_with_the_region_between_the_profile_and_the_axis() {
let path = profile("M40 10 L40 90");
let bounds = Rect::new(0.0, 10.0, 40.0, 90.0);
// Seen from the front, a half turn's two cut sides both face the viewer: the profile's plane
// to the right of the axis and to its left.
let faces = revolve(&path, bounds, Revolve { angle: 180.0, ..options() }).unwrap();
let cuts = cut_sides(&faces);
assert_eq!(cuts.len(), 2);
for cut in &cuts {
assert!((area(cut) - 40.0 * 80.0).abs() < 1e-6, "{}", area(cut));
assert!(cut.points.iter().all(|p| (10.0 - 1e-9..=90.0 + 1e-9).contains(&p.y)));
}
assert!(cuts.iter().any(|f| f.points.iter().all(|p| p.x >= -1e-9)));
assert!(cuts.iter().any(|f| f.points.iter().all(|p| p.x <= 1e-9)));
assert!(faces.windows(2).all(|pair| pair[0].depth <= pair[1].depth));
}
#[test]
fn cap_off_full_turns_and_no_turn_leave_the_cut_sides_open() {
let path = profile("M40 10 L40 90");
let bounds = Rect::new(0.0, 10.0, 40.0, 90.0);
for (o, what) in [
(Revolve { angle: 180.0, cap_ends: false, ..options() }, "hollow"),
(Revolve { angle: 360.0, rotation_x: 90.0, ..options() }, "a full turn"),
(Revolve { angle: 0.0, ..options() }, "no turn"),
] {
let faces = revolve(&path, bounds, o).unwrap();
assert!(cut_sides(&faces).is_empty(), "{what}");
}
}
#[test]
fn a_closed_profile_closes_its_cut_sides_with_its_area_and_leaves_its_hole_open() {
// A square ring away from the axis, its hole wound the other way.
let path = profile("M20 10 L60 10 L60 50 L20 50 Z M30 20 L30 40 L50 40 L50 20 Z");
let bounds = path.bounds().unwrap();
let o = Revolve { angle: 180.0, offset: 10.0, rotation_y: 20.0, ..options() };
let faces = revolve(&path, bounds, o).unwrap();
let cuts = cut_sides(&faces);
assert_eq!(cuts.len(), 2);
for cut in &cuts {
let outline = cut.outline.as_ref().unwrap();
assert_eq!(outline.subpaths.len(), 2, "the outline and its hole");
// Turned 20° about the vertical axis, each side is foreshortened by cos 20°.
let expected = (40.0 * 40.0 - 20.0 * 20.0) * 20f64.to_radians().cos();
assert!((area(cut) - expected).abs() < 1e-6, "{} != {expected}", area(cut));
}
// Visibility measures the face with its hole open.
assert!(!visible_faces(&faces).unwrap().is_empty());
}
#[test]
fn an_even_odd_hole_wound_with_its_outline_stays_open_in_the_drawn_cut_sides() {
// The hole runs the same way round as the outline, so only the even-odd rule leaves it open.
let path = profile("M20 10 L60 10 L60 50 L20 50 Z M30 20 L50 20 L50 40 L30 40 Z");
let bounds = path.bounds().unwrap();
let o = Revolve { angle: 180.0, offset: 10.0, ..options() };
let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::EvenOdd, ..o }).unwrap();
let cuts = cut_sides(&faces);
assert_eq!(cuts.len(), 2);
for cut in cuts {
// The drawn path is filled with the nonzero rule; the hole is in the middle of the side.
let filled = cut.path().to_bezpath();
assert!(!filled.contains(filled.bounding_box().center()));
assert!((area(cut) - (40.0 * 40.0 - 20.0 * 20.0)).abs() < 1e-6, "{}", area(cut));
}
// Under the nonzero rule the inner contour fills too: each side is the whole outer square.
let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::NonZero, ..o }).unwrap();
let areas: Vec<f64> = cut_sides(&faces).iter().map(|f| area(f)).collect();
assert_eq!(areas.len(), 2);
assert!(areas.iter().all(|a| (a - 1600.0).abs() < 1e-6), "{areas:?}");
}
#[test]
fn a_bow_tie_whose_loops_cancel_out_closes_its_cut_sides_with_both_loops() {
// Two triangles of 400 pt² that meet at (40, 30), wound opposite ways.
let path = profile("M20 10 L60 50 L60 10 L20 50 Z");
let bounds = path.bounds().unwrap();
let o = Revolve { angle: 180.0, offset: 10.0, rotation_y: 20.0, ..options() };
let faces = revolve(&path, bounds, o).unwrap();
let cuts = cut_sides(&faces);
// Each side draws each loop as a face.
assert_eq!(cuts.len(), 4);
let expected = 400.0 * 20f64.to_radians().cos();
for cut in cuts {
assert!((area(cut) - expected).abs() < 1e-6, "{} != {expected}", area(cut));
}
let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, Revolve { angle: 90.0, rotation_y: 0.0, ..o }).unwrap();
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
assert!((start - 800.0).abs() < 1e-6, "{start}");
}
#[test]
fn the_mesh_closes_a_cut_side_that_crosses_itself_with_both_of_its_loops() {
// Loops of 900 pt² and 100 pt² that meet at (50, 40): the mesh covers both, and nothing
// between them.
let path = profile("M20 10 L60 50 L60 30 L20 70 Z");
let bounds = path.bounds().unwrap();
let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, Revolve { angle: 90.0, offset: 10.0, ..options() }).unwrap();
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
assert!((start - 1000.0).abs() < 1e-6, "{start}");
}
#[test]
fn a_region_thinner_than_a_millionth_of_a_point_is_debris_and_closes_no_cut_side() {
// 0.0000005 pt wide and 80 pt tall, beside a square 40 pt across.
let path = profile("M40 10 L40.0000005 10 L40.0000005 90 L40 90 Z M50 10 L90 10 L90 50 L50 50 Z");
let bounds = path.bounds().unwrap();
let o = Revolve { angle: 90.0, offset: 10.0, ..options() };
let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, o).unwrap();
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
assert!((start - 40.0 * 40.0).abs() < 1e-6, "{start}");
}
#[test]
fn cut_sides_whose_holes_cannot_be_found_within_the_limit_are_refused() {
// 2,100 squares on top of each other: each test of a point meets every square.
let square = "M20 10 L60 10 L60 50 L20 50 Z ";
let path = profile(&square.repeat(2100));
let bounds = path.bounds().unwrap();
let o = Revolve { angle: 90.0, offset: 10.0, ..options() };
assert_eq!(revolve(&path, bounds, o).err().as_deref(), Some(TOO_COMPLEX_PROFILE));
// Hollow, the sweep has no cut sides to close.
assert!(revolve(&path, bounds, Revolve { cap_ends: false, ..o }).is_ok());
}
#[test]
fn visibility_keeps_both_of_two_separate_regions_wound_opposite_ways() {
let path = profile("M20 10 L30 10 L30 50 L20 50 Z M40 10 L40 50 L50 50 L50 10 Z");
let bounds = path.bounds().unwrap();
// Seen from behind, the half turn's walls are behind both cut sides, which nothing covers. Seen
// from the front, the walls the outer square sweeps cover both sides completely.
for (rotation_y, all) in [(180.0, 4.0 * 10.0 * 40.0), (0.0, 0.0)] {
let faces = revolve(&path, bounds, Revolve { angle: 180.0, offset: 10.0, rotation_y, ..options() }).unwrap();
let cuts = cut_sides(&faces);
assert_eq!(cuts.len(), 4, "a face for each region on each side");
let mut depths: Vec<f64> = cuts.iter().map(|f| f.depth).collect();
depths.dedup();
let visible = visible_faces(&faces).unwrap();
let shown: f64 = visible
.iter()
.filter(|v| depths.contains(&v.depth))
.flat_map(|v| v.path.subpaths.iter().map(|s| PathData::new(vec![s.clone()]).to_bezpath().area().abs()))
.sum();
assert!((shown - all).abs() < 1e-6, "turned {rotation_y}°, the cut sides show {shown}, not {all}");
}
}
#[test]
fn every_open_contour_of_a_compound_profile_closes_its_own_region_on_each_side() {
let path = profile("M40 10 L40 40 M20 60 L50 90");
let bounds = Rect::new(0.0, 10.0, 50.0, 90.0);
let faces = revolve(&path, bounds, Revolve { angle: 180.0, ..options() }).unwrap();
let mut areas: Vec<f64> = cut_sides(&faces).iter().map(|f| area(f)).collect();
areas.sort_by(f64::total_cmp);
// The trapezoid between the slanted line and the axis, (20 + 50) / 2 × 30, and 40 × 30.
let expected = [35.0 * 30.0, 35.0 * 30.0, 40.0 * 30.0, 40.0 * 30.0];
assert_eq!(areas.len(), 4);
assert!(areas.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-6), "{areas:?}");
}
#[test]
fn a_cut_side_seen_edge_on_is_not_drawn() {
let path = profile("M40 10 L40 90");
let bounds = Rect::new(0.0, 10.0, 40.0, 90.0);
// A quarter turn ends in the plane through the axis toward the viewer.
let faces = revolve(&path, bounds, Revolve { angle: 90.0, ..options() }).unwrap();
let cuts = cut_sides(&faces);
assert_eq!(cuts.len(), 1);
assert!((area(cuts[0]) - 40.0 * 80.0).abs() < 1e-6);
}
#[test]
fn cut_sides_are_shaded_evenly_by_their_plane() {
let path = profile("M40 10 L40 90");
let bounds = Rect::new(0.0, 10.0, 40.0, 90.0);
let o = Revolve { angle: 180.0, shade: true, rotation_y: 30.0, ..options() };
let faces = revolve(&path, bounds, o).unwrap();
let cuts = cut_sides(&faces);
assert_eq!(cuts.len(), 2);
for cut in cuts {
assert!(cut.gradient.is_none(), "a flat face is shaded evenly");
assert!(cut.plane.is_some());
assert!((0.0..=1.0).contains(&cut.brightness));
// Both sides lie in the plane through the axis turned 30°, whose normal faces the viewer.
let n = cut.normal;
assert!((n[0].abs() - 30f64.to_radians().sin()).abs() < 1e-9 && n[2] > 0.0, "{n:?}");
}
}
/// The area of the triangles of `mesh` whose normal is `normal`.
fn area_facing(mesh: &Mesh, normal: [f64; 3]) -> f64 {
mesh.triangles
.iter()
.filter(|t| t.iter().all(|&i| mesh.normals[i as usize].iter().zip(normal).all(|(a, b)| (a - b).abs() < 1e-9)))
.map(|t| {
let [a, b, c] = t.map(|i| mesh.positions[i as usize]);
let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
let x = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]).sqrt() / 2.0
})
.sum()
}
#[test]
fn the_mesh_closes_both_cut_sides_and_leaves_holes_open_under_either_fill_rule() {
let ring = "M20 10 L60 10 L60 50 L20 50 Z";
let o = Revolve { angle: 90.0, offset: 10.0, ..options() };
let expected = 40.0 * 40.0 - 20.0 * 20.0;
// The hole wound against the outline, and wound with it under even-odd.
for (hole, rule) in [("M30 20 L30 40 L50 40 L50 20 Z", FillRule::NonZero), ("M30 20 L50 20 L50 40 L30 40 Z", FillRule::EvenOdd)] {
let path = profile(&format!("{ring} {hole}"));
let mesh = revolve_mesh(&path, rule, path.bounds().unwrap(), o).unwrap();
// The start faces back, against the sweep; a quarter turn ends facing left, along it.
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
let end = area_facing(&mesh, [-1.0, 0.0, 0.0]);
assert!((start - expected).abs() < 1e-6, "{rule:?}: {start}");
assert!((end - expected).abs() < 1e-6, "{rule:?}: {end}");
}
let path = profile(ring);
let hollow = revolve_mesh(&path, FillRule::NonZero, path.bounds().unwrap(), Revolve { cap_ends: false, ..o }).unwrap();
assert_eq!(area_facing(&hollow, [0.0, 0.0, -1.0]), 0.0);
}
#[test]
fn overlapping_contours_close_the_cut_sides_with_what_the_fill_rule_fills() {
// Two squares of 1,600 pt² that overlap in 300 pt², and only one corner of each lies inside
// the other. The even-odd rule leaves the overlap open; the nonzero rule fills it once.
let path = profile("M20 10 L60 10 L60 50 L20 50 Z M50 20 L90 20 L90 60 L50 60 Z");
let bounds = path.bounds().unwrap();
let o = Revolve { angle: 180.0, offset: 10.0, ..options() };
for (rule, expected) in [(FillRule::EvenOdd, 2.0 * (1600.0 - 300.0)), (FillRule::NonZero, 2.0 * 1600.0 - 300.0)] {
let faces = revolve(&path, bounds, Revolve { fill_rule: rule, ..o }).unwrap();
let cuts = cut_sides(&faces);
let total: f64 = cuts.iter().map(|f| area(f)).sum();
assert!((total - 2.0 * expected).abs() < 1e-6, "{rule:?}: both sides cover {total}, not twice {expected}");
let mesh = revolve_mesh(&path, rule, bounds, Revolve { angle: 90.0, ..o }).unwrap();
let start = area_facing(&mesh, [0.0, 0.0, -1.0]);
assert!((start - expected).abs() < 1e-6, "{rule:?}: {start}");
}
}
#[test]
fn the_cut_sides_kept_for_a_mesh_have_a_corner_at_every_corner_of_the_side() {
// With graphics mapped, the square's side is cut half way round from its outer side, at
// (20, 30), which is not an anchor: the cut side takes that corner too.
let path = profile("M20 10 L60 10 L60 50 L20 50 Z");
let bounds = path.bounds().unwrap();
let o = Revolve { angle: 90.0, offset: 10.0, map_surface: true, ..options() };
let mut faces = vec![];
revolve_faces(&path, FillRule::NonZero, bounds, o, Some(&mut faces)).unwrap();
// The corners in the plane where the sweep starts, of every face kept for the mesh and of the
// cut side's alone, which faces back against the sweep.
let in_plane = |all: bool| {
let start = |n: &V3| (n.0.abs() + n.1.abs() + (n.2 + 1.0).abs()) < 1e-9;
let kept = faces.iter().filter(|(_, n)| all || start(n));
kept.flat_map(|(contours, _)| contours.iter().flatten().copied()).filter(|v| v.2.abs() < 1e-9).collect::<Vec<V3>>()
};
let cut = in_plane(false);
assert!(!cut.is_empty());
for p in in_plane(true) {
assert!(cut.iter().any(|q| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9), "{p:?} is not a corner of the cut side");
}
}
#[test]
fn the_mesh_cut_sides_face_out_of_a_sweep_on_the_left_of_its_axis() {
// The axis is 40 pt to the right of the line, which sweeps from the left of the axis to its back.
let path = profile("M40 10 L40 90");
let o = Revolve { angle: 90.0, edge: Edge::Right, offset: 40.0, ..options() };
let mesh = revolve_mesh(&path, FillRule::NonZero, Rect::new(40.0, 10.0, 40.0, 90.0), o).unwrap();
assert!((area_facing(&mesh, [0.0, 0.0, 1.0]) - 40.0 * 80.0).abs() < 1e-6);
assert!((area_facing(&mesh, [1.0, 0.0, 0.0]) - 40.0 * 80.0).abs() < 1e-6);
}
+5 -2
View File
@@ -199,7 +199,8 @@ pub fn visible_faces(faces: &[Face]) -> Result<Vec<VisibleFace>, String> {
}) {
return Err("Revolve visibility requires finite projected faces".into());
}
let all = faces.iter().flat_map(|f| &f.points).copied().collect::<Vec<_>>();
let outlines = faces.iter().filter_map(|f| f.outline.as_ref()).flat_map(|o| o.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)));
let all = faces.iter().flat_map(|f| f.points.iter().copied()).chain(outlines).collect::<Vec<_>>();
let total = bounds(&all);
if total.width() <= 0.0 || total.height() <= 0.0 {
return Ok(vec![]);
@@ -222,7 +223,9 @@ pub fn visible_faces(faces: &[Face]) -> Result<Vec<VisibleFace>, String> {
if pieces.is_empty() {
continue;
}
let source_bounds = bounds(&face.points);
// A face drawn as several contours, such as a cut side of a partial sweep, reaches past its
// own polygon: look for covers over all of its pieces.
let source_bounds = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)).unwrap_or_else(|| bounds(&face.points));
let mut fragments: Vec<_> = pieces.iter().map(|p| p.points.clone()).collect();
let mut clipped = false;
'covers: for tile in index.tiles(source_bounds) {
+19
View File
@@ -91,6 +91,22 @@ fn triangulate(mut points: Vec<Point>, epsilon: f64, work: &mut usize, depth: us
Ok(out)
}
/// Triangles covering a flat face drawn as several straight-edged contours, such as a cut side of a
/// partial Revolve whose profile has holes: outlines one way round and holes the other, the holes
/// left uncovered. The work is checked before the face is cut, at four times its corners squared.
fn with_holes(outline: &vectorcraft_geom::PathData, epsilon: f64, work: &mut usize) -> Result<Vec<Vec<Point>>, String> {
const LIMIT: &str = "Revolve visibility exceeds its geometry work limit";
let rings: Vec<Vec<crate::V3>> = outline.subpaths.iter().map(|s| s.anchors.iter().map(|a| crate::V3(a.p.x, a.p.y, 0.0)).collect()).collect();
let corners: usize = rings.iter().map(Vec::len).sum();
*work = work.saturating_add(corners.saturating_mul(corners).saturating_mul(4));
if *work > MAX_WORK {
return Err(LIMIT.into());
}
let mut spent = 0;
let triangles = crate::mesh::triangulate(&rings, crate::mesh::newell(&rings), &mut spent)?;
Ok(triangles.into_iter().map(|t| clean(t.iter().map(|v| Point::new(v.0, v.1)).collect(), epsilon)).filter(|t| !t.is_empty()).collect())
}
pub(super) fn pieces(face: &Face, epsilon: f64, work: &mut usize) -> Result<Vec<Vec<Point>>, String> {
if let Some(strips) = &face.visibility_pieces {
let mut out = vec![];
@@ -99,6 +115,9 @@ pub(super) fn pieces(face: &Face, epsilon: f64, work: &mut usize) -> Result<Vec<
}
return Ok(out);
}
if let Some(outline) = face.outline.as_ref().filter(|o| !face.cap && o.subpaths.len() > 1) {
return with_holes(outline, epsilon, work);
}
if !face.cap {
return triangulate(clean(face.points.clone(), epsilon), epsilon, work, 0);
}
+369 -20
View File
@@ -2,10 +2,12 @@
//! its artboard (the whole image when it lies inside one); its handles and its inside drag it,
//! always within the image, and the part outside it is dimmed. Enter (or the Control bar's Apply)
//! crops the image to it (`object.cropImage {rect}`), Escape (or Cancel) leaves it as it was; both
//! go back to the Selection tool. The Control bar edits the box through the `rect` option.
//! go back to the Selection tool. The Control bar edits the box through the `rect` option, the
//! point its X and Y name through `reference`, whether its W and H keep their proportions through
//! `linked`, and the cropped image's resolution through `ppi`.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, Selection};
use vectorcraft_doc::{Document, ImageObject, NodeId, NodeKind, Selection};
use vectorcraft_geom::{Point, Rect, Vec2};
use crate::bbox::{Handle, hit_handle};
@@ -18,6 +20,97 @@ pub const ID: &str = "cropImage";
/// The smallest the box gets, in points.
const MIN: f64 = 1.0;
/// The resolutions the Control bar's PPI list offers; those above the image's own are disabled.
pub const PPI_CHOICES: [f64; 5] = [72.0, 96.0, 150.0, 200.0, 300.0];
/// The highest resolution a linked image can be cropped to.
pub const LINKED_MAX_PPI: f64 = 300.0;
/// The reference point the box's X and Y name by default: its center (of the nine points of
/// [`vectorcraft_geom::reference_point`], left to right and top to bottom).
pub const CENTER: usize = 4;
/// An image's own resolution in pixels per inch (along its denser side, measured on its pixel
/// grid, so turning it changes nothing), and the highest resolution it can be cropped to: its own,
/// or [`LINKED_MAX_PPI`] for a linked image.
pub fn image_ppi(im: &ImageObject) -> (f64, f64) {
let [a, b, c, d, _, _] = im.xf.as_coeffs();
// The document lengths of one pixel's sides.
let (sx, sy) = (a.hypot(b), c.hypot(d));
let own = 72.0 / sx.min(sy).max(1e-9);
(own, if im.link.is_some() { LINKED_MAX_PPI } else { own })
}
/// Whether cropping `im` at `ppi` keeps its pixels as they are: its pixels are square (the same
/// resolution across and down) and at that resolution, within `tolerance` ppi.
pub fn keeps_resolution(im: &ImageObject, ppi: f64, tolerance: f64) -> bool {
let [a, b, c, d, _, _] = im.xf.as_coeffs();
let (x, y) = (72.0 / a.hypot(b).max(1e-9), 72.0 / c.hypot(d).max(1e-9));
(x - ppi).abs() <= tolerance && (y - ppi).abs() <= tolerance
}
/// Checks the values `tool.setOption` gives the tool before any is set: `ppi` a number from 1 to
/// 2400, and no more than `max` (the selected image's limit, from [`image_ppi`]), or null;
/// `reference` a whole number from 0 to 8; `linked` true or false.
pub fn check_options(values: &serde_json::Map<String, Value>, max: Option<f64>) -> Result<(), String> {
for (key, v) in values {
let error = match key.as_str() {
"ppi" if v.is_null() => None,
"ppi" => match v.as_f64().filter(|n| (1.0..=2400.0).contains(n)) {
None => Some(format!("`ppi` must be a number from 1 to 2400 or null, not {v}")),
Some(n) => {
max.filter(|m| n > m + 1e-6).map(|m| format!("`ppi` can't be more than {} for this image", (m * 100.0 + 1e-6).floor() / 100.0))
}
},
"reference" => (!v.as_u64().is_some_and(|n| n <= 8)).then(|| format!("`reference` must be a whole number from 0 to 8, not {v}")),
"linked" => (!v.is_boolean()).then(|| format!("`linked` must be true or false, not {v}")),
_ => None,
};
if let Some(e) = error {
return Err(e);
}
}
Ok(())
}
/// The box `r` over an image with bounds `image`, with one Control bar field set: `x` or `y` moves
/// the box so its `reference` point is there; `width` or `height` resizes it about that point, the
/// other side following in proportion when `linked`. Sizes below [`MIN`] are raised to it, a
/// linked size with both sides together so it keeps its proportions. A
/// linked size is held to the image with both sides scaled together, and a box that fits is slid
/// back within the image, so its proportions survive being kept within it. `None` for another key
/// or a value that isn't finite.
pub fn edited_box(r: Rect, image: Rect, reference: usize, linked: bool, key: &str, v: f64) -> Option<Rect> {
if !v.is_finite() {
return None;
}
let p = vectorcraft_geom::reference_point(r, reference);
let (mut w, mut h) = (r.width(), r.height());
let fit = |b: Rect| if b.width() <= image.width() + 1e-9 && b.height() <= image.height() + 1e-9 { slid_within(b, image) } else { b };
match key {
"x" => return Some(fit(r + Vec2::new(v - p.x, 0.0))),
"y" => return Some(fit(r + Vec2::new(0.0, v - p.y))),
// Linked, both sides take one scale, raised so neither side falls below MIN.
"width" | "height" if linked && w > 0.0 && h > 0.0 => {
let k = (v / if key == "width" { w } else { h }).max(MIN / w).max(MIN / h);
(w, h) = (w * k, h * k);
}
"width" => w = v.max(MIN),
"height" => h = v.max(MIN),
_ => return None,
}
if linked {
let k = (image.width() / w).min(image.height() / h).min(1.0);
if k.is_finite() && k > 0.0 {
(w, h) = (w * k, h * k);
}
}
// The reference point keeps its place: it sits at the same fraction of the new box.
let (fx, fy) = ((reference % 3) as f64 / 2.0, (reference / 3).min(2) as f64 / 2.0);
let (x0, y0) = (p.x - w * fx, p.y - h * fy);
Some(fit(Rect::new(x0, y0, x0 + w, y0 + h)))
}
/// Create the Crop Image tool by id (None = not ours).
pub fn create(id: &str) -> Option<Box<dyn Tool>> {
(id == ID).then(|| Box::new(CropImageTool::default()) as Box<dyn Tool>)
@@ -75,7 +168,6 @@ enum Drag {
Move(Point, Rect),
}
#[derive(Default)]
pub struct CropImageTool {
/// The box, for the image it was made for (None: set from outside, for the selected image);
/// None until it's dragged or set.
@@ -83,6 +175,18 @@ pub struct CropImageTool {
drag: Option<Drag>,
/// Where the pointer last was on the canvas (measurement label during a drag).
last: Point,
/// The cropped image's resolution in pixels per inch (None: the image's own).
ppi: Option<f64>,
/// The point of the box the Control bar's X and Y name (0..=8, [`CENTER`] by default).
reference: usize,
/// Whether the Control bar's W and H keep the box's proportions.
linked: bool,
}
impl Default for CropImageTool {
fn default() -> Self {
Self { rect: None, drag: None, last: Point::ZERO, ppi: None, reference: CENTER, linked: false }
}
}
impl CropImageTool {
@@ -93,24 +197,49 @@ impl CropImageTool {
crop_box(cx.doc, cx.selection, set)
}
/// Crop to the box and go back to the Selection tool (only back when it covers the image).
/// Crop to the box at the chosen resolution and go back to the Selection tool (only back when
/// the box covers the image and the resolution is the image's own). The box and the resolution
/// are forgotten when the tool is left, so a crop that fails keeps them for another try.
fn apply(&mut self, cx: &ToolContext) -> Vec<Action> {
let current = self.current(cx);
self.reset();
let ppi = self.ppi;
self.drag = None;
let mut out = vec![];
if let Some((_, image, r)) = current
&& !same(r, image)
{
out.push(Action::Exec("object.cropImage".into(), json!({ "rect": [r.x0, r.y0, r.width(), r.height()] })));
if let Some((id, image, r)) = current {
let im = match cx.doc.node(id).map(|n| &n.kind) {
Some(NodeKind::Image(im)) => Some(&**im),
_ => None,
};
let max = im.map_or(f64::INFINITY, |im| image_ppi(im).1);
// A resolution set before this image was selected is held to this image's limit.
let resample = ppi.map(|v| v.min(max)).filter(|v| im.is_none_or(|im| !keeps_resolution(im, *v, 1e-3)));
// A turned or skewed image is drawn to be cropped: the resolution goes with it even when
// it is the image's own, which the PPI field shows until another is chosen (when it is
// one `object.cropImage` takes). A resolution chosen for it crops even over the whole box.
let drawn = im.filter(|im| {
let [_, b, c, _, _, _] = im.xf.as_coeffs();
b.abs() > 1e-9 || c.abs() > 1e-9
});
let own = |im: &ImageObject| Some(image_ppi(im).0).filter(|v| (1.0..=2400.0).contains(v) && *v <= max + 1e-6);
let send = resample.or_else(|| drawn.and_then(|im| ppi.map(|v| v.min(max)).or_else(|| own(im))));
if !same(r, image) || resample.is_some() || (drawn.is_some() && ppi.is_some()) {
let mut p = json!({ "rect": [r.x0, r.y0, r.width(), r.height()] });
if let Some(v) = send {
p["ppi"] = json!(v);
}
out.push(Action::Exec("object.cropImage".into(), p));
}
}
out.push(Action::SwitchTool("selection".into()));
out
}
/// Forget the box and the resolution; the reference point and the link stay as they were set.
fn reset(&mut self) {
self.rect = None;
self.drag = None;
self.last = Point::ZERO;
self.ppi = None;
}
}
@@ -242,19 +371,40 @@ impl Tool for CropImageTool {
}
/// `rect`: the box as `[x, y, width, height]` once it's been dragged or set (until then it's
/// [`initial_box`]).
/// [`initial_box`]); `ppi` once it's been set (until then the image's own); `reference` (0..=8)
/// and `linked`.
fn options(&self) -> Value {
match self.rect {
Some((_, r)) => json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }),
None => json!({}),
let mut o = json!({ "reference": self.reference, "linked": self.linked });
if let Some((_, r)) = self.rect {
o["rect"] = json!([r.x0, r.y0, r.width(), r.height()]);
}
if let Some(v) = self.ppi {
o["ppi"] = json!(v);
}
o
}
/// `rect` `[x, y, width, height]` sets the box (kept within the selected image when used);
/// anything else puts it back where it starts.
/// anything else puts it back where it starts. `ppi` a positive number sets the cropped
/// image's resolution (null: the image's own). `reference` a whole number 0..=8 sets the point X and Y name, and `linked`
/// true or false the link of W and H. `tool.setOption` refuses other values of those three
/// ([`check_options`]); one that reaches the tool anyway puts that setting back to its default.
fn set_option(&mut self, key: &str, value: &Value) {
if key != "rect" {
return;
match key {
"ppi" => {
self.ppi = value.as_f64().filter(|v| v.is_finite() && *v > 0.0);
return;
}
"reference" => {
self.reference = value.as_u64().filter(|v| *v <= 8).map_or(CENTER, |v| v as usize);
return;
}
"linked" => {
self.linked = value.as_bool().unwrap_or(false);
return;
}
"rect" => {}
_ => return,
}
// Invalid components must discard the whole box, not silently shift the
// coordinates by dropping a non-numeric entry.
@@ -310,6 +460,15 @@ mod tests {
}
}
/// Enter, then the switch to the Selection tool that a crop that ran is followed by.
fn enter(t: &mut CropImageTool, cx: &ToolContext) -> Vec<Action> {
let acts = t.key(cx, ToolKey::Enter, Mods::default());
if acts.contains(&Action::SwitchTool("selection".into())) {
assert!(t.deactivate(cx).is_empty());
}
acts
}
fn crop_rect(acts: &[Action]) -> Option<Vec<f64>> {
acts.iter().find_map(|a| match a {
Action::Exec(c, v) if c == "object.cropImage" => Some(v["rect"].as_array()?.iter().filter_map(Value::as_f64).collect()),
@@ -341,11 +500,11 @@ mod tests {
assert_eq!(ov.iter().filter(|o| matches!(o, Overlay::Highlight { .. })).count(), 2, "above and right of the box");
assert_eq!(ov.iter().filter(|o| matches!(o, Overlay::Handle { .. })).count(), 8);
// Enter crops to it and goes back to the Selection tool.
let acts = t.key(&cx, ToolKey::Enter, Mods::default());
let acts = enter(&mut t, &cx);
assert_eq!(crop_rect(&acts), Some(vec![50.0, 70.0, 130.0, 90.0]));
assert_eq!(acts.last(), Some(&Action::SwitchTool("selection".into())));
assert!(t.options().get("rect").is_none(), "the next crop starts afresh");
assert!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())).is_none(), "the whole image: nothing to cut");
assert!(crop_rect(&enter(&mut t, &cx)).is_none(), "the whole image: nothing to cut");
}
/// In a view turned 90° the handles' cursors turn with the view.
@@ -369,10 +528,10 @@ mod tests {
let mut t = CropImageTool::default();
drag(&mut t, &cx, (100.0, 150.0), (110.0, 150.0));
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("selection".into())]);
assert_eq!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(vec![0.0, 100.0, 150.0, 100.0]));
assert_eq!(crop_rect(&enter(&mut t, &cx)), Some(vec![0.0, 100.0, 150.0, 100.0]));
// The Control bar sets the box; it stays within the image.
t.set_option("rect", &json!([100, 120, 500, 20]));
assert_eq!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(vec![100.0, 120.0, 50.0, 20.0]));
assert_eq!(crop_rect(&enter(&mut t, &cx)), Some(vec![100.0, 120.0, 50.0, 20.0]));
// Nothing selected: no box, and the keys go elsewhere.
let none = Selection::default();
let cx = crate::testutil::cx(&d, &none, &p);
@@ -411,6 +570,196 @@ mod tests {
assert_eq!(tool.options()["rect"], json!([10.0, 20.0, 30.0, 40.0]));
}
/// The Control bar's fields: X and Y place the reference point, W and H resize about it, and
/// the link keeps the proportions.
#[test]
fn fields_move_and_resize_the_box_about_its_reference_point() {
let r = Rect::new(10.0, 20.0, 110.0, 70.0);
let big = Rect::new(0.0, 0.0, 1000.0, 1000.0);
// The center (the default): today's behavior.
assert_eq!(edited_box(r, big, CENTER, false, "x", 100.0), Some(Rect::new(50.0, 20.0, 150.0, 70.0)));
assert_eq!(edited_box(r, big, CENTER, false, "width", 50.0), Some(Rect::new(35.0, 20.0, 85.0, 70.0)));
// The top-left corner: X and Y name it, and a new size keeps it where it is.
assert_eq!(edited_box(r, big, 0, false, "x", 0.0), Some(Rect::new(0.0, 20.0, 100.0, 70.0)));
assert_eq!(edited_box(r, big, 0, false, "y", 5.0), Some(Rect::new(10.0, 5.0, 110.0, 55.0)));
assert_eq!(edited_box(r, big, 0, false, "height", 10.0), Some(Rect::new(10.0, 20.0, 110.0, 30.0)));
// The bottom-right corner keeps its place too.
assert_eq!(edited_box(r, big, 8, false, "width", 40.0), Some(Rect::new(70.0, 20.0, 110.0, 70.0)));
// Linked: the other side follows in proportion (100 × 50 → 40 × 20, then 60 × 30).
assert_eq!(edited_box(r, big, 0, true, "width", 40.0), Some(Rect::new(10.0, 20.0, 50.0, 40.0)));
assert_eq!(edited_box(r, big, 8, true, "height", 30.0), Some(Rect::new(50.0, 40.0, 110.0, 70.0)));
// A size below a point is raised to one; other keys and values that aren't finite change nothing.
assert_eq!(edited_box(r, big, 0, false, "width", -5.0), Some(Rect::new(10.0, 20.0, 11.0, 70.0)));
assert_eq!(edited_box(r, big, 0, false, "angle", 5.0), None);
assert_eq!(edited_box(r, big, 0, false, "x", f64::NAN), None);
// Within a 120 × 80 image: a linked size is held to the image with both sides scaled
// (200 × 100 → 120 × 60), and the box slides back within it, keeping its 2:1 proportions.
let image = Rect::new(0.0, 0.0, 120.0, 80.0);
assert_eq!(edited_box(r, image, 0, true, "width", 200.0), Some(Rect::new(0.0, 20.0, 120.0, 80.0)));
assert_eq!(edited_box(r, image, 0, true, "height", 70.0), Some(Rect::new(0.0, 20.0, 120.0, 80.0)));
// A move past the edge slides the box back without changing its size.
assert_eq!(edited_box(r, image, 0, false, "x", 50.0), Some(Rect::new(20.0, 20.0, 120.0, 70.0)));
// Unlinked, a side larger than the image is left for the box's own limit to cut.
assert_eq!(edited_box(r, image, 0, false, "width", 200.0), Some(Rect::new(10.0, 20.0, 210.0, 70.0)));
}
#[test]
fn reference_link_and_resolution_are_tool_options() {
let mut t = CropImageTool::default();
assert_eq!(t.options(), json!({ "reference": 4, "linked": false }));
t.set_option("reference", &json!(0));
t.set_option("linked", &json!(true));
t.set_option("ppi", &json!(150));
assert_eq!(t.options(), json!({ "reference": 0, "linked": true, "ppi": 150.0 }));
// Values that don't read put each back to its default.
for (k, v) in [("reference", json!(9)), ("linked", json!("yes")), ("ppi", json!(0)), ("ppi", json!(-72)), ("ppi", json!("high"))] {
t.set_option(k, &v);
}
assert_eq!(t.options(), json!({ "reference": 4, "linked": false }));
}
#[test]
fn option_values_are_checked_before_they_are_set() {
let values = |v: Value| v.as_object().cloned().unwrap();
assert_eq!(check_options(&values(json!({ "ppi": 150.5, "reference": 8, "linked": true, "rect": [0, 0, 1, 1] })), None), Ok(()));
assert_eq!(check_options(&values(json!({ "ppi": null })), Some(36.0)), Ok(()));
assert_eq!(check_options(&values(json!({ "ppi": 36 })), Some(36.0)), Ok(()));
for (v, want) in [
(json!({ "ppi": 0.5 }), "`ppi` must be a number from 1 to 2400 or null, not 0.5"),
(json!({ "ppi": 2401 }), "`ppi` must be a number from 1 to 2400 or null, not 2401"),
(json!({ "ppi": "high" }), "`ppi` must be a number from 1 to 2400 or null, not \"high\""),
(json!({ "ppi": 72 }), "`ppi` can't be more than 36 for this image"),
(json!({ "reference": 9 }), "`reference` must be a whole number from 0 to 8, not 9"),
(json!({ "reference": 1.5 }), "`reference` must be a whole number from 0 to 8, not 1.5"),
(json!({ "linked": "yes" }), "`linked` must be true or false, not \"yes\""),
] {
assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}");
}
}
/// An image's own resolution, and the most it can be cropped to.
#[test]
fn image_resolution_and_its_limit() {
let (d, s) = doc_with_image((50.0, 60.0));
let (id, _) = selected_image(&d, &s).unwrap();
let Some(NodeKind::Image(im)) = d.node(id).map(|n| n.kind.clone()) else { panic!("an image") };
// 100 px over 200 pt: half a pixel per point, 36 ppi.
assert_eq!(image_ppi(&im), (36.0, 36.0));
// Turned, it is the same image: 36 ppi, not the density across its bounding box.
let turned = ImageObject { xf: Affine::rotate(0.5) * im.xf, ..(*im).clone() };
assert!((image_ppi(&turned).0 - 36.0).abs() < 1e-9);
// Stretched to 3 pt a pixel across, its denser side counts.
let stretched = ImageObject { xf: Affine::scale_non_uniform(3.0, 2.0), ..(*im).clone() };
assert_eq!(image_ppi(&stretched).0, 36.0);
// Its own resolution keeps its pixels; pixels that are not square are resampled at any resolution.
assert!(keeps_resolution(&im, 36.0, 1e-6) && !keeps_resolution(&im, 18.0, 1e-6));
assert!(!keeps_resolution(&stretched, 36.0, 1e-6) && !keeps_resolution(&stretched, 24.0, 1e-6));
let linked = ImageObject { link: Some("photo.png".into()), ..*im };
assert_eq!(image_ppi(&linked), (36.0, LINKED_MAX_PPI));
}
/// Apply sends the chosen resolution with the box, even for a box over the whole image; the
/// image's own resolution sends nothing new, and one above the image's limit is held to it.
#[test]
fn apply_sends_the_chosen_resolution() {
let (d, s) = doc_with_image((50.0, 60.0));
let p = paint();
let cx = cx(&d, &s, &p);
let exec = |acts: &[Action]| {
acts.iter().find_map(|a| match a {
Action::Exec(c, v) if c == "object.cropImage" => Some(v.clone()),
_ => None,
})
};
let mut t = CropImageTool::default();
t.set_option("ppi", &json!(20));
assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [50.0, 60.0, 200.0, 100.0], "ppi": 20.0 })));
assert!(t.options().get("ppi").is_none(), "the next crop starts at the image's own");
t.set_option("ppi", &json!(36));
assert_eq!(exec(&enter(&mut t, &cx)), None, "the image's own over the whole image: nothing to do");
t.set_option("ppi", &json!(36));
t.set_option("rect", &json!([60, 70, 100, 50]));
assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] })));
// A resolution set before this image was selected is held to its limit: 300 → its own 36.
t.set_option("ppi", &json!(300));
t.set_option("rect", &json!([60, 70, 100, 50]));
assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] })));
t.set_option("ppi", &json!(300));
assert_eq!(exec(&enter(&mut t, &cx)), None, "held to its own over the whole image: nothing to do");
}
/// A turned image is drawn to be cropped, so Apply sends its own resolution too, the one the
/// PPI field shows, or the one chosen.
#[test]
fn apply_sends_a_turned_image_s_own_resolution() {
// Turned about the page's corner, it stays within the artboard.
let (mut d, s) = doc_with_image((150.0, 60.0));
let Some(id) = s.objects.first().copied() else { panic!("an image") };
if let Some(NodeKind::Image(im)) = d.node_mut(id).map(|n| &mut n.kind) {
im.xf = Affine::rotate(0.5) * im.xf;
}
let p = paint();
let cx = cx(&d, &s, &p);
let ppi = |acts: &[Action]| {
acts.iter().find_map(|a| match a {
Action::Exec(c, v) if c == "object.cropImage" => v.get("ppi").and_then(Value::as_f64),
_ => None,
})
};
let mut t = CropImageTool::default();
t.set_option("rect", &json!([150, 150, 20, 20]));
assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9));
t.set_option("rect", &json!([150, 150, 20, 20]));
t.set_option("ppi", &json!(36));
assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9));
// Over the whole box, Apply crops at a resolution chosen, and leaves it alone without one.
t.set_option("ppi", &json!(36));
assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9));
assert!(!enter(&mut t, &cx).iter().any(|a| matches!(a, Action::Exec(..))));
// A linked image's own resolution above what it can be cropped to is not sent in its place.
let Some(NodeKind::Image(im)) = d.node(id).map(|n| n.kind.clone()) else { panic!("an image") };
let mut linked = d.clone();
if let Some(NodeKind::Image(l)) = linked.node_mut(id).map(|n| &mut n.kind) {
l.link = Some("photo.png".into());
l.xf = im.xf * Affine::scale(0.1);
}
// 0.2 pt a pixel: 360 ppi, above the 300 a linked image is cropped to.
let cx = crate::testutil::cx(&linked, &s, &p);
t.set_option("rect", &json!([105, 128, 4, 4]));
assert_eq!(ppi(&enter(&mut t, &cx)), None);
}
/// A crop that fails leaves the tool chosen (the switch to the Selection tool is not made), so
/// the box and the resolution stay for another try; leaving the tool forgets them.
#[test]
fn the_box_and_resolution_stay_until_the_tool_is_left() {
let (d, s) = doc_with_image((50.0, 60.0));
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = CropImageTool::default();
t.set_option("ppi", &json!(20));
t.set_option("rect", &json!([60, 70, 100, 50]));
let acts = t.key(&cx, ToolKey::Enter, Mods::default());
assert_eq!(crop_rect(&acts), Some(vec![60.0, 70.0, 100.0, 50.0]));
assert_eq!(t.options()["rect"], json!([60.0, 70.0, 100.0, 50.0]));
assert_eq!(t.options()["ppi"], json!(20.0));
assert!(t.deactivate(&cx).is_empty());
assert!(t.options().get("rect").is_none() && t.options().get("ppi").is_none());
}
/// A linked size raised to the smallest box keeps the box's proportions: both sides grow
/// together until the shorter one is a point.
#[test]
fn a_linked_size_at_the_smallest_keeps_its_proportions() {
let big = Rect::new(0.0, 0.0, 1000.0, 1000.0);
let wide = Rect::new(10.0, 20.0, 110.0, 70.0);
assert_eq!(edited_box(wide, big, 0, true, "width", 1.0), Some(Rect::new(10.0, 20.0, 12.0, 21.0)));
assert_eq!(edited_box(wide, big, 0, true, "height", 0.25), Some(Rect::new(10.0, 20.0, 12.0, 21.0)));
let tall = Rect::new(10.0, 20.0, 60.0, 120.0);
assert_eq!(edited_box(tall, big, 0, true, "height", 1.0), Some(Rect::new(10.0, 20.0, 11.0, 22.0)));
assert_eq!(edited_box(tall, big, 0, true, "width", -3.0), Some(Rect::new(10.0, 20.0, 11.0, 22.0)));
}
#[test]
fn the_tool_is_made_by_its_id() {
assert_eq!(crate::create(ID).id(), ID);
+37 -12
View File
@@ -30,9 +30,11 @@
//! line to 45° steps from the canvas axes.
mod area;
mod line;
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_brush::{Calligraphic, Variation};
@@ -44,6 +46,7 @@ use super::{FEEDBACK, blob_area, blob_tip, eraser_tip, points_json, polyline};
use crate::guides::DrawSnap;
use crate::{Action, Cursor, Mods, Overlay, PenPose, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
use area::{AreaKey, AreaPreview};
use line::LinePreview;
/// How far from its drag the Smooth tool smooths, in screen pixels. Alt smoothing with the
/// Pencil, Paintbrush or Blob Brush uses the same radius.
@@ -217,6 +220,8 @@ pub struct GestureTool {
band: Cell<Option<SmoothBand>>,
/// The band last shown does not cover the whole drag yet; the next call adds to it.
band_pending: Cell<bool>,
/// The pieces of a long drag's line shown so far ([`LinePreview`]).
line: Cell<Option<LinePreview>>,
}
/// The band a smoothing drag smooths, for the drag's first `used` points at `radius`, kept as its
@@ -239,8 +244,8 @@ struct SmoothBand {
dirty_long: BTreeSet<usize>,
/// The band changed since `shown` was made.
changed: bool,
/// The outline last finished.
shown: Option<BezPath>,
/// The outline last finished, shared with the overlays that show it until it is made again.
shown: Option<Arc<BezPath>>,
/// The work done on long segments in the current call ([`BAND_WORK_PER_CALL`]).
work: usize,
}
@@ -496,7 +501,7 @@ impl SmoothBand {
/// The band's outline: the last one finished. While the band has changed since, the parts it
/// changed are made again, until [`BAND_WORK_PER_CALL`] is spent in the call; when all are
/// made, the outline is joined from them ([`SmoothBand::make_outline`]).
fn outline(&mut self) -> Option<BezPath> {
fn outline(&mut self) -> Option<Arc<BezPath>> {
while self.changed {
if !self.dirty_tiles.is_empty() || !self.dirty_long.is_empty() {
if self.work >= BAND_WORK_PER_CALL {
@@ -516,7 +521,7 @@ impl SmoothBand {
}
}
} else {
self.shown = Some(self.make_outline());
self.shown = Some(Arc::new(self.make_outline()));
self.changed = false;
}
}
@@ -903,6 +908,7 @@ impl GestureTool {
area_pending: Cell::new(false),
band: Cell::new(None),
band_pending: Cell::new(false),
line: Cell::new(None),
}
}
@@ -1154,6 +1160,7 @@ impl GestureTool {
self.area_pending.set(false);
self.band.set(None);
self.band_pending.set(false);
self.line.set(None);
}
/// The outline of the band a smoothing drag smooths: every point within `radius` of the drag,
@@ -1166,8 +1173,9 @@ impl GestureTool {
/// outside the squares, and one whose outlines cannot be combined adds nothing. Either way the
/// band goes on past it. The work on such long segments stops for the call once
/// [`BAND_WORK_PER_CALL`] is spent, and the drag is added to the band only once the outline of
/// what it holds is finished.
fn smooth_band(&self, radius: f64) -> Option<BezPath> {
/// what it holds is finished. The outline is the same shared path from one call to the next
/// until the band changes.
fn smooth_band(&self, radius: f64) -> Option<Arc<BezPath>> {
let pts = &self.points;
let &first = pts.first()?;
let mut b = self
@@ -1845,7 +1853,7 @@ impl Tool for GestureTool {
&& has_selected_smooth_path(cx)
&& let Some(path) = self.smooth_band(cx.tol(SMOOTH_RADIUS))
{
o.push(Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: true });
o.push(Overlay::SharedPath { path, color: FEEDBACK, width: 1.0, dash: Some(0.0) });
}
// A Blob Brush drag that smooths shows the Smooth tool's thin line.
let width = match self.id {
@@ -1878,17 +1886,34 @@ impl Tool for GestureTool {
let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }];
area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j)));
let paths = area.paths(&self.points);
o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 }));
o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0, dash: None }));
o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false }));
self.area_pending.set(area.pending(&self.points));
self.area.set(Some(area));
} else if size_varies {
// With Size on a mode that follows the pen, each step of the drag shows as wide as the
// tip the pen gives at its ends.
for (j, seg) in self.points.windows(2).enumerate() {
let width = (self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom;
o.push(Overlay::Path { path: polyline(seg), color, width: width as f32, dashed: false });
// tip the pen gives at its ends. A long drag's steps are kept from call to call
// ([`LinePreview::segments`]).
let width_of = |j: usize| ((self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom) as f32;
if self.points.len() > line::PIECE_SEGMENTS + 1 {
let mut kept = self.line.take().unwrap_or_default();
for (j, path) in kept.segments(&self.points).into_iter().enumerate() {
o.push(Overlay::SharedPath { path, color, width: width_of(j), dash: None });
}
self.line.set(Some(kept));
} else {
for (j, seg) in self.points.windows(2).enumerate() {
o.push(Overlay::Path { path: polyline(seg), color, width: width_of(j), dashed: false });
}
}
} else if self.points.len() > line::PIECE_SEGMENTS + 1 {
// A long drag's line shows in pieces kept from call to call ([`LinePreview::pieces`]).
let mut kept = self.line.take().unwrap_or_default();
let dashed = self.id == "knife";
for piece in kept.pieces(&self.points) {
o.push(Overlay::SharedPath { path: piece.path, color, width, dash: dashed.then_some(piece.along) });
}
self.line.set(Some(kept));
} else {
o.push(Overlay::Path { path: polyline(&self.points), color, width, dashed: self.id == "knife" });
}
+164
View File
@@ -0,0 +1,164 @@
//! The line a drag shows while it is dragged where it does not show the area its tip covers (a
//! round Eraser tip, the Knife, the Pencil with Live preview off, a smoothing drag), kept in
//! pieces that later calls return again unchanged.
//!
//! A drag of more than [`PIECE_SEGMENTS`] segments is cut into pieces of that many segments. A
//! piece ends halfway along the segment after its last point, where the next piece starts, so that
//! a wide line turns at a piece's last point as one line does and no part of the line is drawn
//! twice. A piece the drag has gone past is built once and returned again as the
//! same shared path; only the last piece is built again, and only when the drag changed it. With
//! Size on a mode that follows the pen each segment shows at its own width, so each segment is
//! kept as its own path, and only a segment whose ends moved is built again.
use std::sync::Arc;
use vectorcraft_geom::{BezPath, Point};
use super::super::polyline;
/// The segments of a drag from the first point of one piece of its line to the first point of the
/// next.
pub(super) const PIECE_SEGMENTS: usize = 64;
/// A piece of the line along the drag's points `from` to `to`: from point `from`, or halfway to the
/// point after it in a piece other than the first, and up to point `to`, or halfway to it in a
/// piece the drag has gone past.
struct Piece {
path: Arc<BezPath>,
from: usize,
to: usize,
/// The drag's point `to` when the piece was built.
end: Point,
/// The length of the line before the piece's first point.
along: f64,
/// The length of the piece.
length: f64,
}
/// A piece of the line to show ([`LinePreview::pieces`]).
pub(super) struct LinePiece {
/// The same shared path as in the call before while the piece did not change.
pub path: Arc<BezPath>,
/// The length of the line before the piece, where a dashed line's pattern goes on.
pub along: f64,
}
/// The pieces of a long drag's line, as far as they are built.
#[derive(Default)]
pub(super) struct LinePreview {
/// The pieces the drag has gone past, in order.
settled: Vec<Piece>,
/// The last piece, up to the drag's last point.
last: Option<Piece>,
/// Each segment of the drag as its own path, with the points it runs between.
segments: Vec<(Point, Point, Arc<BezPath>)>,
/// The points copied into new paths by the last call.
built: usize,
}
impl LinePreview {
/// The points copied into new paths by the last call.
#[cfg(test)]
pub(super) fn built(&self) -> usize {
self.built
}
/// The pieces of the line through `pts`: the pieces kept from the call before while the drag
/// still runs through their points, and new ones for the rest.
pub(super) fn pieces(&mut self, pts: &[Point]) -> Vec<LinePiece> {
self.built = 0;
// The drag no longer runs through the points of a kept piece (another drag, or a drag
// made again from its press).
let runs_through = |p: &Piece| pts.get(p.to) == Some(&p.end) && p.path.elements().first().and_then(|e| e.end_point()) == start(pts, p.from);
if let Some(k) = self.settled.iter().position(|p| !runs_through(p)) {
self.settled.truncate(k);
self.last = None;
}
// A piece settles once the drag has gone past its last point, which can still move. It
// then ends halfway along the segment after that point, so it is built again.
loop {
let from = self.settled.len() * PIECE_SEGMENTS;
let to = from + PIECE_SEGMENTS + 1;
if to + 1 >= pts.len() {
break;
}
let along = self.along_next();
let piece = self.build(pts, from, to, true, along);
self.settled.push(piece);
}
let from = self.settled.len() * PIECE_SEGMENTS;
let to = pts.len().saturating_sub(1);
if to > from {
let along = self.along_next();
// The last piece's points other than its last can change only with its last one, or
// with the drag's length.
let kept =
self.last.take().filter(|p| p.from == from && p.to == to && run(pts, from, to, false).is_some_and(|run| same_points(&p.path, run)));
self.last = Some(match kept {
Some(p) => p,
None => self.build(pts, from, to, false, along),
});
} else {
self.last = None;
}
self.settled.iter().chain(&self.last).map(|p| LinePiece { path: Arc::clone(&p.path), along: p.along }).collect()
}
/// Each segment of the line through `pts` as its own path: the same shared path as in the
/// call before while the segment's ends did not move.
pub(super) fn segments(&mut self, pts: &[Point]) -> Vec<Arc<BezPath>> {
self.built = 0;
let n = pts.len().saturating_sub(1);
self.segments.truncate(n);
let mut out = Vec::with_capacity(n);
for (j, w) in pts.windows(2).enumerate() {
match self.segments.get(j) {
Some((a, b, path)) if *a == w[0] && *b == w[1] => out.push(Arc::clone(path)),
_ => {
let path = Arc::new(polyline(w));
self.built += 2;
match self.segments.get_mut(j) {
Some(kept) => *kept = (w[0], w[1], Arc::clone(&path)),
None => self.segments.push((w[0], w[1], Arc::clone(&path))),
}
out.push(path);
}
}
}
out
}
/// The length of the line before the piece after the settled ones.
fn along_next(&self) -> f64 {
self.settled.last().map_or(0.0, |p| p.along + p.length)
}
/// The piece along the points `from` to `to` of `pts` ([`run`]), `along` the line.
fn build(&mut self, pts: &[Point], from: usize, to: usize, settled: bool, along: f64) -> Piece {
let points: Vec<Point> = run(pts, from, to, settled).map(Iterator::collect).unwrap_or_default();
self.built += points.len();
let length = points.windows(2).map(|w| w[0].distance(w[1])).sum();
Piece { path: Arc::new(polyline(&points)), from, to, end: pts.get(to).copied().unwrap_or_default(), along, length }
}
}
/// Where a piece from the point `from` of `pts` starts: at the point in the first piece, else
/// halfway to the point after it, where the piece before ends.
fn start(pts: &[Point], from: usize) -> Option<Point> {
if from == 0 { pts.first().copied() } else { Some(pts.get(from)?.midpoint(*pts.get(from + 1)?)) }
}
/// The points of the piece along the points `from` to `to` of `pts`: from its [`start`], through
/// the points after `from`, to point `to`, or, in a piece the drag has gone past (`settled`), to
/// halfway between the point before `to` and point `to`.
fn run(pts: &[Point], from: usize, to: usize, settled: bool) -> Option<impl Iterator<Item = Point> + '_> {
let first = start(pts, from)?;
let inner = pts.get(from + 1..if settled { to } else { to + 1 })?;
let last = if settled { Some(pts.get(to.checked_sub(1)?)?.midpoint(*pts.get(to)?)) } else { None };
Some(std::iter::once(first).chain(inner.iter().copied()).chain(last))
}
/// Does `path` run through exactly the points `pts`?
fn same_points(path: &BezPath, mut pts: impl Iterator<Item = Point>) -> bool {
path.elements().iter().all(|e| e.end_point().is_some() && e.end_point() == pts.next()) && pts.next().is_none()
}
+122 -3
View File
@@ -1195,7 +1195,14 @@ fn pencil_alt_smooths_within_the_smooth_tools_radius() {
/// The dashed paths among the overlays.
fn bands(t: &GestureTool, cx: &ToolContext) -> Vec<vectorcraft_geom::BezPath> {
t.overlays(cx).into_iter().filter_map(|o| if let Overlay::Path { path, dashed: true, .. } = o { Some(path) } else { None }).collect()
t.overlays(cx)
.into_iter()
.filter_map(|o| match o {
Overlay::Path { path, dashed: true, .. } => Some(path),
Overlay::SharedPath { path, dash: Some(_), .. } => Some((*path).clone()),
_ => None,
})
.collect()
}
/// How far `q` is from the polyline through `pts`.
@@ -1344,6 +1351,12 @@ fn smoothing_band_follows_a_long_drag() {
assert_eq!(frames, (n - 1).div_ceil(BAND_STEP * BAND_STEPS_PER_CALL), "frames for {n} points");
check_band(&t, &cx, cx.tol(12.0));
assert!(!t.overlays_pending());
// Once finished, the band shows as the same shared path each frame.
let band_of = |t: &GestureTool| {
t.overlays(&cx).into_iter().find_map(|o| if let Overlay::SharedPath { path, dash: Some(_), .. } = o { Some(path) } else { None })
};
let (a, b) = (band_of(&t), band_of(&t));
assert!(a.zip(b).is_some_and(|(a, b)| std::sync::Arc::ptr_eq(&a, &b)), "the band is not made again");
let last = pts[pts.len() - 1];
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, last.x, last.y));
// The next drag shows only its own band.
@@ -1623,7 +1636,7 @@ fn smoothing_drag_shows_no_band_without_a_path_it_smooths() {
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 400.0, 300.0));
let o = t.overlays(&cx);
assert!(!o.iter().any(|o| matches!(o, Overlay::Path { dashed: true, .. })), "{o:?}");
assert!(bands(&t, &cx).is_empty(), "{o:?}");
}
/// An Alt smoothing drag uses the Smooth tool's Fidelity for Pencil, Paintbrush and Blob Brush.
@@ -2500,7 +2513,7 @@ fn the_blob_brush_sends_its_tip_and_shows_the_area_it_covers() {
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0).with_mods(alt));
let o = t.overlays(&cx);
let [Overlay::Path { dashed: true, .. }, Overlay::Path { path, width, dashed: false, .. }] = &o[..] else { panic!("{o:?}") };
let [Overlay::SharedPath { dash: Some(_), .. }, Overlay::Path { path, width, dashed: false, .. }] = &o[..] else { panic!("{o:?}") };
assert_eq!(*width, 1.0);
assert!(vectorcraft_geom::Shape::bounding_box(path).height() < 0.1, "{o:?}");
}
@@ -2660,6 +2673,112 @@ fn the_settled_outline_of_a_long_drag_is_the_same_shared_path_each_frame() {
}
}
/// The points the last `overlays` call copied into new paths for a drag's line.
fn line_built(t: &GestureTool) -> usize {
let line = t.line.take();
let built = line.as_ref().map_or(0, |l| l.built());
t.line.set(line);
built
}
/// The points of piece `k` of the line of a drag through `pts`. A piece other than the first starts
/// halfway along the segment after its first point, and a piece other than the last (`settled`)
/// ends halfway along the segment after its last point, where the next piece starts.
fn piece_points(pts: &[Point], k: usize, settled: bool) -> Vec<Point> {
let from = k * line::PIECE_SEGMENTS;
let to = if settled { from + line::PIECE_SEGMENTS } else { pts.len() - 1 };
let mut want = vec![if k == 0 { pts[0] } else { pts[from].midpoint(pts[from + 1]) }];
want.extend_from_slice(&pts[from + 1..=to]);
if settled {
want.push(pts[to].midpoint(pts[to + 1]));
}
want
}
/// The line of a long round Eraser, Knife, Path Eraser or Pencil (Live preview off) drag shows in
/// pieces, and the steps of a round Eraser drag whose Size follows the pen each as its own path.
/// They come back from one call to the next, at any zoom, as the same shared paths, which the host
/// draws again without building them again; the call copies no point into a new path. A step of
/// the drag builds again only the last piece, or adds one step. The pieces run through every point
/// of the drag, each from where the one before ends, halfway along a segment, so no part of the
/// line is drawn twice, and the Knife's dashes go on from one piece to the next.
#[test]
fn the_line_of_a_long_drag_is_the_same_shared_pieces_each_frame() {
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.set([id]);
let p = paint();
let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
let shared = |o: &[Overlay]| -> Vec<(std::sync::Arc<BezPath>, f32, Option<f64>)> {
o.iter()
.filter_map(
|o| if let Overlay::SharedPath { path, width, dash, .. } = o { Some((std::sync::Arc::clone(path), *width, *dash)) } else { None },
)
.collect()
};
let points_of = |p: &BezPath| -> Vec<Point> { p.elements().iter().filter_map(|e| e.end_point()).collect() };
let n = 3000;
for (id, pressure) in [("eraser", false), ("knife", false), ("pathEraser", false), ("pencil", false), ("eraser", true)] {
let mut t = GestureTool::new(id);
t.set_option("size", &json!(10));
t.set_option("livePreview", &json!(false));
if pressure {
t.set_option("sizeMode", &json!("pressure"));
t.set_option("sizeVariation", &json!(4));
}
long_area_drag(&mut t, &cx, n, |i| if pressure { 0.3 + 0.6 * ((i % 50) as f32 / 50.0) } else { 1.0 });
let first = shared(&t.overlays(&cx));
assert!(t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Path { .. })), "{id}: no path of the drag is built for the call alone");
if pressure {
assert_eq!(first.len(), n - 1, "{id}: a path for each step");
for (j, (path, _, dash)) in first.iter().enumerate() {
assert_eq!(points_of(path), t.points[j..=j + 1], "{id}: step {j}");
assert_eq!(*dash, None);
}
} else {
assert!(first.len() > 1, "{id}: {} pieces", first.len());
let mut along = 0.0;
for (k, (path, width, dash)) in first.iter().enumerate() {
let got = points_of(path);
assert_eq!(got, piece_points(&t.points, k, k + 1 < first.len()), "{id}: piece {k}");
assert_eq!(*width, if id == "eraser" { 10.0 } else { 1.0 }, "{id}");
match dash {
Some(at) => assert!(id == "knife" && (at - along).abs() < 1e-6, "{id}: piece {k} dashes from {at}, not {along}"),
None => assert_ne!(id, "knife"),
}
along += got.windows(2).map(|w| w[0].distance(w[1])).sum::<f64>();
}
assert_eq!(first.len() - 1, (n - 3) / line::PIECE_SEGMENTS, "{id}: the last piece holds the points no settled piece holds");
}
for zoom in [1.0, 4.0, 1.0] {
let again = shared(&t.overlays(&ToolContext { zoom, ..cx }));
assert_eq!(line_built(&t), 0, "{id}: at zoom {zoom}, no point is copied into a new path");
assert_eq!(again.len(), first.len(), "{id}");
assert!(
again.iter().zip(&first).all(|(a, b)| std::sync::Arc::ptr_eq(&a.0, &b.0)),
"{id}: at zoom {zoom}, every path is the one shown before"
);
}
// One step more along the drag.
let s = n as f64;
let r = 150.0 + 100.0 * (s * 0.0071).sin();
let (x, y) = (300.0 + r * (s * 0.04).cos(), 300.0 + r * (s * 0.04).sin());
t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, x, y) });
let after = shared(&t.overlays(&cx));
let built = line_built(&t);
let kept = after.iter().filter(|a| first.iter().any(|f| std::sync::Arc::ptr_eq(&a.0, &f.0))).count();
if pressure {
assert_eq!((built, after.len(), kept), (2, n, n - 1), "{id}: one step added");
} else {
assert!(built <= line::PIECE_SEGMENTS + 2, "{id}: {built} points copied");
assert_eq!(kept, first.len() - 1, "{id}: only the last piece is built again");
}
let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y));
assert!(!acts.is_empty(), "{id}: the release still acts");
assert!(t.line.take().is_none(), "{id}: the release drops the pieces");
}
}
/// The outline a Blob Brush or Eraser drag shows does not change what its release sends: the same
/// drag sends the same command whether or not its outline was drawn along the way.
#[test]
+17
View File
@@ -421,6 +421,23 @@ impl DrawSnap {
self.guides.clear();
}
/// Snap to Tangent for a circle drawn around `center`, its radius `r` set by the pointer at `p`
/// through the dragged `corner` (where [`Self::drag`] put it): the radius, within the Smart
/// Guides snapping tolerance of `r`, at which the circle touches nearby art
/// ([`Targets::tangent_radius`]), its guides replacing the last snap's. None, the guides kept,
/// with Smart Guides or Snap to Tangent off, pixels or the grid snapping instead (each read
/// again on every move, as [`PointSnap::snap_from`] reads pixels and the grid), nothing in
/// reach, or an anchor, center or crossing in reach of `p` or at `corner`.
pub fn circle_radius(&mut self, cx: &ToolContext, center: Point, p: Point, corner: Point, r: f64) -> Option<f64> {
let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return None };
if !cx.smart_guides || !cx.snap_tangent || cx.snaps_to_pixel(*op) || cx.snap_to_grid {
return None;
}
let (radius, guides) = t.tangent_radius(center, p, corner, r, cx.tol(*tol))?;
self.guides = guides;
Some(radius)
}
/// Snap `p`, dragged since the press, with the targets the press gathered.
pub fn drag(&mut self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> Point {
if self.targets.is_none() {
+151
View File
@@ -107,6 +107,89 @@ pub(super) fn span(r: &Rect, x: bool) -> (f64, f64) {
if x { (r.x0, r.x1) } else { (r.y0, r.y1) }
}
/// Is `v` square to the direction `d` (both nonzero)?
fn square_to(v: Vec2, d: Vec2) -> bool {
let scale = v.hypot() * d.hypot();
scale > 1e-18 && v.dot(d).abs() <= 1e-9 * scale
}
/// Do the directions `a` and `b` (both nonzero) run the same way?
fn parallel(a: Vec2, b: Vec2) -> bool {
let scale = a.hypot() * b.hypot();
scale > 1e-18 && a.dot(b) > 0.0 && a.cross(b).abs() <= 1e-6 * scale
}
/// Does the curve `seg` run around `center` the whole way, as an arc of a circle about it drawn
/// with curves does: nearly square to the center all along, and its distance from the center
/// varying by no more than 0.03%? A circle drawn with four curves ([`vectorcraft_geom::shapes::ellipse`])
/// strays outward from its radius by up to 0.0273%, so an ellipse whose axes differ by less than
/// that cannot be told from one. A circle around the center then lies along the curve.
fn runs_round(seg: &PathSeg, center: Point) -> bool {
const SAMPLES: [f64; 9] = [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0];
if matches!(seg, PathSeg::Line(_)) {
return false;
}
let (mut lo, mut hi) = (f64::INFINITY, 0.0_f64);
for t in SAMPLES {
let (v, d) = (seg.eval(t) - center, seg_direction(seg, t));
if v.dot(d).abs() > 2e-3 * v.hypot() * d.hypot() {
return false;
}
(lo, hi) = (lo.min(v.hypot()), hi.max(v.hypot()));
}
hi - lo <= 3e-4 * hi
}
/// Whether a segment of `segs` other than the `i`th carries on past the end `at` of the `i`th
/// (its start when `at_start`) in the same direction: it has an end at `at` and runs away from
/// it the way the `i`th runs out through it, so the two join smoothly there rather than overlap.
fn continues_smoothly(segs: &[&PathSeg], i: usize, at: Point, at_start: bool) -> bool {
let Some(seg) = segs.get(i) else { return false };
let d = end_direction(seg, at_start);
let out = if at_start { -d } else { d };
let close = 1e-9 * (1.0 + at.x.abs().max(at.y.abs()));
segs.iter().enumerate().filter(|(j, _)| *j != i).any(|(_, s)| {
[(true, s.start()), (false, s.end())].into_iter().any(|(start, end)| {
let d = end_direction(s, start);
end.distance(at) <= close && parallel(if start { d } else { -d }, out)
})
})
}
/// The direction `seg` runs at its start (`at_start`) or its end. Where a curve's handle lies on
/// its anchor the derivative there is zero, so the direction is taken toward the next control
/// point that differs from the anchor, the direction the curve leaves the anchor in.
fn end_direction(seg: &PathSeg, at_start: bool) -> Vec2 {
let mut points: Vec<Point> = match seg {
PathSeg::Line(l) => vec![l.p0, l.p1],
PathSeg::Quad(q) => vec![q.p0, q.p1, q.p2],
PathSeg::Cubic(c) => vec![c.p0, c.p1, c.p2, c.p3],
};
if !at_start {
points.reverse();
}
let Some((&anchor, rest)) = points.split_first() else { return Vec2::ZERO };
let away = rest.iter().map(|q| *q - anchor).find(|v| v.hypot2() > 0.0).unwrap_or(Vec2::ZERO);
if at_start { away } else { -away }
}
/// The points inside `seg` where the line from `center` meets it square, where a circle round
/// `center` touches it, with the segment's direction there. A straight segment has at most one, its
/// foot of the perpendicular. On a curve, besides the sign changes [`touch_params`] finds, a sample
/// where the line is square exactly counts too: a center straight out from a symmetric curve's
/// middle meets it square at t = 0.5.
fn radial_touches(seg: &PathSeg, center: Point) -> Vec<(Point, Vec2)> {
/// The samples checked for an exact square meeting, as [`touch_params`] samples the curve.
const STEPS: u32 = 24;
if let PathSeg::Line(l) = seg {
let d = l.p1 - l.p0;
let t = (center - l.p0).dot(d) / d.hypot2();
return if t.is_finite() && t > 0.0 && t < 1.0 { vec![(l.p0 + d * t, d)] } else { vec![] };
}
let sampled = (1..STEPS).map(|i| f64::from(i) / f64::from(STEPS)).filter(|&t| square_to(seg.eval(t) - center, seg_direction(seg, t)));
sampled.chain(touch_params(seg, center, true)).map(|t| (seg.eval(t), seg_direction(seg, t))).collect()
}
/// Along axis `x`, does dragging `handle` move the box's minimum edge (true) or maximum (false)?
fn resize_moves_min_edge(handle: Handle, x: bool) -> Option<bool> {
let (ax, ay) = handle.axes();
@@ -778,6 +861,74 @@ impl Targets {
out
}
/// Snap to Tangent for a circle drawn around `center` with radius `r`: the radius nearest `r`,
/// within `tol` of it, at which the circle touches a target segment (where the line from
/// `center` meets the path square, at a point the path runs smoothly through), and the guides
/// showing it. None with an anchor, a center or a crossing within `tol` of the pointer `p`, or
/// at `corner`, where the drawn point snapped to: those win as they do for a drawn point. At
/// most 256 segments are measured, the ones nearest `p` when more cross the ring round
/// `center` at radius `r`.
pub(super) fn tangent_radius(&self, center: Point, p: Point, corner: Point, r: f64, tol: f64) -> Option<(f64, Vec<Overlay>)> {
/// How many segments one pointer move measures at most.
const MAX_SEGMENTS: usize = 256;
let finite = [center.x, center.y, p.x, p.y, corner.x, corner.y, r, tol].iter().all(|v| v.is_finite());
if !self.tangent || !finite || r < 0.0 || tol <= 0.0 {
return None;
}
if self.nearest_point(p, tol).is_some() || self.crossing(p, tol).is_some() {
return None;
}
// The corner snapped onto a point or a crossing: it lies on one, not merely near.
let on = |q: Point| q.distance(corner) <= 1e-9 * (1.0 + corner.x.abs().max(corner.y.abs()));
if self.nearest_point(corner, tol).is_some_and(|(q, _)| on(q)) || self.crossing(corner, tol).is_some_and(on) {
return None;
}
let (lo, hi) = (r - tol, r + tol);
// A segment can touch the circle only if part of its control bounds lies within the ring
// between `lo` and `hi` around the center.
let in_ring = |b: &Rect| {
let near = Point::new(center.x.clamp(b.x0, b.x1), center.y.clamp(b.y0, b.y1)).distance(center);
let far = (center.x - b.x0).abs().max((center.x - b.x1).abs()).hypot((center.y - b.y0).abs().max((center.y - b.y1).abs()));
near <= hi && far >= lo
};
let mut best: Option<(f64, Point, Vec2)> = None;
let mut offer = |q: Point, d: Vec2| {
let rho = q.distance(center);
if rho > tol && (rho - r).abs() <= tol && best.is_none_or(|(b, ..)| (rho - r).abs() < (b - r).abs()) {
best = Some((rho, q, d));
}
};
let mut ring: Vec<&(Rect, PathSeg)> = self.segments.iter().filter(|(b, _)| in_ring(b)).collect();
if ring.len() > MAX_SEGMENTS {
let from_p = |b: &Rect| Point::new(p.x.clamp(b.x0, b.x1), p.y.clamp(b.y0, b.y1)).distance(p);
ring.select_nth_unstable_by(MAX_SEGMENTS, |a, b| from_p(&a.0).total_cmp(&from_p(&b.0)));
ring.truncate(MAX_SEGMENTS);
}
let near: Vec<&PathSeg> = ring.into_iter().map(|(_, s)| s).collect();
for (i, seg) in near.iter().enumerate() {
// A circle around the same center lies along such a curve rather than touching it.
if runs_round(seg, center) {
continue;
}
for (q, d) in radial_touches(seg, center) {
offer(q, d);
}
// At an end square to the center the circle touches the path only where the next
// segment carries on in the same direction: at a corner or an open end it meets it.
// That segment ends on the circle too, so it is in the ring; when more than
// MAX_SEGMENTS segments are in the ring and it is not among those kept, the end is not
// offered.
for (at_start, end) in [(true, seg.start()), (false, seg.end())] {
let d = end_direction(seg, at_start);
if square_to(end - center, d) && continues_smoothly(&near, i, end, at_start) {
offer(end, d);
}
}
}
let (rho, q, d) = best?;
Some((rho, self.touch_guides(center, q, false, d, tol)))
}
/// The segment extension nearest `p`, within `tol` of it (and `p` farther than that from the
/// end it starts at): that end, its direction and where `p` lands on it. Where `p` is nearer
/// the horizontal or the vertical through that end there is none: lining up with it ("align")
+7 -4
View File
@@ -73,10 +73,13 @@ pub enum Overlay {
SelectionMarquee { rect: Rect, enclosed: bool, pointer: Point },
/// A path preview (e.g. pen rubber band) in a colour (RGB).
Path { path: BezPath, color: [u8; 3], width: f32, dashed: bool },
/// A solid path preview that later calls return again, as the same shared `path`, for as long
/// as it does not change (the settled outline of a long Blob Brush or Eraser drag). The host
/// can keep what it built to draw it while `path` is the same allocation.
SharedPath { path: std::sync::Arc<BezPath>, color: [u8; 3], width: f32 },
/// A path preview that later calls return again, as the same shared `path`, for as long as it
/// does not change (the settled outline of a long Blob Brush or Eraser drag, the pieces of a long
/// drag's line). The host can keep what it built to draw it while `path` is the same allocation.
/// With `dash`, it is dashed as a dashed [`Overlay::Path`] is, from `dash` document units along
/// the dash pattern: the pieces of one line, each starting where the one before it ends, dash
/// as the whole line does.
SharedPath { path: std::sync::Arc<BezPath>, color: [u8; 3], width: f32, dash: Option<f64> },
/// A line segment (smart guide, handle line).
Line { a: Point, b: Point, color: [u8; 3], dashed: bool },
/// An anchor square: filled = selected.
+48 -2
View File
@@ -15,6 +15,10 @@
//! box's eight handles scales the selection, a press on the selection's centre point (Show Center)
//! moves it, and one just outside a corner of its box turns it about that centre, as the Selection
//! tool's handles, centre point and rotate zone do; a press anywhere else draws a new shape (#5477).
//!
//! With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift)
//! takes the radius at which it touches a nearby path whenever its radius comes within the
//! snapping tolerance of it ([`DrawSnap::circle_radius`]).
use serde_json::{Value, json};
use vectorcraft_doc::OrientedBox;
@@ -92,6 +96,10 @@ pub struct ShapeTool {
pub star_ratio: f64,
/// The star's inner radius held while Ctrl/Cmd is down in a drag.
inner: Option<f64>,
/// Where the last drag put the dragged corner of a circle drawn from its center, from the
/// center, when Snap to Tangent sized it ([`Self::tangent_circle`]); none when the pointer
/// sized it. Space moving the circle moves the corner it was drawn with there and clears it.
tangent_corner: Option<Vec2>,
/// Line Segment Tool Options: the length and angle (degrees) a click's dialog opens with, and
/// Fill Line (new lines take the current fill).
pub line_length: f64,
@@ -153,6 +161,7 @@ impl ShapeTool {
corner_radius: 12.0,
star_ratio: 0.5,
inner: None,
tangent_corner: None,
snap: DrawSnap::default(),
line_length: 100.0,
line_angle: 0.0,
@@ -418,6 +427,27 @@ impl ShapeTool {
}
}
/// Snap to Tangent for a circle drawn from its center `s` (the Ellipse tool with Alt and
/// Shift): the dragged corner `p` moved toward or away from `s` so that the circle touches a
/// nearby path, when its radius is within the snapping tolerance of a touching one
/// ([`DrawSnap::circle_radius`]); `raw` is the pointer before snapping. The radius is measured
/// along the Constrain Angle's axes, as the drawn box is ([`turned_box`]). None for any other
/// shape or modifiers, or with `p` on `s`.
fn tangent_circle(&mut self, cx: &ToolContext, s: Point, raw: Point, p: Point, m: Mods) -> Option<Point> {
if self.id != "ellipse" || !(m.alt && m.shift) || m.space {
return None;
}
let axes = vectorcraft_geom::constrain_axes(cx.constrain_angle).unwrap_or(Affine::IDENTITY);
let back = axes.inverse();
let (c, d) = (back * s, back * p - back * s);
let r = d.x.abs().max(d.y.abs());
if r.is_nan() || r <= 0.0 {
return None;
}
let radius = self.snap.circle_radius(cx, s, raw, p, r)?;
Some(axes * (c + d * (radius / r)))
}
/// The command for a drag from `start` to `p` (snapped: a line's end already keeps Shift's
/// angle).
pub fn command(&self, start: Point, p: Point, m: Mods) -> (String, Value) {
@@ -560,6 +590,7 @@ impl Tool for ShapeTool {
}
PointerKind::Drag => {
let Some(mut s) = self.start else { return vec![] };
let raw = ev.pos;
let pos = self.snap.drag(cx, ev.pos, self.leave(cx, s, ev.mods).as_ref());
let ev = &PointerEvent { pos, ..*ev };
// The inner radius of the star the last drag showed, with the ratio it drew with:
@@ -567,15 +598,28 @@ impl Tool for ShapeTool {
// first arrives with the next position.
let ratio = if self.mods.alt { straight_ratio(self.points).unwrap_or(self.star_ratio) } else { self.star_ratio };
let shown = (self.last - s).hypot() * ratio;
// Space moves a circle Snap to Tangent sized from the corner it was drawn with, so
// it keeps that size while it moves and after Space is let go.
if ev.mods.space
&& self.began
&& let Some(d) = self.tangent_corner.take()
{
self.last = s + d;
}
space_moves(&mut s, &mut self.last, ev, self.began);
self.start = Some(s);
self.mods = ev.mods;
if self.id == "star" {
self.hold_inner(shown, s, ev.pos, ev.mods);
}
// A circle from its center takes a radius that touches a nearby path. Whether the
// drag has begun is judged before that snap.
let dragged = ev.pos;
self.tangent_corner = self.tangent_circle(cx, s, raw, ev.pos, ev.mods).map(|q| q - s);
let ev = &PointerEvent { pos: self.tangent_corner.map_or(ev.pos, |d| s + d), ..*ev };
let mut out = vec![];
if !self.began {
if ev.pos.distance(s) < cx.tol(2.0) {
if dragged.distance(s) < cx.tol(2.0) {
return out;
}
self.began = true;
@@ -733,7 +777,9 @@ impl Tool for ShapeTool {
let (w, h) = match self.id {
"polygon" => ((self.last - s).x.abs(), (self.last - s).y.abs()),
_ => {
let (r, _) = turned_box(s, self.last, self.mods, cx.constrain_angle);
// The corner Snap to Tangent moved a circle's to, as the preview draws it.
let corner = self.tangent_corner.map_or(self.last, |d| s + d);
let (r, _) = turned_box(s, corner, self.mods, cx.constrain_angle);
(r.width(), r.height())
}
};
+350
View File
@@ -196,6 +196,356 @@ fn shift_square_alt_center() {
assert_eq!(v, json!({"x": -10.0, "y": -10.0, "width": 20.0, "height": 20.0}));
}
/// A 500 × 500 document holding `paths`.
fn doc_holding_paths(paths: impl IntoIterator<Item = vectorcraft_geom::PathData>) -> vectorcraft_doc::Document {
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
let l = d.layers[0].id;
for (i, path) in paths.into_iter().enumerate() {
let id = d.alloc_id();
d.insert(Some(l), i, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap();
}
d
}
/// The box of the last preview of a drag: x, y, width, height.
fn previewed_box(a: &[Action]) -> [f64; 4] {
let Some(Action::Preview(_, v)) = a.last() else { panic!("no preview: {a:?}") };
["x", "y", "width", "height"].map(|k| v[k].as_f64().unwrap_or(f64::NAN))
}
/// An Alt+Shift drag with the Ellipse tool from `center` to `to`: the circle's box as previewed,
/// and the overlays it shows.
fn circle_drag(c: &ToolContext, center: Point, to: Point) -> ([f64; 4], Vec<Overlay>) {
let both = Mods { alt: true, shift: true, ..Mods::default() };
let mut t = ShapeTool::new("ellipse");
t.pointer(c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(both));
let a = t.pointer(c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both));
(previewed_box(&a), t.overlays(c))
}
fn tangent_label_at(o: &[Overlay], at: Point, within: f64) -> bool {
o.iter().any(|o| matches!(o, Overlay::Label { text, p, .. } if text == "tangent" && p.distance(at) <= within))
}
/// Snap to Tangent: a circle drawn from its center takes the radius at which it touches a nearby
/// straight path, with the "tangent" label at the touch point, also when the touch point is the
/// middle of the segment; the size label gives the circle as drawn.
#[test]
fn a_circle_from_its_center_snaps_its_radius_to_touch_a_line() {
// The line's ends and middle line up with none of the corners below.
let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]);
let (s, p) = (Selection::default(), paint());
let c = ToolContext { measurement_labels: true, ..cx(&d, &s, &p) };
// The pointer makes the radius 98; the line is 100 below the center.
let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(203.0, 102.0));
assert_eq!(b, [100.0, 100.0, 200.0, 200.0]);
assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}");
assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.size_label(200.0, 200.0))), "{o:?}");
// From the other side of the touching radius too (102).
let (b, _) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(205.0, 98.0));
assert_eq!(b, [100.0, 100.0, 200.0, 200.0]);
// Space moves the snapped circle and keeps its size.
let both = Mods { alt: true, shift: true, ..Mods::default() };
let mut t = ShapeTool::new("ellipse");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(both));
t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 203.0, 102.0).with_mods(both));
// Space pressed with the pointer still moves the circle by no more than the snap moved its
// corner.
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 203.0, 102.0).with_mods(Mods { space: true, ..both }));
let b = previewed_box(&a);
assert!(b[2] == 200.0 && b[3] == 200.0 && (b[0] - 100.0).abs() <= 4.0 && (b[1] - 100.0).abs() <= 4.0, "{b:?}");
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 253.0, 152.0).with_mods(Mods { space: true, ..both }));
let b = previewed_box(&a);
assert!(b[2] == 200.0 && b[3] == 200.0 && (b[0], b[1]) != (100.0, 100.0), "moved, same size: {b:?}");
assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.size_label(200.0, 200.0))));
// Letting go of Space where the moved circle no longer touches the line keeps its size, and
// moving on grows it from there.
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 253.0, 152.0).with_mods(both));
assert_eq!(previewed_box(&a), b, "Space let go");
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 243.0, 142.0).with_mods(both));
let (grown, moved) = (previewed_box(&a), Point::new(b[0] + 100.0, b[1] + 100.0));
let radius = (243.0 - moved.x).abs().max((142.0 - moved.y).abs());
assert!(grown[2] == 2.0 * radius && grown[3] == 2.0 * radius && radius > 105.0, "{grown:?} from {moved:?}");
// Out of reach (radius 90): the pointer sizes it.
let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(203.0, 110.0));
assert_eq!(b, [110.0, 110.0, 180.0, 180.0]);
assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}");
}
/// A circle drawn around a center outside another circle touches it from outside at the nearer
/// side and takes it inside at the farther side, the radii those of the closed form (the distance
/// between the centers less or plus the other radius) within the error of the curves that draw a
/// circle. A center inside a circle gives the inscribed circle; its touch point is an anchor of
/// the circle, where two segments join smoothly. A center at the circle's own center gets no snap:
/// every point is square to it.
#[test]
fn a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside() {
use vectorcraft_geom::shapes::ellipse;
// A circle of radius 50 around (350, 300), its center 50√13 from (200, 200).
let d = doc_holding_paths([ellipse(Rect::new(300.0, 250.0, 400.0, 350.0))]);
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let (center, between) = (Point::new(200.0, 200.0), 50.0 * 13f64.sqrt());
let toward = Vec2::new(150.0, 100.0) / between;
for (radius, pointer) in [(between - 50.0, Vec2::new(20.0, -(between - 52.0))), (between + 50.0, Vec2::new(-20.0, between + 48.0))] {
let (b, o) = circle_drag(&c, center, center + pointer);
assert!((b[2] / 2.0 - radius).abs() < 0.02 && b[2] == b[3], "{b:?}, want radius {radius}");
assert!(tangent_label_at(&o, center + toward * radius, 0.2), "{o:?}");
}
// Concentric: no tangent snap.
let (_, o) = circle_drag(&c, Point::new(350.0, 300.0), Point::new(374.0, 252.0));
assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}");
// Ellipses with radii 10010 and 10000, or 1001 and 1000, around the center are nearly square
// to it all round, but they are not circles: a circle touches each at the ends of its axes.
for (rx, ry) in [(10_010.0, 10_000.0), (1001.0, 1000.0)] {
let d = doc_holding_paths([ellipse(Rect::new(250.0 - rx, 250.0 - ry, 250.0 + rx, 250.0 + ry))]);
let c = cx(&d, &s, &p);
let (_, o) = circle_drag(&c, Point::new(250.0, 250.0), Point::new(280.0, 252.0 - ry));
assert!(tangent_label_at(&o, Point::new(250.0, 250.0 - ry), 1e-6), "{rx} × {ry}: {o:?}");
}
let near = |b: [f64; 4], want: [f64; 4]| b.iter().zip(want).all(|(a, w)| (a - w).abs() < 1e-6);
// Inside a circle of radius 150 around (250, 250), 50 from its center: the inscribed circle has
// radius 100.
let d = doc_holding_paths([ellipse(Rect::new(100.0, 100.0, 400.0, 400.0))]);
let c = cx(&d, &s, &p);
let (b, o) = circle_drag(&c, Point::new(200.0, 250.0), Point::new(203.0, 152.0));
assert!(near(b, [100.0, 150.0, 200.0, 200.0]), "{b:?}");
assert!(tangent_label_at(&o, Point::new(100.0, 250.0), 1e-6), "{o:?}");
}
/// The touch point can fall inside a curved segment: the radius is the distance to the nearest
/// point of the curve, measured here by sampling the path's own segments densely.
#[test]
fn a_circle_from_its_center_snaps_to_touch_a_curve() {
use vectorcraft_geom::ParamCurve;
let path = vectorcraft_geom::shapes::ellipse(Rect::new(300.0, 100.0, 500.0, 200.0));
let center = Point::new(250.0, 300.0);
let sp = &path.subpaths[0];
let (want, at) = (0..sp.segment_count())
.flat_map(|i| (0..=20_000).map(move |k| (i, f64::from(k) / 20_000.0)))
.map(|(i, t)| sp.segment(i).eval(t))
.map(|q| (q.distance(center), q))
.min_by(|a, b| a.0.total_cmp(&b.0))
.unwrap();
let d = doc_holding_paths([path]);
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let r = want - 2.0;
let (b, o) = circle_drag(&c, center, center + Vec2::new(-r * 0.3, r));
assert!((b[2] / 2.0 - want).abs() < 1e-4 && (b[3] / 2.0 - want).abs() < 1e-4, "radius {} want {want}", b[2] / 2.0);
assert!(tangent_label_at(&o, at, 1e-2), "{at:?} {o:?}");
// Straight out from a symmetric curve's middle (t = 0.5, (200, 262.5)), 162.5 from (200, 100).
let mut bump = vectorcraft_geom::BezPath::new();
bump.move_to((100.0, 300.0));
bump.curve_to((150.0, 250.0), (250.0, 250.0), (300.0, 300.0));
let d = doc_holding_paths([vectorcraft_geom::PathData::from_bezpath(&bump)]);
let c = cx(&d, &s, &p);
let (b, o) = circle_drag(&c, Point::new(200.0, 100.0), Point::new(40.0, 40.0));
assert!((b[2] - 325.0).abs() < 1e-9 && (b[3] - 325.0).abs() < 1e-9, "{b:?}");
assert!(tangent_label_at(&o, Point::new(200.0, 262.5), 1e-9), "{o:?}");
}
/// The snap is Snap to Tangent's, under Smart Guides: off, the pointer sizes the circle. An
/// ellipse (no Shift) and a box drawn from a corner (no Alt) do not snap. An open path's end and
/// a corner square to the center are where a circle meets the path rather than touches it, so
/// neither is offered.
#[test]
fn a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch() {
let line = vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0));
let d = doc_holding_paths([line]);
let (s, p) = (Selection::default(), paint());
// The pointer makes the radius 98, 2 short of touching the line.
let (center, to) = (Point::new(200.0, 200.0), Point::new(215.0, 102.0));
for off in [ToolContext { snap_tangent: false, ..cx(&d, &s, &p) }, ToolContext { smart_guides: false, ..cx(&d, &s, &p) }] {
assert_eq!(circle_drag(&off, center, to).0, [102.0, 102.0, 196.0, 196.0]);
}
let c = cx(&d, &s, &p);
assert_eq!(circle_drag(&c, center, to).0, [100.0, 100.0, 200.0, 200.0], "on, it snaps");
for (mods, want) in
[(Mods { alt: true, ..Mods::default() }, [185.0, 102.0, 30.0, 196.0]), (Mods { shift: true, ..Mods::default() }, [200.0, 102.0, 98.0, 98.0])]
{
let mut t = ShapeTool::new("ellipse");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(mods));
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(mods));
assert_eq!(previewed_box(&a), want, "{mods:?}");
}
// The line's left end is square below (60, 200), but it is an open end, also with a second
// line starting there the same way, which overlaps it rather than carrying it on.
assert_eq!(circle_drag(&c, Point::new(60.0, 200.0), Point::new(63.0, 102.0)).0, [-38.0, 102.0, 196.0, 196.0]);
let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1));
let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((60.0, 300.0), (200.0, 300.0))]);
let c = cx(&d, &s, &p);
assert_eq!(circle_drag(&c, Point::new(60.0, 200.0), Point::new(63.0, 102.0)).0, [-38.0, 102.0, 196.0, 196.0]);
// Two lines end to end in one direction meet smoothly under (200, 200): the circle touches there.
let d = doc_holding_paths([line((60.0, 300.0), (200.0, 300.0)), line((200.0, 300.0), (380.0, 300.0))]);
let c = cx(&d, &s, &p);
assert_eq!(circle_drag(&c, center, to).0, [100.0, 100.0, 200.0, 200.0]);
// A rectangle's corner (200, 200) is 100√2 from (300, 300), diagonal to both its sides.
let (d, _) = doc_with_rect();
let c = cx(&d, &s, &p);
let r = 100.0 * 2f64.sqrt() - 2.0;
let (b, _) = circle_drag(&c, Point::new(300.0, 300.0), Point::new(300.0 + r, 300.0 + r * 0.5));
assert!((b[2] - 2.0 * r).abs() < 1e-9, "{b:?}");
}
/// An anchor the dragged corner snapped to wins over the tangent radius, as it does for a drawn
/// point. With more segments near the radius than one move measures, the ones nearest the pointer
/// are measured.
#[test]
fn a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer() {
let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1));
let (s, p) = (Selection::default(), paint());
let center = Point::new(200.0, 200.0);
// Shift keeps the corner on the diagonal, and it slides onto the anchor (297, 103): radius 97.
let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((297.0, 103.0), (297.0, 40.0))]);
let c = cx(&d, &s, &p);
let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0));
assert_eq!(b, [103.0, 103.0, 194.0, 194.0]);
assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}");
// A corner that only lines up with an anchor near it, (300, 104), still takes the tangent.
let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((300.0, 104.0), (300.0, 40.0))]);
let c = cx(&d, &s, &p);
let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0));
assert_eq!(b, [100.0, 100.0, 200.0, 200.0]);
assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}");
// 300 short segments pointing at the center cross the ring above it, ahead of the line below.
let spokes = (0..300).map(|i| {
let a = (-55.0 + 110.0 * f64::from(i) / 299.0_f64).to_radians();
let at = |r: f64| (200.0 + r * a.sin(), 200.0 - r * a.cos());
line(at(95.0), at(105.0))
});
let d = doc_holding_paths(spokes.chain([line((60.0, 300.0), (380.0, 300.0))]));
let c = cx(&d, &s, &p);
// The press lines up with a spoke's anchor, so the center moves by less than a point.
let (b, o) = circle_drag(&c, center, Point::new(215.0, 298.0));
assert!((b[2] - 200.0).abs() < 1e-9 && (b[3] - 200.0).abs() < 1e-9 && (b[1] - 100.0).abs() < 1e-9, "{b:?}");
assert!(o.iter().any(|o| matches!(o, Overlay::Label { text, p, .. } if text == "tangent" && (p.y - 300.0).abs() < 1e-9)), "{o:?}");
}
/// With a Constrain Angle the radius is measured, and the snapped box rebuilt, along the turned
/// axes: the circle still touches the line.
#[test]
fn a_circle_snapped_to_touch_keeps_to_the_constrain_angle() {
let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(0.0, 300.0), Point::new(450.0, 300.0))]);
let (s, p) = (Selection::default(), paint());
let c = ToolContext { constrain_angle: 30.0, ..cx(&d, &s, &p) };
let axes = vectorcraft_geom::constrain_axes(30.0).unwrap();
let center = Point::new(200.0, 200.0);
let both = Mods { alt: true, shift: true, ..Mods::default() };
let mut t = ShapeTool::new("ellipse");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(both));
let to = center + (axes * Point::new(-40.0, -97.0)).to_vec2();
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both));
let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") };
let (w, h) = (v["width"].as_f64().unwrap(), v["height"].as_f64().unwrap());
assert!((w - 200.0).abs() < 1e-9 && (h - 200.0).abs() < 1e-9, "{v}");
assert!((v["rotation"].as_f64().unwrap() + 30.0).abs() < 1e-9, "{v}");
let mid = Point::new(v["x"].as_f64().unwrap() + w / 2.0, v["y"].as_f64().unwrap() + h / 2.0);
assert!(mid.distance(center) < 1e-9, "centered on the press: {mid:?}");
// Space pressed with the pointer still keeps the size and moves the circle by no more than
// the snap moved its corner.
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { space: true, ..both }));
let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") };
let (w, h) = (v["width"].as_f64().unwrap(), v["height"].as_f64().unwrap());
assert!((w - 200.0).abs() < 1e-9 && (h - 200.0).abs() < 1e-9, "{v}");
let mid = Point::new(v["x"].as_f64().unwrap() + w / 2.0, v["y"].as_f64().unwrap() + h / 2.0);
assert!(mid.distance(center) <= 4.0, "{mid:?}");
}
/// Snap to Grid and pixel snapping place the drawn point instead of the tangent snap, also when
/// one is turned on while the circle is dragged out. Snap to Tangent turned off while dragging
/// stops the snap.
#[test]
fn a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels() {
let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]);
let (s, p) = (Selection::default(), paint());
let on = cx(&d, &s, &p);
let grid = ToolContext { snap_to_grid: true, ..cx(&d, &s, &p) };
let pixels = ToolContext { snap_to_pixel: true, pixel_snap: crate::PixelSnap { drawing: true, ..on.pixel_snap }, ..cx(&d, &s, &p) };
let no_tangent = ToolContext { snap_tangent: false, ..cx(&d, &s, &p) };
let both = Mods { alt: true, shift: true, ..Mods::default() };
let drag = |press: &ToolContext, moved: &ToolContext, to: Point| {
let mut t = ShapeTool::new("ellipse");
t.pointer(press, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(both));
let a = t.pointer(moved, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both));
(previewed_box(&a), t.overlays(moved))
};
let tangent = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent"));
// The pointer makes the radius 98: the snap would make it 100.
let to = Point::new(203.0, 102.0);
assert_eq!(drag(&on, &on, to).0, [100.0, 100.0, 200.0, 200.0], "the snap applies");
// Pixels round (203.2, 102.2) to (203, 102): radius 98.
let to = Point::new(203.2, 102.2);
for (press, moved) in [(&pixels, &pixels), (&on, &pixels)] {
let (b, o) = drag(press, moved, to);
assert_eq!(b, [102.0, 102.0, 196.0, 196.0]);
assert!(!tangent(&o), "{o:?}");
}
// The grid (every 9 points) puts the corner on (207, 99): radius 101 from (200, 200), or 99
// from (198, 198), where the grid puts a press made with it on.
for (press, moved, want) in [(&grid, &grid, [99.0, 99.0, 198.0, 198.0]), (&on, &grid, [99.0, 99.0, 202.0, 202.0])] {
let (b, o) = drag(press, moved, to);
assert_eq!(b, want);
assert!(!tangent(&o), "{o:?}");
}
let (b, o) = drag(&on, &no_tangent, Point::new(203.0, 102.0));
assert_eq!(b, [102.0, 102.0, 196.0, 196.0]);
assert!(!tangent(&o), "{o:?}");
}
/// A press and a small jitter is a click, not a drag, even when the tangent snap would size the
/// circle at the jittered pointer large enough to begin a drag.
#[test]
fn a_jittered_alt_shift_press_beside_a_path_is_a_click() {
// With a Constrain Angle, Shift does not hold the corner on the page's diagonal, which would
// take it onto the line.
let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]);
let (s, p) = (Selection::default(), paint());
let c = ToolContext { constrain_angle: 30.0, ..cx(&d, &s, &p) };
let both = Mods { alt: true, shift: true, ..Mods::default() };
let mut t = ShapeTool::new("ellipse");
// 5.5 above the line, beyond the snapping tolerance of 4. The jitter of 1.9 makes the radius
// 1.9 cos 30°, about 1.65, within 4 of the touching radius 5.5.
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 294.5).with_mods(both));
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 201.9, 294.5).with_mods(both)), vec![]);
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 201.9, 294.5).with_mods(both));
assert!(!a.contains(&Action::Commit), "{a:?}");
}
/// An anchor or a crossing within the snapping tolerance of the pointer takes the point, and the
/// circle is not sized to touch the line.
#[test]
fn a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer() {
let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1));
let (s, p) = (Selection::default(), paint());
let center = Point::new(200.0, 200.0);
let base = line((60.0, 300.0), (380.0, 300.0));
// An anchor at (205, 104), and two lines crossing there.
for extra in [vec![line((205.0, 104.0), (260.0, 40.0))], vec![line((185.0, 84.0), (225.0, 124.0)), line((185.0, 124.0), (225.0, 84.0))]] {
let d = doc_holding_paths(std::iter::once(base.clone()).chain(extra));
let c = cx(&d, &s, &p);
let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0));
assert!(b[2] != 200.0, "{b:?}");
assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}");
}
}
/// A path whose anchor below the center joins two straight curves with their handles drawn back
/// onto that anchor runs smoothly through it: the circle touches it there.
#[test]
fn a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles() {
let mut run = vectorcraft_geom::BezPath::new();
run.move_to((60.0, 300.0));
run.curve_to((100.0, 300.0), (200.0, 300.0), (200.0, 300.0));
run.curve_to((200.0, 300.0), (300.0, 300.0), (380.0, 300.0));
let d = doc_holding_paths([vectorcraft_geom::PathData::from_bezpath(&run)]);
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(215.0, 102.0));
assert_eq!(b, [100.0, 100.0, 200.0, 200.0]);
assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}");
}
/// General › Constrain Angle: a Shift-drag squares along the turned axes, and the shape turns
/// by the angle about its centre.
#[test]
+72 -7
View File
@@ -395,20 +395,76 @@ struct SharedKey {
/// The painter's clip: the lines of the path outside it have no triangles in the mesh.
clip: egui::Rect,
stroke: Stroke,
/// Where the dash pattern starts along the path, in document units, when it is dashed.
dash: Option<f64>,
pixels_per_point: f32,
tessellation: TessellationOptions,
}
/// The length of a dash of a dashed overlay, in screen pixels.
const DASH: f32 = 4.0;
/// The length of the gap after each dash of a dashed overlay, in screen pixels.
const GAP: f32 = 3.0;
/// Add to `out` the dashes of `line` drawn with `s`, [`DASH`] pixels drawn and [`GAP`] left out,
/// with the pattern started `from` pixels along it: from 0, the dashes [`Shape::dashed_line`] gives.
pub(super) fn dashes_from(line: &[Pos2], s: Stroke, from: f64, out: &mut Vec<Shape>) {
let period = f64::from(DASH + GAP);
let phase = from.rem_euclid(period);
let phase = if phase.is_finite() { phase as f32 } else { 0.0 };
if line.len() < 2 {
return;
}
if phase >= DASH {
Shape::dashed_line_many_with_offset(line, s, &[DASH], &[GAP], DASH + GAP - phase, out);
return;
}
// The pattern starts within a dash: the rest of that dash is drawn, then the pattern goes on
// after its gap.
let mut left = DASH - phase;
for (i, w) in line.windows(2).enumerate() {
let len = (w[1] - w[0]).length();
if len >= left {
let cut = w[0] + (w[1] - w[0]) * (left / len);
let mut dash = line[..=i].to_vec();
dash.push(cut);
segments(&dash, s, out);
let mut rest = vec![cut];
rest.extend_from_slice(&line[i + 1..]);
Shape::dashed_line_many_with_offset(&rest, s, &[DASH], &[GAP], GAP, out);
return;
}
left -= len;
}
segments(line, s, out);
}
/// Add to `out` each line of `line` that has a length as its own [`Shape::LineSegment`], as
/// [`Shape::dashed_line`] draws a dash.
fn segments(line: &[Pos2], s: Stroke, out: &mut Vec<Shape>) {
out.extend(line.windows(2).filter(|w| w[0] != w[1]).map(|w| Shape::line_segment([w[0], w[1]], s)));
}
impl SharedPaths {
/// The mesh that draws `path` with `s` at the view `xf` with the painter `p`: the one kept in
/// this frame or in `last` (the last frame's) when it was built for the same, else a new one.
/// It is kept for the next frame.
fn mesh(&mut self, last: &mut HashMap<usize, SharedMesh>, path: &Arc<BezPath>, xf: &Xf, s: Stroke, p: &egui::Painter) -> Arc<Mesh> {
/// The mesh that draws `path` with `s`, dashed from `dash` document units along the pattern
/// when that is set, at the view `xf` with the painter `p`: the one kept in this frame or in
/// `last` (the last frame's) when it was built for the same, else a new one. It is kept for
/// the next frame.
fn mesh(
&mut self,
last: &mut HashMap<usize, SharedMesh>,
path: &Arc<BezPath>,
xf: &Xf,
s: Stroke,
dash: Option<f64>,
p: &egui::Painter,
) -> Arc<Mesh> {
let ctx = p.ctx();
let key = SharedKey {
view: xf.affine().as_coeffs(),
clip: p.clip_rect(),
stroke: s,
dash,
pixels_per_point: ctx.pixels_per_point(),
tessellation: ctx.tessellation_options(|o| *o),
};
@@ -425,7 +481,16 @@ impl SharedPaths {
tessellator.set_clip_rect(key.clip);
let mut mesh = Mesh::default();
for line in to_screen_path(path, xf) {
tessellator.tessellate_shape(Shape::line(line, s), &mut mesh);
match dash {
Some(from) => {
let mut dashes = vec![];
dashes_from(&line, s, from * xf.zoom, &mut dashes);
for d in dashes {
tessellator.tessellate_shape(d, &mut mesh);
}
}
None => tessellator.tessellate_shape(Shape::line(line, s), &mut mesh),
}
}
SharedMesh { path: Arc::clone(path), key, mesh: Arc::new(mesh) }
}
@@ -476,8 +541,8 @@ pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t:
stroke_path(p, path, xf, s);
}
}
Overlay::SharedPath { path, color, width } => {
let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), p);
Overlay::SharedPath { path, color, width, dash } => {
let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), *dash, p);
if !mesh.is_empty() {
p.add(Shape::mesh(mesh));
}
+67 -1
View File
@@ -99,7 +99,8 @@ fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() {
path.line_to((250.0, 160.0));
let a = std::sync::Arc::new(path.clone());
let b = std::sync::Arc::new(path.clone());
let shared_of = |p: &std::sync::Arc<BezPath>| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0 };
let shared_of =
|p: &std::sync::Arc<BezPath>| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0, dash: None };
let first = one(frame(&[shared_of(&a)], 1.0, &mut shared));
assert!(!first.vertices.is_empty());
let again = one(frame(&[shared_of(&a)], 1.0, &mut shared));
@@ -143,6 +144,71 @@ fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() {
half.line_to((5100.0, 5000.0));
let half = one(frame(&[shared_of(&std::sync::Arc::new(half))], 1.0, &mut shared));
assert_eq!(*half, *first, "the subpath off the canvas adds no triangles");
// A dashed shared path keeps its mesh too, and the place its dashes start is part of it.
let dashed_of = |p: &std::sync::Arc<BezPath>, dash: f64| Overlay::SharedPath {
path: std::sync::Arc::clone(p),
color: [0x80, 0x80, 0x80],
width: 1.0,
dash: Some(dash),
};
let dashed = one(frame(&[dashed_of(&a, 0.0)], 1.0, &mut shared));
assert!(!dashed.vertices.is_empty() && *dashed != *first, "the dashes leave out parts of the line");
assert!(std::sync::Arc::ptr_eq(&dashed, &one(frame(&[dashed_of(&a, 0.0)], 1.0, &mut shared))));
let moved = one(frame(&[dashed_of(&a, 2.0)], 1.0, &mut shared));
assert!(!std::sync::Arc::ptr_eq(&dashed, &moved) && *dashed != *moved, "dashes that start elsewhere build a new mesh");
}
/// A line drawn dashed in pieces, each piece's dashes starting as far along the pattern as the
/// pieces before it are long, shows the dashes the whole line shows dashed in one go, whether a
/// piece starts within a dash or within a gap, and a pattern started at 0 gives the dashes of
/// [`Shape::dashed_line`].
#[test]
fn a_line_dashed_in_pieces_dashes_as_the_whole_line_does() {
// The stretches of x that dashes along the x axis cover, with touching ones joined.
let covered = |shapes: &[Shape]| -> Vec<(f32, f32)> {
let mut spans: Vec<(f32, f32)> = shapes
.iter()
.map(|s| {
let xs: Vec<f32> = match s {
Shape::LineSegment { points, .. } => points.iter().map(|p| p.x).collect(),
Shape::Path(p) => p.points.iter().map(|p| p.x).collect(),
other => panic!("{other:?}"),
};
(xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max))
})
.collect();
spans.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut joined: Vec<(f32, f32)> = vec![];
for (a, b) in spans {
match joined.last_mut() {
Some(last) if a - last.1 < 1e-3 => last.1 = last.1.max(b),
_ => joined.push((a, b)),
}
}
joined
};
let s = Stroke::new(1.0, Color32::WHITE);
let along = |xs: &[f32]| -> Vec<Pos2> { xs.iter().map(|&x| pos2(x, 10.0)).collect() };
let whole = along(&[0.0, 30.0, 61.5, 100.0]);
let mut one_go = vec![];
overlays::dashes_from(&whole, s, 0.0, &mut one_go);
assert_eq!(covered(&one_go), covered(&Shape::dashed_line(&whole, s, 4.0, 3.0)));
// Cuts at 50 (within a dash: 50 is 1 past the dash that starts at 49) and at 75 (within a gap).
let mut pieces = vec![];
overlays::dashes_from(&along(&[0.0, 30.0, 50.0]), s, 0.0, &mut pieces);
overlays::dashes_from(&along(&[50.0, 61.5, 75.0]), s, 50.0, &mut pieces);
overlays::dashes_from(&along(&[75.0, 100.0]), s, 75.0, &mut pieces);
let (want, got) = (covered(&one_go), covered(&pieces));
assert_eq!(want.len(), got.len(), "{want:?} {got:?}");
assert!(want.iter().zip(&got).all(|(w, g)| (w.0 - g.0).abs() < 1e-3 && (w.1 - g.1).abs() < 1e-3), "{want:?} {got:?}");
// Every dash is drawn as line segments with a length, as `Shape::dashed_line` draws them: the
// cut first dash, a dash cut on a vertex (at 4) and a line shorter than the rest of a dash too.
let mut ends = vec![];
overlays::dashes_from(&along(&[0.0, 4.0, 10.0]), s, 0.0, &mut ends);
overlays::dashes_from(&along(&[0.0, 1.0, 2.0]), s, 1.0, &mut ends);
for shape in one_go.iter().chain(&pieces).chain(&ends) {
assert!(matches!(shape, Shape::LineSegment { points: [a, b], .. } if a != b), "{shape:?}");
}
}
#[test]
+1 -1
View File
@@ -3292,7 +3292,7 @@ fn the_control_bar_s_controls_stay_inside_the_bar_in_a_narrow_window() {
wide(&mut app, "an embedded image", &["Unembed…", "Image Trace", "Mask", "Crop Image", "Remove Background"]);
app.select_tool(vectorcraft_tools::cropimage::ID);
check(&mut app, "Crop Image");
wide(&mut app, "Crop Image", &["X:", "Y:", "W:"]);
wide(&mut app, "Crop Image", &["PPI", "X:", "Y:", "W:", "H:"]);
app.select_tool("selection");
app.run("imageTrace.make", json!({"preset": "Default"})).unwrap();
let trace = selected(&app);
+5 -1
View File
@@ -655,7 +655,8 @@ pub(crate) fn parent(d: &Dialog) -> Option<Dialog> {
/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change
/// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in
/// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor
/// Artwork's `group` selects that color group and its `groupAction` runs the button at once.
/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. A value
/// Composite Fonts' Show Sample can't take is refused.
pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> {
if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) {
transform_each::field_set(app, field, old);
@@ -664,6 +665,9 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu
if app.ui.dialog.as_ref().is_some_and(|d| d.kind == recolor::KIND) {
return recolor::field_set(app, field);
}
if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) {
return composite_fonts::field_set(d, field);
}
let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) };
match field {
"exportPreset" => export_for_screens::preset_set(app),
File diff suppressed because it is too large Load Diff
+30 -4
View File
@@ -5,14 +5,17 @@
//! out, Import… adds the fonts of a file and Export… writes the one picked to a file. Custom shows
//! the custom character sets of the font picked: New adds a set based on the one picked, Delete Set
//! takes it out, and Add puts the characters typed (Direct Entry) or the character of a Unicode code
//! into it; Delete takes the character picked out. Nothing changes in the document until OK, which
//! into it; Delete takes the character picked out. Show Sample draws a sample of the font picked
//! with lines that mark its metrics ([`sample`]). Nothing changes in the document until OK, which
//! runs `type.compositeFonts.set` with every font as one undo step; Cancel leaves them as they were.
//!
//! Fields: `fonts` (the composite fonts as `type.compositeFonts.set` takes them), `selected` (the
//! index of the one picked) and `name` (its name as typed); `custom` (whether the custom character
//! sets show), `set` (the index of the set picked), `setName` (its name as typed), `entryMode`
//! (`direct` or `unicode`), `entry` (the characters or code typed) and `char` (the index of the
//! character picked in the set).
//! character picked in the set); `sample` (whether the sample shows), `zoom` (its magnification in
//! percent) and `lineIcfBox`, `lineEmBox`, `lineBaseline`, `lineCapHeight`, `lineAscentDescent`,
//! `lineAscender` and `lineXHeight` (whether each of its lines shows).
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
@@ -29,6 +32,8 @@ use crate::picks::PickRequest;
use crate::state::Dialog;
use crate::{FilePick, VectorcraftApp, widgets};
mod sample;
/// The dialog kind of Composite Fonts.
pub const KIND: &str = "compositeFonts";
@@ -53,15 +58,22 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
};
/// Open Composite Fonts on the active document's composite fonts, the first one picked, with the
/// custom character sets hidden and nothing typed.
/// custom character sets and the sample hidden and nothing typed.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec();
let mut d = Dialog::new(KIND, json!({ "fonts": fonts, "selected": 0, "custom": false, "entryMode": "direct", "entry": "" }));
sample::defaults(&mut d.fields);
show_selected(&mut d);
app.ui.dialog = Some(d);
Ok(Value::Null)
}
/// Why `ui.dialog.set` can't set `field` of Composite Fonts `d` to the value it now holds (Show
/// Sample's fields, [`sample::check_field`]).
pub(super) fn field_set(d: &Dialog, field: &str) -> Result<(), String> {
sample::check_field(d, field)
}
/// The fonts the dialog holds.
fn fonts(d: &Dialog) -> Vec<CompositeFont> {
d.fields.get("fonts").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default()
@@ -138,6 +150,8 @@ enum Action {
Export,
/// Custom: show or hide the custom character sets.
Custom,
/// Show Sample or Hide Sample.
Sample,
NewSet,
DeleteSet,
/// Add the characters typed, or the character of the code typed, to the set picked.
@@ -178,6 +192,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, tl!("Custom"), 64.0)).inner.clicked() {
act = Some(Action::Custom);
}
let label = if d.bool("sample") { tl!("Hide Sample") } else { tl!("Show Sample") };
if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, label, 96.0)).inner.clicked() {
act = Some(Action::Sample);
}
});
if let Some(k) = picked {
select(d, k);
@@ -192,6 +210,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
f.name = d.str("name");
ui.add_space(8.0);
parts_table(app, ui, f);
if d.bool("sample") {
ui.add_space(8.0);
sample::show(ui, d, f);
}
if d.bool("custom") {
ui.add_space(8.0);
ui.separator();
@@ -319,6 +341,10 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action) -> Result<(), Stri
let open = !d.bool("custom");
d.fields.insert("custom".into(), json!(open));
}
Action::Sample => {
let open = !d.bool("sample");
d.fields.insert("sample".into(), json!(open));
}
Action::NewSet | Action::DeleteSet | Action::AddChars | Action::DeleteChar => {
let f = list.get_mut(i).ok_or("no composite font")?;
let at = edit_sets(d, f, act)?;
@@ -389,7 +415,7 @@ fn edit_sets(d: &mut Dialog, f: &mut CompositeFont, act: Action) -> Result<Optio
d.fields.remove("char");
Ok(None)
}
Action::New | Action::Delete | Action::Import | Action::Export | Action::Custom => Ok(None),
Action::New | Action::Delete | Action::Import | Action::Export | Action::Custom | Action::Sample => Ok(None),
}
}
@@ -0,0 +1,384 @@
//! Show Sample in Composite Fonts: the font picked set in a line of sample text, with lines that
//! mark its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest
//! ascender and x-height, each shown or hidden by its button, at the size Zoom picks.
//!
//! The sample text, the zoom steps, the size at 100% and what each line measures are VectorCraft's
//! own: the em box and ICF box are those of the face of the part that sets the sample's first Kanji
//! (the Kanji part, or a custom set that holds that character)
//! ([`vectorcraft_text::FontFace::ideographic_centre`], [`vectorcraft_text::FontFace::icf_margins`]),
//! the cap height and x-height those of the face the Roman letters are drawn in, Max Ascent/Descent
//! the highest ascent and lowest descent among the faces the sample is drawn in (fallback faces
//! included), and Max Ascender the top of the sample's tallest glyph. Each takes its part's size,
//! baseline and vertical scale.
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352>,
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
use std::hash::{DefaultHasher, Hash, Hasher};
use egui::{Color32, Rect, Sense, Stroke, Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_doc::{CharClass, CharStyle, CompositeClass, CompositeFont, FontHeightReference, TextObject};
use vectorcraft_geom::kurbo::BezPath;
use vectorcraft_geom::{Affine, Point};
use vectorcraft_text::FontDb;
use crate::state::Dialog;
use crate::widgets;
/// The text the sample sets: two Kanji, two kana, two punctuation marks, a symbol, Roman letters
/// with an ascender and a descender, and two numerals, then the first character of each custom set.
pub(super) const TEXT: &str = "永国あア、。※Agh12";
/// The Zoom menu's magnifications, in percent.
pub(super) const ZOOMS: [u64; 7] = [25, 50, 75, 100, 200, 400, 800];
/// The size the sample is set at with Zoom at 100%, in points.
const SIZE: f64 = 36.0;
/// How tall the sample is drawn, in points.
const HEIGHT: f32 = 150.0;
/// How far the sample text starts from the left edge, in points.
const INSET: f64 = 12.0;
/// The width of the column of line buttons and Zoom beside the sample, in points.
const BUTTONS: f32 = 190.0;
/// The narrowest and widest the sample is drawn, in points.
const WIDTH: std::ops::RangeInclusive<f32> = 240.0..=720.0;
/// The name the sample lends the font under, so a name that is empty, being typed or shared with
/// another font still draws.
const NAME: &str = "VectorCraft Composite Sample";
/// A line Show Sample can mark.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Mark {
IcfBox,
EmBox,
Baseline,
CapHeight,
AscentDescent,
Ascender,
XHeight,
}
impl Mark {
/// The marks, in the order their buttons show.
pub(super) const ALL: [Self; 7] =
[Self::IcfBox, Self::EmBox, Self::Baseline, Self::CapHeight, Self::AscentDescent, Self::Ascender, Self::XHeight];
/// The dialog field that holds whether the mark shows.
pub(super) fn field(self) -> &'static str {
match self {
Self::IcfBox => "lineIcfBox",
Self::EmBox => "lineEmBox",
Self::Baseline => "lineBaseline",
Self::CapHeight => "lineCapHeight",
Self::AscentDescent => "lineAscentDescent",
Self::Ascender => "lineAscender",
Self::XHeight => "lineXHeight",
}
}
fn label(self) -> &'static str {
match self {
Self::IcfBox => tl!("ICF Box"),
Self::EmBox => tl!("Em Box"),
Self::Baseline => tl!("Baseline"),
Self::CapHeight => tl!("Cap Height"),
Self::AscentDescent => tl!("Max Ascent/Descent"),
Self::Ascender => tl!("Max Ascender"),
Self::XHeight => tl!("x-height"),
}
}
/// Shown when the dialog opens: the em box, the ICF box and the baseline.
pub(super) fn shown_at_first(self) -> bool {
matches!(self, Self::IcfBox | Self::EmBox | Self::Baseline)
}
fn color(self) -> Color32 {
match self {
Self::IcfBox => Color32::from_rgb(0, 150, 170),
Self::EmBox => Color32::from_rgb(220, 60, 60),
Self::Baseline => Color32::from_rgb(40, 110, 230),
Self::CapHeight => Color32::from_rgb(40, 160, 70),
Self::AscentDescent => Color32::from_rgb(230, 140, 30),
Self::Ascender => Color32::from_rgb(150, 80, 200),
Self::XHeight => Color32::from_rgb(200, 60, 160),
}
}
}
/// The fields Show Sample adds to the dialog when it opens: hidden, at 100%, with the marks of
/// [`Mark::shown_at_first`].
pub(super) fn defaults(fields: &mut serde_json::Map<String, Value>) {
fields.insert("sample".into(), json!(false));
fields.insert("zoom".into(), json!(100));
for m in Mark::ALL {
fields.insert(m.field().into(), json!(m.shown_at_first()));
}
}
/// Why `ui.dialog.set` can't set Show Sample's `field` to the value `d` now holds: `sample` and the
/// marks take true or false, and `zoom` one of [`ZOOMS`].
pub(super) fn check_field(d: &Dialog, field: &str) -> Result<(), String> {
let v = d.fields.get(field);
let key = field;
if field == "sample" || Mark::ALL.iter().any(|m| m.field() == field) {
if !v.is_some_and(Value::is_boolean) {
return Err(format!("`{key}` must be true or false"));
}
} else if field == "zoom" && !v.and_then(Value::as_u64).is_some_and(|z| ZOOMS.contains(&z)) {
return Err(format!("`{key}` must be one of {}", ZOOMS.map(|z| z.to_string()).join(", ")));
}
Ok(())
}
/// The Zoom `d` holds, 100 when it holds none of [`ZOOMS`].
fn zoom(d: &Dialog) -> u64 {
d.fields.get("zoom").and_then(Value::as_u64).filter(|z| ZOOMS.contains(z)).unwrap_or(100)
}
/// The heights the marks are drawn at, in points above the baseline (a mark's line is not drawn
/// when its height is `None`). The baseline is at 0.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct Heights {
/// The em box's bottom and top.
pub em_box: Option<(f64, f64)>,
/// The ICF box's bottom and top.
pub icf_box: Option<(f64, f64)>,
pub cap_height: Option<f64>,
pub x_height: Option<f64>,
/// The lowest descent and the highest ascent.
pub ascent_descent: Option<(f64, f64)>,
/// The top of the tallest glyph.
pub ascender: Option<f64>,
}
impl Heights {
/// The heights of mark `m`.
fn of(&self, m: Mark) -> Vec<f64> {
let pair = |p: Option<(f64, f64)>| p.map_or_else(Vec::new, |(a, b)| vec![a, b]);
match m {
Mark::IcfBox => pair(self.icf_box),
Mark::EmBox => pair(self.em_box),
Mark::Baseline => vec![0.0],
Mark::CapHeight => self.cap_height.into_iter().collect(),
Mark::AscentDescent => pair(self.ascent_descent),
Mark::Ascender => self.ascender.into_iter().collect(),
Mark::XHeight => self.x_height.into_iter().collect(),
}
}
}
/// `f` as the sample sets it: named [`NAME`], without its custom sets when one of them can't be
/// used (a set whose name is empty or shared while it is typed).
fn sample_font(f: &CompositeFont) -> CompositeFont {
let mut s = f.clone();
s.name = NAME.to_string();
if s.check().is_err() {
s.custom.clear();
}
s
}
/// [`TEXT`], then the first character of each of `f`'s custom sets that it does not hold yet.
pub(super) fn text(f: &CompositeFont) -> String {
let mut t = TEXT.to_string();
for c in f.custom.iter().filter_map(|s| s.characters.chars().next()) {
if !t.contains(c) {
t.push(c);
}
}
t
}
/// The outlines of the sample of `f` set at `size` points with its baseline at y 0 (y down), and
/// the heights of its marks.
pub(super) fn measure(f: &CompositeFont, size: f64) -> (BezPath, Heights) {
let db = FontDb::global();
let font = sample_font(f);
let _lent = db.lend_composite_fonts(std::slice::from_ref(&font));
let text = text(&font);
let style = CharStyle { font_family: NAME.to_string(), size, ..Default::default() };
let layout = vectorcraft_text::layout(db, &TextObject::point(Point::ZERO, &text, style));
let path = layout.to_bezpath();
let classes = font.classes();
// The face of character `c`'s part, the face layout draws it in (a fallback face when the part's
// font lacks it), the size of its em and the shift of its baseline (points), and its part's
// vertical scale, as layout sets them: Kana scaled at center keep the middle of their part's em
// box where it is.
let placed = |c: char| {
let (part_face, _) = db.composite_resolve(NAME, c)?;
let drawn = text.find(c).and_then(|at| layout.glyphs.iter().find(|g| g.byte == at)).and_then(|g| db.face_by_id(g.font_id));
let class = classes.of(c);
let p = font.part(class).unwrap_or(&font.parts.kanji);
let em = size * p.size / 100.0;
let mut shift = size * p.baseline / 100.0;
if class == CompositeClass::Fixed(CharClass::Kana) && p.scale_at_center && p.v_scale != 100.0 {
shift += em * part_face.ideographic_centre() * (1.0 - p.v_scale / 100.0);
}
let drawn = drawn.unwrap_or_else(|| part_face.clone());
Some((part_face, drawn, em, shift, p.v_scale / 100.0))
};
let mut h = Heights::default();
// The em box and ICF box are those of the part that sets the sample's first Kanji (the Kanji
// part, or a custom set that holds that character), as layout measures that part's face for
// Scale at Center.
if let Some((face, _, em, shift, v)) = TEXT.chars().next().and_then(placed) {
let tall = em * v;
let mid = shift + face.ideographic_centre() * tall;
let (bottom, top) = (mid - tall * 0.5, mid + tall * 0.5);
let m = face.icf_margins();
h.em_box = Some((bottom, top));
h.icf_box = Some((bottom + m.bottom * tall, top - m.top * tall));
}
if let Some((_, face, em, shift, v)) = placed('A') {
let height = |r| face.font_height(r, false);
let cap = height(FontHeightReference::CapHeight).unwrap_or_else(|| face.cap_height() / face.units_per_em());
h.cap_height = Some(shift + cap * em * v);
let x = height(FontHeightReference::XHeight).unwrap_or_else(|| face.x_height() / face.units_per_em());
h.x_height = Some(shift + x * em * v);
}
let mut seen = Vec::new();
for c in text.chars().filter(|c| !c.is_whitespace()) {
let Some((_, face, em, shift, v)) = placed(c) else { continue };
if seen.contains(&(face.id(), em.to_bits(), shift.to_bits(), v.to_bits())) {
continue;
}
seen.push((face.id(), em.to_bits(), shift.to_bits(), v.to_bits()));
let (ascent, descent) = face.vertical_metrics();
let scale = em * v / face.units_per_em();
let (low, high) = (shift - descent * scale, shift + ascent * scale);
h.ascent_descent = Some(h.ascent_descent.map_or((low, high), |(l, t)| (l.min(low), t.max(high))));
}
// Outlines, color glyphs and bitmap glyphs alike.
h.ascender = layout.ink_bounds().filter(|ink| ink.height() > 0.0).map(|ink| -ink.y0);
(path, h)
}
/// The sample drawn for a key, kept until the font, zoom, size, display scale, text color or the
/// fonts installed change.
struct Drawn {
key: u64,
texture: Option<egui::TextureHandle>,
heights: Heights,
}
thread_local! {
static DRAWN: crate::graphics::TexCache<Option<Drawn>> = crate::graphics::TexCache::default();
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new());
}
/// Show Sample's area under the table: the sample of `f` with its marks, then the mark buttons and
/// Zoom beside it.
pub(super) fn show(ui: &mut Ui, d: &mut Dialog, f: &CompositeFont) {
let zoom = zoom(d);
ui.horizontal(|ui| {
let width = (ui.available_width() - BUTTONS).clamp(*WIDTH.start(), *WIDTH.end());
let (rect, _) = ui.allocate_exact_size(vec2(width, HEIGHT), Sense::hover());
paint(ui, rect, d, f, zoom);
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
for m in Mark::ALL {
let on = d.bool(m.field());
ui.horizontal(|ui| {
let (swatch, _) = ui.allocate_exact_size(vec2(10.0, 10.0), Sense::hover());
ui.painter().rect_filled(swatch, 1.0, m.color());
if ui.add(egui::Button::selectable(on, m.label())).clicked() {
d.fields.insert(m.field().into(), json!(!on));
}
});
}
ui.add_space(4.0);
ui.horizontal(|ui| {
widgets::dim_label(ui, tl!("Zoom"));
let names: Vec<String> = ZOOMS.iter().map(|z| format!("{z}%")).collect();
let options: Vec<&str> = names.iter().map(String::as_str).collect();
let current = format!("{zoom}%");
if let Some(k) = widgets::dropdown(ui, "composite-fonts-zoom", &current, &options, 80.0)
&& let Some(z) = ZOOMS.get(k)
{
d.fields.insert("zoom".into(), json!(z));
}
});
});
});
}
/// Draw the sample of `f` at `zoom` percent into `rect`, its em box centered in it, with the marks
/// `d` shows.
fn paint(ui: &Ui, rect: Rect, d: &Dialog, f: &CompositeFont, zoom: u64) {
let painter = ui.painter_at(rect);
let visuals = ui.visuals();
painter.rect_filled(rect, 2.0, visuals.extreme_bg_color);
let ppp = ui.ctx().pixels_per_point();
let ink = visuals.text_color();
let mut h = DefaultHasher::new();
serde_json::to_string(f).unwrap_or_default().hash(&mut h);
(zoom, ppp.to_bits(), rect.width().to_bits(), rect.height().to_bits(), ink.to_array(), FontDb::global().generation()).hash(&mut h);
let key = h.finish();
let size = SIZE * zoom as f64 / 100.0;
let (texture, heights) = DRAWN.with(|cache| {
let mut cache = cache.borrow_mut();
if let Some(drawn) = cache.as_ref().filter(|c| c.key == key) {
return (drawn.texture.clone(), drawn.heights);
}
let (_, heights) = measure(f, size);
let texture = render(ui.ctx(), f, size, baseline(&heights, size, rect), rect, ppp, ink);
*cache = Some(Drawn { key, texture: texture.clone(), heights });
(texture, heights)
});
if let Some(t) = &texture {
painter.image(t.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
}
let base = rect.top() + baseline(&heights, size, rect) as f32;
for m in Mark::ALL.into_iter().filter(|m| d.bool(m.field())) {
for y in heights.of(m) {
painter.hline(rect.x_range(), base - y as f32, Stroke::new(1.0, m.color()));
}
}
painter.rect_stroke(rect, 2.0, visuals.widgets.noninteractive.bg_stroke, egui::StrokeKind::Inside);
}
/// Where the baseline goes, in points down from the top of `rect`: the em box's middle (else
/// 0.38 em above the baseline) at the middle of `rect`.
fn baseline(h: &Heights, size: f64, rect: Rect) -> f64 {
let mid = h.em_box.map_or(size * 0.38, |(bottom, top)| (bottom + top) * 0.5);
f64::from(rect.height()) * 0.5 + mid
}
/// The sample of `f` drawn into a texture the size of `rect` in pixels ([`draw`]). `None` when
/// `rect` is empty or larger than the largest texture.
fn render(ctx: &egui::Context, f: &CompositeFont, size: f64, baseline: f64, rect: Rect, ppp: f32, ink: Color32) -> Option<egui::TextureHandle> {
let (w, h) = ((rect.width() * ppp).round(), (rect.height() * ppp).round());
let max = ctx.input(|i| i.max_texture_side) as f32;
if w < 1.0 || h < 1.0 || w > max || h > max || w > f32::from(u16::MAX) || h > f32::from(u16::MAX) {
return None;
}
let image = draw(f, size, baseline, (w as u16, h as u16), ppp, ink);
Some(ctx.load_texture("composite-font-sample", crate::canvas::color_image_owned(image), egui::TextureOptions::LINEAR))
}
/// The sample of `f` set at `size` points in `ink`, its baseline `baseline` points down from the
/// top, drawn by the renderer as the canvas draws type (color and bitmap glyphs in their own
/// colors) into `px` pixels at `ppp` pixels per point.
pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered {
let (w, h) = px;
let mut doc = vectorcraft_doc::Document::new(f64::from(w) / f64::from(ppp), f64::from(h) / f64::from(ppp));
let font = sample_font(f);
let sample = text(&font);
*doc.composite_fonts = vec![font];
let [r, g, b, _] = ink.to_normalized_gamma_f32();
let fill = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(r, g, b));
let style = CharStyle { font_family: NAME.to_string(), size, fill, ..Default::default() };
let t = TextObject::point(Point::new(INSET, baseline), &sample, style);
let node = std::sync::Arc::new(vectorcraft_doc::Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::Text(Box::new(t))));
let view = Affine::scale(f64::from(ppp));
let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h) * 4] };
RENDERER.with(|r| r.borrow_mut().render_node(&doc, &node, w, h, view)).unwrap_or_else(empty)
}
@@ -280,3 +280,193 @@ fn custom_sets_sharing_a_name_keep_the_dialog_open() {
assert!(app.ui.dialog.is_some());
assert!(names(&app).is_empty());
}
/// A composite font set in Inter, with its Roman part as `roman` changes it.
fn inter_font(roman: impl FnOnce(&mut vectorcraft_doc::CompositePart)) -> CompositeFont {
let mut parts = vectorcraft_doc::CompositeParts::all(vectorcraft_doc::CompositePart::new("Inter", "Regular"));
roman(&mut parts.roman);
CompositeFont { name: "UI Composite Sample".into(), parts, custom: Vec::new() }
}
/// Show Sample opens hidden at 100% with the ICF box, em box and baseline shown; its button shows
/// and hides the sample, which draws with every line shown and at every zoom; nothing changes in
/// the document.
#[test]
fn show_sample_shows_and_hides_the_sample() {
let mut app = app();
open(&mut app).unwrap();
let d = dialog(&mut app);
assert!(!d.bool("sample"));
assert_eq!(d.fields.get("zoom"), Some(&json!(100)));
let shown: Vec<bool> = sample::Mark::ALL.iter().map(|m| d.bool(m.field())).collect();
assert_eq!(shown, [true, true, true, false, false, false, false]);
press(&mut app, Action::New);
press(&mut app, Action::Sample);
assert!(dialog(&mut app).bool("sample"));
frame(&mut app);
for m in sample::Mark::ALL {
dialog(&mut app).fields.insert(m.field().into(), json!(true));
}
for z in sample::ZOOMS {
dialog(&mut app).fields.insert("zoom".into(), json!(z));
frame(&mut app);
}
press(&mut app, Action::Sample);
assert!(!dialog(&mut app).bool("sample"));
super::super::cancel(&mut app);
assert!(names(&app).is_empty());
}
/// `ui.dialog.set` takes `sample`, `zoom` and the line fields; a zoom outside the Zoom menu or a
/// line that is not true or false is refused and leaves the dialog as it was.
#[test]
fn sample_fields_are_set_and_checked() {
let mut app = app();
let ctx = egui::Context::default();
open(&mut app).unwrap();
let set = |app: &mut VectorcraftApp, field: &str, value: Value| {
let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": field, "value": value}));
let crate::control::Outcome::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("not done") };
r
};
for (field, value) in [("sample", json!(true)), ("zoom", json!(400)), ("lineCapHeight", json!(true)), ("lineBaseline", json!(false))] {
let r = set(&mut app, field, value.clone());
assert!(r.get("error").is_none(), "{field}: {r}");
assert_eq!(dialog(&mut app).fields.get(field), Some(&value), "{field}");
}
for (field, value) in [("zoom", json!(30)), ("zoom", json!("200")), ("sample", json!(1)), ("lineXHeight", json!("yes"))] {
let r = set(&mut app, field, value.clone());
assert!(r.get("error").is_some(), "{field} {value}: {r}");
}
let d = dialog(&mut app);
assert_eq!((d.fields.get("zoom"), d.bool("sample"), d.bool("lineXHeight")), (Some(&json!(400)), true, false));
}
/// The sample's lines: the em box and ICF box of the face the Kanji are set in (a face without
/// ideographs centers its em box 0.38 em above the baseline), the cap height and x-height of the
/// Roman part's face raised by its baseline and scaled by its vertical scale, the lowest descent
/// and highest ascent, and the top of the tallest glyph; all of them grow with the size.
#[test]
fn sample_lines_follow_the_parts() {
let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
let (path, h) = sample::measure(&inter_font(|_| {}), 36.0);
assert!(!path.elements().is_empty());
let (bottom, top) = h.em_box.unwrap();
assert!(close(bottom, -0.12 * 36.0) && close(top, 0.88 * 36.0), "{h:?}");
let (ib, it) = h.icf_box.unwrap();
assert!(ib >= bottom && it <= top && ib < it, "{h:?}");
let (cap, x) = (h.cap_height.unwrap(), h.x_height.unwrap());
assert!(0.0 < x && x < cap && cap < top, "{h:?}");
let (low, high) = h.ascent_descent.unwrap();
assert!(low < 0.0 && high > cap, "{h:?}");
assert!(h.ascender.unwrap() > x, "{h:?}");
// The Roman part raised by 10% and squeezed to half height moves its lines; the Kanji's stay.
let (_, raised) = sample::measure(
&inter_font(|p| {
p.baseline = 10.0;
p.v_scale = 50.0;
}),
36.0,
);
assert!(close(raised.cap_height.unwrap(), 3.6 + cap * 0.5), "{raised:?}");
assert!(close(raised.x_height.unwrap(), 3.6 + x * 0.5), "{raised:?}");
assert_eq!(raised.em_box, h.em_box);
// At 200% every line is twice as far from the baseline.
let (_, double) = sample::measure(&inter_font(|_| {}), 72.0);
assert!(close(double.cap_height.unwrap(), cap * 2.0) && close(double.em_box.unwrap().1, top * 2.0), "{double:?}");
}
/// The ICF box is the Kanji face's ideographic character face inside its em box, and a Roman face
/// without an OS/2 cap height still gets a Cap Height line, estimated from its ascent.
#[test]
fn sample_lines_read_the_icf_box_and_estimate_a_missing_cap_height() {
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, HEIGHTLESS_FAMILY, height_font};
let db = vectorcraft_text::FontDb::global();
db.add_font(height_font(true).expect("the test font builds"));
db.add_font(height_font(false).expect("the test font builds"));
let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
let mut f = inter_font(|p| p.font = HEIGHTLESS_FAMILY.into());
f.parts.kanji.font = HEIGHT_FAMILY.into();
let (_, h) = sample::measure(&f, 36.0);
let (bottom, top) = h.icf_box.unwrap();
assert!(close(bottom, -0.07 * 36.0) && close(top, 0.83 * 36.0), "{h:?}");
let cap = h.cap_height.expect("an estimated cap height");
assert!(cap > h.x_height.unwrap() && cap < h.ascent_descent.unwrap().1, "{h:?}");
}
/// A character its part's font lacks is drawn in a fallback face, and the lines measure that face:
/// in a font whose box runs to 0.9 em and which maps no `A`, `g`, `h`, `1` or `2`, the highest
/// ascent is the fallback face's.
#[test]
fn sample_lines_measure_the_faces_that_draw_the_glyphs() {
use vectorcraft_text::test_fonts::{PATH_ALIGN_HHEA_FAMILY, path_align_font};
vectorcraft_text::FontDb::global().add_font(path_align_font(PATH_ALIGN_HHEA_FAMILY).expect("the test font builds"));
let mut f = inter_font(|_| {});
f.parts = vectorcraft_doc::CompositeParts::all(vectorcraft_doc::CompositePart::new(PATH_ALIGN_HHEA_FAMILY, "Regular"));
let (_, h) = sample::measure(&f, 36.0);
let (_, high) = h.ascent_descent.unwrap();
assert!(high > 0.9 * 36.0 + 0.5, "{h:?}");
}
/// The lines follow a vertical scale as the glyphs do: a custom set that holds the first Kanji at
/// half height halves the em box about its baseline, and Kana scaled at center keep the middle of
/// their em box, so their ascent moves up by the half they lose below it.
#[test]
fn sample_lines_follow_vertical_scale() {
let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
let mut f = inter_font(|_| {});
let mut half = vectorcraft_doc::CompositePart::new("Inter", "Regular");
half.v_scale = 50.0;
f.custom = vec![CustomCharSet { name: "Half".into(), characters: "永".into(), part: half }];
let (_, h) = sample::measure(&f, 36.0);
let (bottom, top) = h.em_box.unwrap();
assert!(close(bottom, (0.38 - 0.5) * 18.0) && close(top, (0.38 + 0.5) * 18.0), "{h:?}");
let kana = |at_center: bool| {
let mut f = inter_font(|_| {});
f.parts.kana.size = 300.0;
f.parts.kana.v_scale = 50.0;
f.parts.kana.scale_at_center = at_center;
sample::measure(&f, 36.0).1.ascent_descent.unwrap()
};
// The Kana, at three times the size, give the highest ascent either way.
let ((_, high), (_, raised)) = (kana(false), kana(true));
assert!(close(raised, high + 0.38 * 108.0 * 0.5), "{high} {raised}");
}
/// The sample adds the first character of each custom set it does not hold yet, and a font whose
/// sets can't be used yet (two sharing a name while it is typed) still draws, without them.
#[test]
fn the_sample_takes_the_custom_sets() {
let mut f = inter_font(|_| {});
let set = |name: &str, characters: &str| CustomCharSet {
name: name.into(),
characters: characters.into(),
part: vectorcraft_doc::CompositePart::new("Inter", "Regular"),
};
f.custom = vec![set("Marks", "〒※"), set("Letters", "A")];
assert_eq!(sample::text(&f), format!("{}〒", sample::TEXT));
f.custom = vec![set("Marks", "〒"), set("marks", "〒")];
let (path, h) = sample::measure(&f, 36.0);
assert!(!path.elements().is_empty() && h.cap_height.is_some());
}
/// The sample draws a color font's glyphs in their own colors, not in the dialog's text color.
#[test]
fn the_sample_draws_color_glyphs_in_their_colors() {
use vectorcraft_text::test_fonts::{COLOUR_CHAR, colr_family, colr_font};
vectorcraft_text::FontDb::global().add_font(colr_font(false).expect("the test font builds"));
let mut f = inter_font(|_| {});
let mut colr = vectorcraft_doc::CompositePart::new(colr_family(false), "Regular");
colr.size = 300.0;
f.custom = vec![CustomCharSet { name: "Color".into(), characters: COLOUR_CHAR.to_string(), part: colr }];
let img = sample::draw(&f, 36.0, 120.0, (900, 160), 1.0, egui::Color32::BLACK);
let red = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).any(|(x, y)| {
let p = img.pixel(x, y);
p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200
});
assert!(red, "the glyph's red layer is drawn");
// Max Ascender reaches the top of the color glyph, three times the size of the rest.
let (_, plain) = sample::measure(&inter_font(|_| {}), 36.0);
let (_, tall) = sample::measure(&f, 36.0);
assert!(tall.ascender.unwrap() > plain.ascender.unwrap() * 1.5, "{plain:?} {tall:?}");
}
+1 -1
View File
@@ -120,7 +120,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
number(ui, d, "offset", tl!("Offset"), (0.0, 100000.0), "", 1, Some(unit));
ui.horizontal(|ui| {
let cap = flag(d, "cap", true);
let tip = tl!("Close the circular ends of open profiles. Partial sweeps keep their cut sides open.");
let tip = tl!("Close the circular ends of open profiles. Partial sweeps also close their cut sides.");
if widgets::check3_tip(ui, c3("Cap"), cap, true, tip) {
d.fields.insert("cap".into(), json!(cap != Some(true)));
}
+1
View File
@@ -31,6 +31,7 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, width:
ui.set_max_height(tall);
panels::libraries(app, ui);
}
None if id == "color" && widgets::panel_footer_bottom(ui).is_some() => panels::color::show_sized(app, ui, tall),
None => panels::show_icon_panel(app, ui, id),
}
});
+104 -21
View File
@@ -4,7 +4,10 @@
//! or reached with ↑/↓ previews its font on the selected text (one live interaction, nothing in
//! the history); a click or Enter applies it as one step, Escape or closing the menu puts the text
//! back. The Glyphs panel and Find Font only pick a font ([`picked`]): nothing is previewed on the
//! document. A star marks a favourite family, and the ★ filter lists only those. The Font
//! document. A star marks a favourite family, and the ★ filter lists only those. The ≈ button
//! before a family's star (Show Similar Fonts) orders the listed families by how alike they look to
//! it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent
//! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font
//! Technology filter's Variable lists only variable font families. Preferences › Type › Enable
//! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays
//! out its filters on the same four rows wherever it opens. However narrow its field, it opens at
@@ -160,6 +163,8 @@ impl<'a> MenuLook<'a> {
const ROW: f32 = 24.0;
/// Width of the star at the end of a family's row.
const STAR: f32 = 18.0;
/// Width of the Show Similar Fonts button before the star.
const SIMILAR: f32 = 18.0;
/// The least share of a row the family's name takes when the row is too narrow for the widest
/// name and [`SAMPLE_W`]; the sample fills the rest.
const NAME_SHARE: f32 = 0.5;
@@ -305,8 +310,8 @@ fn remap_highlight(before: &[Row], selected: Option<usize>, after: &[Row]) -> Op
/// What the rows were listed for: the query, the script, kind, font technology (variable only) and
/// favourites filters, Show Font Names in English, the expanded families, favourites, recent
/// history and font list generation.
type RowsKey = (String, usize, Option<FontClass>, bool, bool, bool, Vec<String>, Vec<String>, Vec<String>, u64);
/// history, font list generation and the family Show Similar Fonts orders by.
type RowsKey = (String, usize, Option<FontClass>, bool, bool, bool, Vec<String>, Vec<String>, Vec<String>, u64, Option<String>);
/// The menu's state between frames.
#[derive(Clone, Default)]
@@ -330,6 +335,12 @@ struct MenuState {
favorites_only: bool,
/// Families whose styles are listed (lowercase).
expanded: Vec<String>,
/// Show Similar Fonts: the family the list is ordered by likeness to, until it is cleared or
/// the menu closes.
similar: Option<String>,
/// Show Similar Fonts was chosen or cleared: the family it ordered by, which is highlighted
/// and scrolled to once (to the top while the list is ordered by it).
similar_moved: Option<String>,
/// What was previewed last (None: nothing is previewed).
previewed: Option<(String, Option<String>)>,
/// The rows listed, and what for: built again only when that changes, not every frame.
@@ -1043,6 +1054,8 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
st.highlight = None;
st.query.clear();
st.current = current.to_string();
st.similar = None;
st.similar_moved = None;
}
st.last = pass;
// For [`end_stale_preview`]: the menu is open, in this layer.
@@ -1080,10 +1093,15 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
look.favorites.to_vec(),
look.recent.to_vec(),
db.generation(),
st.similar.clone(),
);
if st.rows_key.as_ref() != Some(&key) {
let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look)).cloned().collect();
let rows = grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f));
// Show Similar Fonts orders every listed family by likeness, the recent ones among them.
let rows = match &st.similar {
Some(base) => grouped_rows(&db.similar_families(base, &families), &[], &st.expanded, |f| db.styles(f)),
None => grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)),
};
// Filter changes (including un-starring a favourite) may remove rows; expanding
// another family or a background font scan can insert rows before the highlight.
// Never preview an unrelated family because the old numeric index now points to it.
@@ -1096,6 +1114,9 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
st.query = query.clone();
st.highlight = None;
}
if let Some(base) = &st.similar_moved {
st.highlight = rows.iter().position(|r| matches!(r, Row::Family(f) if f.eq_ignore_ascii_case(base)));
}
if st.highlight.is_none() && query.is_empty() {
st.highlight = rows.iter().position(|r| matches!(r, Row::Family(f) if f.eq_ignore_ascii_case(current)));
}
@@ -1196,16 +1217,29 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool {
});
}
st.filters = widest;
// While Show Similar Fonts orders the list: the family it orders by, which clears it. Its
// width is left out of the widest row: a long name wraps instead of widening the menu.
if let Some(base) = st.similar.clone() {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(4.0, 2.0);
let chip = egui::RichText::new(format!("≈ {base} ✕")).size(FILTER_SIZE);
if ui.selectable_label(true, chip).on_hover_text(tl!("Clear Similar Fonts")).clicked() {
st.similar_moved = st.similar.take();
refilter = true;
}
});
}
refilter
}
/// The width the open menu takes at least: the widest row of filters last frame, and the widest
/// name up to [`NAME_MAX`] with room for its sample, the star and the scroll bar beside it, within
/// [`WINDOW_SHARE`] of the window. The menu is never narrower than its field.
/// name up to [`NAME_MAX`] with room for its sample, the Show Similar Fonts button, the star and the
/// scroll bar beside it, within [`WINDOW_SHARE`] of the window. The menu is never narrower than its
/// field.
fn menu_width(ui: &Ui, st: &MenuState, look: MenuLook) -> f32 {
let sample = if look.samples { SAMPLE_W } else { 0.0 };
let names = name_width(ui, vectorcraft_text::FontDb::global(), look.english_names, &st.rows).min(NAME_MAX);
let row = DISCLOSURE + names + NAME_GAP + sample + STAR + 2.0 + widgets::list_scroll_style().allocated_width();
let row = DISCLOSURE + names + NAME_GAP + sample + SIMILAR + STAR + 2.0 + widgets::list_scroll_style().allocated_width();
// Rounding in the chips' widths must not wrap the widest row.
let filters = if st.filters > 0.0 { st.filters.ceil() + 1.0 } else { 0.0 };
filters.max(row).min(ui.ctx().content_rect().width() * WINDOW_SHARE)
@@ -1267,13 +1301,14 @@ fn widest_label(ui: &Ui, labels: Vec<String>) -> f32 {
}
/// Where a row `width` wide puts its sample, after the name column: room for the widest name
/// (`widest`) and a gap, as far as that leaves [`SAMPLE_W`] and the star for the sample or
/// [`NAME_SHARE`] of the row for the name. Without samples the name runs to the star.
/// (`widest`) and a gap, as far as that leaves [`SAMPLE_W`], the Show Similar Fonts button and the
/// star for the sample or [`NAME_SHARE`] of the row for the name. Without samples the name runs to
/// the Show Similar Fonts button.
fn name_column(width: f32, widest: f32, samples: bool) -> f32 {
if !samples {
return width - STAR;
return width - SIMILAR - STAR;
}
(DISCLOSURE + widest + NAME_GAP).min((width - STAR - 2.0 - SAMPLE_W).max(width * NAME_SHARE))
(DISCLOSURE + widest + NAME_GAP).min((width - SIMILAR - STAR - 2.0 - SAMPLE_W).max(width * NAME_SHARE))
}
/// The disclosure triangle of a family with several styles; whether the pointer is on it.
@@ -1293,6 +1328,18 @@ fn star_cell(p: &egui::Painter, resp: &egui::Response, star: egui::Rect, (on, hi
resp.interact_pointer_pos().is_some_and(|pos| star.contains(pos))
}
/// The Show Similar Fonts button before a family's star, shown when the row is hovered or
/// highlighted, or is the family the list is ordered by; whether the pointer hovers it, and whether
/// it presses it.
fn similar_cell(p: &egui::Painter, resp: &egui::Response, cell: egui::Rect, (on, highlighted): (bool, bool), t: &Tokens) -> (bool, bool) {
let hot = resp.hover_pos().is_some_and(|pos| cell.contains(pos));
if on || highlighted || resp.hovered() {
let color = if on || hot { t.accent } else { t.text_dim };
p.text(cell.center(), egui::Align2::CENTER_CENTER, "≈", egui::FontId::proportional(13.0), color);
}
(hot, resp.interact_pointer_pos().is_some_and(|pos| cell.contains(pos)))
}
/// A heading row (Recent Fonts, Fonts), which cannot preview or apply a font.
fn heading_row(ui: &mut Ui, row_h: f32, label: &str, t: &Tokens) {
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::hover());
@@ -1304,6 +1351,35 @@ fn heading_row(ui: &mut Ui, row_h: f32, label: &str, t: &Tokens) {
ui.painter_at(rect).text(rect.left_center() + vec2(4.0, 0.0), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(11.0), t.text_dim);
}
/// The row the list scrolls to this frame, and how it aligns it. Opening, the list shows the recent
/// section even when the current family is farther down the list, else centres the current font;
/// key presses keep the highlight in view. Show Similar Fonts goes to the first row, the family it
/// orders by, and clearing it goes back to that family, highlighted.
fn scroll_target(st: &mut MenuState, rows: &[Row], opening: bool, keyed: bool) -> Option<(usize, Option<egui::Align>)> {
if st.similar_moved.take().is_some() {
return match st.similar {
Some(_) => Some((0, Some(egui::Align::TOP))),
None => st.highlight.map(|i| (i, Some(egui::Align::Center))),
};
}
if opening && matches!(rows.first(), Some(Row::Heading("Recent Fonts"))) {
return Some((0, Some(egui::Align::TOP)));
}
st.highlight.filter(|_| opening || keyed).map(|i| (i, opening.then_some(egui::Align::Center)))
}
/// The Show Similar Fonts button of family `f`'s row `i` before its star (`star`); whether the
/// pointer presses it. A click on it asks for the list ordered by likeness to `f`.
fn similar_button(p: &egui::Painter, resp: &egui::Response, star: egui::Rect, f: &str, (st, i): (&MenuState, usize), t: &Tokens) -> (bool, bool) {
let cell = egui::Rect::from_min_max(egui::pos2(star.min.x - SIMILAR, star.min.y), egui::pos2(star.min.x, star.max.y));
let ordering = st.similar.as_deref().is_some_and(|s| s.eq_ignore_ascii_case(f));
let (hot, pressed) = similar_cell(p, resp, cell, (ordering, st.highlight == Some(i)), t);
if hot {
resp.clone().on_hover_text(tl!("Show Similar Fonts"));
}
(pressed, resp.clicked() && pressed)
}
/// The rows of the open menu in `range`, the ones in view: the menu's one scrolling part, under
/// the search field and filters (#555).
fn rows(ui: &mut Ui, range: std::ops::Range<usize>, h: Listed<'_>, sample: Option<&str>, look: MenuLook) -> Option<FontPick> {
@@ -1327,19 +1403,14 @@ fn rows(ui: &mut Ui, range: std::ops::Range<usize>, h: Listed<'_>, sample: Optio
let place = egui::Rect::from_min_size(egui::pos2(left, top + i as f32 * row_h), vec2(width, row_h));
ui.scroll_to_rect_animation(place, align, egui::style::ScrollAnimation::none());
};
// Open at the recent section even when the current family is farther down the list.
// Otherwise centre the current font; subsequent key presses keep the highlight in view.
if opening && matches!(rows.first(), Some(Row::Heading("Recent Fonts"))) {
scroll_to(ui, 0, Some(egui::Align::TOP));
} else if let Some(i) = st.highlight
&& (opening || keyed)
{
scroll_to(ui, i, opening.then_some(egui::Align::Center));
if let Some((i, align)) = scroll_target(st, &rows, opening, keyed) {
scroll_to(ui, i, align);
}
let mut chosen: Option<(String, Option<String>)> = None;
let mut hovered: Option<usize> = None;
let mut toggled: Option<String> = None;
let mut starred: Option<String> = None;
let mut similar: Option<String> = None;
for i in range {
let Some(row) = rows.get(i) else { continue };
if let Row::Heading(label) = row {
@@ -1379,6 +1450,12 @@ fn rows(ui: &mut Ui, range: std::ops::Range<usize>, h: Listed<'_>, sample: Optio
starred = Some(f.clone());
}
}
let mut on_similar = false;
if let Row::Family(f) = row {
let (pressed, clicked) = similar_button(&p, &resp, star, f, (&*st, i), &t);
on_similar = pressed;
similar = similar.or(clicked.then(|| f.clone()));
}
let indent = if row.style().is_some() { DISCLOSURE + STYLE_INDENT } else { DISCLOSURE };
let name_w = name_column(rect.width(), widest, look.samples);
let name_rect = egui::Rect::from_min_max(rect.min + vec2(indent, 0.0), egui::pos2(rect.min.x + name_w - 4.0, rect.max.y));
@@ -1390,7 +1467,7 @@ fn rows(ui: &mut Ui, range: std::ops::Range<usize>, h: Listed<'_>, sample: Optio
};
ui.painter_at(name_rect).text(name_rect.left_center(), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(NAME_SIZE), t.text);
// The sample takes the row's whole height.
let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(STAR + 2.0, 0.0));
let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(SIMILAR + STAR + 2.0, 0.0));
if look.samples {
// The paper is drawn while the sample is still rendering, and for a family whose sample fails.
let area = sample_area(ui, sample_rect, ink, PAPER_INSET);
@@ -1398,10 +1475,16 @@ fn rows(ui: &mut Ui, range: std::ops::Range<usize>, h: Listed<'_>, sample: Optio
paint_sample(ui, area, &tex, ink);
}
}
if resp.clicked() && !on_triangle && !on_star {
if resp.clicked() && !on_triangle && !on_star && !on_similar {
chosen = row.pick();
}
}
if let Some(f) = similar {
// The rows are ordered again next frame, which highlights `f` and scrolls to it.
st.similar_moved = Some(f.clone());
st.similar = Some(f);
return None;
}
if let Some(f) = toggled {
if st.expanded.contains(&f) {
st.expanded.retain(|e| *e != f);
+80 -4
View File
@@ -64,15 +64,15 @@ fn the_scroll_bar_leaves_the_stars_clear() {
/// In a wide row the sample starts after the widest name and a gap, not halfway along, even for a
/// name wider than the menu widens itself for; the sample keeps its room, and a row too narrow for
/// both gives the name half of it. Without samples the name runs to the star.
/// both gives the name half of it. Without samples the name runs to the Show Similar Fonts button.
#[test]
fn the_sample_starts_after_the_widest_name() {
use super::{DISCLOSURE, NAME_GAP, NAME_MAX, SAMPLE_W, STAR, name_column};
use super::{DISCLOSURE, NAME_GAP, NAME_MAX, SAMPLE_W, SIMILAR, STAR, name_column};
assert_eq!(name_column(500.0, 100.0, true), DISCLOSURE + 100.0 + NAME_GAP);
assert_eq!(name_column(600.0, NAME_MAX + 80.0, true), DISCLOSURE + NAME_MAX + 80.0 + NAME_GAP);
assert_eq!(name_column(600.0, 1000.0, true), 600.0 - STAR - 2.0 - SAMPLE_W);
assert_eq!(name_column(600.0, 1000.0, true), 600.0 - SIMILAR - STAR - 2.0 - SAMPLE_W);
assert_eq!(name_column(200.0, 100.0, true), 100.0);
assert_eq!(name_column(500.0, 100.0, false), 500.0 - STAR);
assert_eq!(name_column(500.0, 100.0, false), 500.0 - SIMILAR - STAR);
}
/// The widest label is the widest one laid out, though it has fewer characters than others, or
@@ -1055,3 +1055,79 @@ fn a_menu_items_sample_follows_show_samples_on_white() {
assert!(!shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default())), "no sample");
assert!(shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.fill == super::SAMPLE_PAPER && r.rect == slot)), "the slot is white");
}
/// The center of the first text shape whose text passes `wanted`.
fn text_at(shapes: &[egui::epaint::ClippedShape], wanted: impl Fn(&str) -> bool) -> Option<egui::Pos2> {
shapes.iter().find_map(|c| match &c.shape {
egui::Shape::Text(t) if wanted(t.galley.text()) => Some(t.visual_bounding_rect().center()),
_ => None,
})
}
/// Show Similar Fonts: the ≈ button of a family's row orders the listed families by likeness to
/// it, that family first and highlighted, without the Recent Fonts section and without picking a
/// font; the ≈ chip under the filters puts the menu's order back, and so does opening the menu
/// again.
#[test]
fn show_similar_fonts_orders_the_list_by_likeness() {
// The bundled fonts alone: fonts that tests running alongside add stay out of the rows.
let db = vectorcraft_text::FontDb::with_font_dirs(vec![]);
let recent = vec!["JetBrains Mono".to_string()];
let ctx = egui::Context::default();
let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0));
let look = super::MenuLook { samples: false, recent: &recent, ..Default::default() };
let mut st = super::MenuState::default();
let picks = std::cell::RefCell::new(vec![]);
let mut frame = |events: Vec<egui::Event>, st: &mut super::MenuState| {
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| {
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area));
picks.borrow_mut().extend(super::list_of(&mut child, &db, egui::Id::unique("similar"), st, "Inter", None, look).inner);
});
out.textures_delta.clear();
out.shapes
};
let click = |frame: &mut dyn FnMut(Vec<egui::Event>, &mut super::MenuState) -> Vec<egui::epaint::ClippedShape>,
st: &mut super::MenuState,
pos: egui::Pos2| {
let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(vec![egui::Event::PointerMoved(pos)], st);
frame(vec![button(true)], st);
frame(vec![button(false)], st);
frame(vec![], st)
};
let families = |st: &super::MenuState| st.rows.iter().filter_map(super::Row::family).map(str::to_string).collect::<Vec<_>>();
let row_of = |st: &super::MenuState, family: &str| st.rows.iter().position(|r| r.family() == Some(family) && r.style().is_none());
let shapes = frame(vec![], &mut st);
let menu_order = families(&st);
assert_eq!(st.rows.first(), Some(&super::Row::Heading("Recent Fonts")));
// A hovered row shows its ≈ button: here Source Serif 4's, not the current family's (Inter).
let name = text_at(&shapes, |t| t == "Source Serif 4").expect("Source Serif 4 is listed");
let shapes = frame(vec![egui::Event::PointerMoved(name)], &mut st);
let button = shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text() == "≈" && (t.visual_bounding_rect().center().y - name.y).abs() < 2.0 => {
Some(t.visual_bounding_rect().center())
}
_ => None,
})
.expect("the hovered row shows ≈");
let shapes = click(&mut frame, &mut st, button);
assert_eq!(st.similar.as_deref(), Some("Source Serif 4"));
assert_eq!(families(&st), db.similar_families("Source Serif 4", &db.menu_family_list()));
assert_eq!(families(&st).first().map(String::as_str), Some("Source Serif 4"));
assert!(!st.rows.iter().any(|r| matches!(r, super::Row::Heading(_))), "no Recent Fonts section: {:?}", st.rows);
assert_eq!(st.highlight, Some(0));
assert!(!picks.borrow().iter().any(|p| matches!(p, super::FontPick::Chosen(..))), "no font picked: {:?}", picks.borrow());
// The chip under the filters clears it, and the family it ordered by stays highlighted.
let chip = text_at(&shapes, |t| t.starts_with("≈ Source Serif 4")).expect("the chip names the family");
click(&mut frame, &mut st, chip);
assert_eq!(st.similar, None);
assert_eq!(families(&st), menu_order);
assert_eq!(st.highlight, row_of(&st, "Source Serif 4"));
// Opening the menu again lists in the menu's order too.
st.similar = Some("Inter".into());
st.last = 0;
frame(vec![], &mut st);
assert_eq!((st.similar.as_deref(), families(&st)), (None, menu_order));
}
+8 -2
View File
@@ -1288,6 +1288,8 @@ font-technology Variable Променливи
Font Family & Style Семейство и стил шрифтове
Font Family, Style & Size Семейство, стил и размер на шрифта
Font List Списък с шрифтове
Show Similar Fonts Показване на подобни шрифтове
Clear Similar Fonts Изчистване на подобните шрифтове
Font Preview Size Размер за преглед на шрифта
Font Size Размер на шрифта
Variable Font Променлив шрифт
@@ -5033,6 +5035,10 @@ axis Both И двете
Em Box Квадратна касетка (Em Box)
x-Height Височина на x
ICF Box Касетка ICF
Show Sample Показване на образец
Hide Sample Скриване на образец
Max Ascent/Descent Макс. височина нагоре/надолу
Max Ascender Макс. възходящ елемент
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` е референцията за стъпка {r}, която се разрешава само от `run` и `command_batch`
@msg `ids` must be an array of object ids, not {v} `ids` трябва да бъде масив от идентификатори на обекти, а не {v}
@msg `colors` must be an array of colors, not {v} `colors` трябва да бъде масив от цветове, а не {v}
@@ -5898,7 +5904,7 @@ theme Appearance Външен вид
@msg Unknown dimension orientation Непозната ориентация на размера
@msg Unknown dimension style Непознат стил на размера
@msg Unknown unit Непозната единица
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Затваря кръговите краища на отворени профили. При частично завъртане срязаните страни остават отворени.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Затваря кръговите краища на отворени профили. При частично завъртане срязаните страни също се затварят.
# Strings added with Drop Shadow Darkness, Isolate Selected Object, Pencil Keep selected, Sample Color from Screen, Tritanopia proofing, Panels Except Tools and Control
Darkness Затъмняване
@@ -6825,7 +6831,7 @@ breakText Glyphs Глифи
@msg stroke cannot be set on a symbol instance stroke не може да се задава за екземпляр на символ
@msg fill on a symbol instance must be a solid color or none fill на екземпляр на символ трябва да е плътен цвят или none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} не може да се задава за изображение без ефект „Конвертиране в фигура“ или „Преобразуване на обекта в контур“
@msg pass newName, registration, exportType, nineSlice and/or type задайте newName, registration, exportType, nineSlice и/или type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid задайте newName, registration, exportType, nineSlice, type и/или alignToPixelGrid
Text Flow Поток на текста
By Rows По редове
By Columns По колони
Can't render this file because it is too large.
+8 -2
View File
@@ -1678,6 +1678,10 @@ digits Malayalam Malajalam
Em Box Em okvir
x-Height Visina malih slova
ICF Box ICF okvir
Show Sample Prikaži uzorak
Hide Sample Sakrij uzorak
Max Ascent/Descent Maks. visina gore/dolje
Max Ascender Maks. gornji produžetak
Copy Color Value (Hex) Kopiraj vrijednost boje (hex)
Create New Swatch… Kreiraj novi uzorak boje…
Name 40% Naziv 40%
@@ -3594,6 +3598,8 @@ theme Appearance Izgled
Find Font Files Pronađi datoteke fontova
Add Font Files Dodaj datoteke fontova
Font List Lista fontova
Show Similar Fonts Prikaži slične fontove
Clear Similar Fonts Očisti slične fontove
Fonts in Document Fontovi u dokumentu
Refresh Font List Osvježi listu fontova
Replace Font Zamijeni font
@@ -5948,7 +5954,7 @@ mark-style Japanese Japanski
@msg Unknown dimension orientation Nepoznata orijentacija kote
@msg Unknown dimension style Nepoznat stil kote
@msg Unknown unit Nepoznata jedinica
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Zatvori kružne krajeve otvorenih profila. Djelimična izvlačenja zadržavaju otvorene rezane strane.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Zatvori kružne krajeve otvorenih profila. Djelimična izvlačenja zatvaraju i svoje rezane strane.
@msg span must be "object" or "selection", got {v} span mora biti "object" ili "selection", dobiveno {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" postavlja `gradient`, a ne uzorak boje
@msg span: "selection" places a gradient: give `gradient` span: "selection" postavlja gradijent: navedite `gradient`
@@ -6877,7 +6883,7 @@ shape Open Otvoren
@msg stroke cannot be set on a symbol instance stroke se ne može postaviti na instancu simbola
@msg fill on a symbol instance must be a solid color or none fill instance simbola mora biti puna boja ili none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} se ne može postaviti na sliku bez efekta „Pretvori u oblik“ ili „Objekat u obrisu“
@msg pass newName, registration, exportType, nineSlice and/or type navedite newName, registration, exportType, nineSlice i/ili type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid navedite newName, registration, exportType, nineSlice, type i/ili alignToPixelGrid
Text Flow Tok teksta
By Rows Po redovima
By Columns Po kolonama
Can't render this file because it contains an unexpected character in line 2 and column 73.
+11 -3
View File
@@ -754,7 +754,7 @@ antiAlias Sharp Nítid
Close Panel Tanca el panell
Close Path Tanca el traçat
Close paths when ends are within: Tanca els traçats quan els extrems siguin a menys de:
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Tanca els extrems circulars dels perfils oberts. Els escombrats parcials mantenen oberts els costats tallats.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Tanca els extrems circulars dels perfils oberts. Els escombrats parcials també tanquen els costats tallats.
Closed Tancat
Closing bracket with no opening one Delimitador de tancament sense un d’obertura
Clumped Agrupat
@@ -1805,6 +1805,8 @@ digits Malayalam Malaiàlam
Font Family, Style & Size Família, estil i mida de tipus de lletra
Font Family: Família de tipus de lletra:
Font List Llista de tipus de lletra
Show Similar Fonts Mostra tipus de lletra semblants
Clear Similar Fonts Esborra els tipus de lletra semblants
Font Preview Size Mida de previsualització del tipus de lletra
Font Size Mida del tipus de lletra
Font Style: Estil de tipus de lletra:
@@ -2662,7 +2664,8 @@ digits Malayalam Malaiàlam
Minimal Mínim
Minimize Minimitza
Minimum Mínim
Minimum must not exceed Desired, nor Desired Maximum. El mínim no pot superar el desitjat ni el màxim desitjat.
Minimum must not exceed Desired, nor Desired Maximum. El mínim no pot superar el desitjat, ni el desitjat el màxim.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: el mínim no pot superar el desitjat, ni el desitjat el màxim
Minus Back Resta al darrere
Minus Front Resta al davant
Mirror Reflexa
@@ -5873,6 +5876,7 @@ liquify-list-end {0}, {1} {0} i {1}
@msg every numbered name for {name} is taken in the document's folder tots els noms numerats per a {name} estan ocupats a la carpeta del document
@msg every search thread stopped on an internal error (please report this bug) tots els fils de cerca s’han aturat per un error intern (informeu d’aquest error)
@msg Expand Appearance: the selection has a basic appearance Expandeix l’aparença: la selecció té una aparença bàsica
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alguns efectes ràster no s’han convertit en imatges: ocuparien més de 1.024 imatges o 256 megapíxels en total
@msg Expand: no brush strokes selected Expandeix: no s’ha seleccionat cap traç de pinzell
@msg Expand: no gradient fills Expandeix: no hi ha farciments de degradat
@msg Expand: nothing to expand Expandeix: no hi ha res per expandir
@@ -7062,6 +7066,10 @@ theme Appearance Aparença
Em Box Caixa em
x-Height Alçada de la x
ICF Box Caixa ICF
Show Sample Mostra l'exemple
Hide Sample Amaga l'exemple
Max Ascent/Descent Alçada/profunditat màx.
Max Ascender Ascendent màx.
# Average & Join (Object › Path, Cmd+Alt+Shift+J).
Average & Join… Mitjana i unió…
Average & Join Mitjana i unió
@@ -7526,7 +7534,7 @@ breakText Glyphs Glifs
@msg stroke cannot be set on a symbol instance stroke no es pot definir en una instància de símbol
@msg fill on a symbol instance must be a solid color or none el fill d’una instància de símbol ha de ser un color sòlid o none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} no es pot definir en una imatge sense l’efecte Converteix en forma o Contorneja l’objecte
@msg pass newName, registration, exportType, nineSlice and/or type indiqueu newName, registration, exportType, nineSlice i/o type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indiqueu newName, registration, exportType, nineSlice, type i/o alignToPixelGrid
Text Flow Flux del text
By Rows Per files
By Columns Per columnes
Can't render this file because it contains an unexpected character in line 2 and column 73.
+12 -2
View File
@@ -1749,6 +1749,10 @@ digits Malayalam Malajálamské
Em Box Čtverčík
x-Height Výška x
ICF Box Rámeček ICF
Show Sample Zobrazit ukázku
Hide Sample Skrýt ukázku
Max Ascent/Descent Max. výška/hloubka
Max Ascender Max. horní dotah
Copy Color Value (Hex) Kopírovat hodnotu barvy (hex)
Create New Swatch… Vytvořit novou položku vzorníku…
Name 40% Název 40 %
@@ -3697,6 +3701,8 @@ theme Appearance Motiv
Find Font Files Najít soubory písem
Add Font Files Přidat soubory písem
Font List Seznam písem
Show Similar Fonts Zobrazit podobná písma
Clear Similar Fonts Zrušit podobná písma
Fonts in Document Písma v dokumentu
Refresh Font List Obnovit seznam písem
Replace Font Nahradit písmo
@@ -4918,6 +4924,7 @@ liquify-list-end {0}, {1} {0} a {1}
@msg Divide Objects Below: select exactly one path Rozdělit objekty pod: vyberte právě jednu cestu
@msg Downloaded {what} Staženo: {what}
@msg Expand Appearance: the selection has a basic appearance Rozložit vzhled: výběr má základní vzhled
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all některé rastrové efekty nebyly převedeny na obrazy: zabraly by více než 1 024 obrazů nebo celkem 256 megapixelů
@msg Expand: no brush strokes selected Rozložit: nejsou vybrány žádné tahy štětcem
@msg Expand: no gradient fills Rozložit: žádné přechodové výplně
@msg Expand: nothing to expand Rozložit: není co rozložit
@@ -6356,7 +6363,7 @@ mark-style Japanese Japonské
@msg Unknown dimension style Neznámý styl kóty
@msg Unknown unit Neznámá jednotka
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Uzavře kruhové konce otevřených profilů. Boční řezy částečného otočení zůstávají otevřené.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Uzavře kruhové konce otevřených profilů. Boční řezy částečného otočení se také uzavřou.
@msg span must be "object" or "selection", got {v} span musí být "object" nebo "selection", ne {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" umísťuje `gradient`, ne vzorník
@msg span: "selection" places a gradient: give `gradient` span: "selection" umísťuje přechod: zadejte `gradient`
@@ -6508,6 +6515,7 @@ mark-style Japanese Japonské
Single Word Justification: Zarovnání jednoho slova:
Full Justify Zarovnat do bloku
Minimum must not exceed Desired, nor Desired Maximum. Minimum nesmí překročit požadovanou hodnotu ani požadovaná hodnota maximum.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimum nesmí překročit požadovanou hodnotu ani požadovaná hodnota maximum
Justification Zarovnání do bloku
Add filters from the list above Přidejte filtry ze seznamu výše
Add to Stack Přidat na zásobník
@@ -7517,7 +7525,7 @@ breakText Glyphs Glyfy
@msg stroke cannot be set on a symbol instance stroke nelze nastavit u instance symbolu
@msg fill on a symbol instance must be a solid color or none fill instance symbolu musí být plná barva nebo none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} nelze nastavit u obrazu bez efektu Převést na tvar nebo Převést objekt na obrys
@msg pass newName, registration, exportType, nineSlice and/or type zadejte newName, registration, exportType, nineSlice a/nebo type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid zadejte newName, registration, exportType, nineSlice, type a/nebo alignToPixelGrid
Text Flow Tok textu
By Rows Po řádcích
By Columns Po sloupcích
@@ -9112,7 +9120,9 @@ breakText Glyphs Glyfy
@msg position must be normal, superscript or subscript position musí být normal, superscript nebo subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position musí být topLeft, topRight, bottomLeft nebo bottomRight
@msg positions must be between 0 and 100000 pt positions musí být mezi 0 a 100000 pt
@msg ppi can't be more than {max} for this image ppi nemůže být pro tento obrázek víc než {max}
@msg ppi must be a positive number, not {ppi} ppi musí být kladné číslo, ne {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim ponechává pixely obrázku beze změny: vynechte ppi
@msg ppi must be between 1 and 2400 ppi musí být mezi 1 a 2400
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` není transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape musí být clippingMask|transparency
Can't render this file because it is too large.
+10 -2
View File
@@ -4319,6 +4319,10 @@ digits Malayalam Malayalam
Em Box Em-felt
x-Height x-højde
ICF Box ICF-felt
Show Sample Vis eksempel
Hide Sample Skjul eksempel
Max Ascent/Descent Maks. højde/dybde
Max Ascender Maks. overhøjde
Copy Color Value (Hex) Kopiér farveværdi (hex)
Create New Swatch… Opret ny farveprøve…
Name 40% Navn 40%
@@ -6092,6 +6096,8 @@ theme Appearance Udseende
Find Font Files Find skrifttypefiler
Add Font Files Tilføj skrifttypefiler
Font List Skrifttypeliste
Show Similar Fonts Vis lignende skrifttyper
Clear Similar Fonts Ryd lignende skrifttyper
Fonts in Document Skrifttyper i dokumentet
Refresh Font List Opdatér skrifttypeliste
Replace Font Erstat skrifttype
@@ -7127,6 +7133,7 @@ imageTrace Outline Kontur
@msg Divide Objects Below: select exactly one path Opdel objekter nedenunder: markér præcis én kurve
@msg Downloaded {what} Downloadede {what}
@msg Expand Appearance: the selection has a basic appearance Udvid udseende: markeringen har et grundlæggende udseende
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all nogle rastereffekter blev ikke lavet om til billeder: de ville kræve mere end 1.024 billeder eller i alt 256 megapixel
@msg Expand: no brush strokes selected Udvid: ingen penselstrøg er markeret
@msg Expand: no gradient fills Udvid: ingen gradientfyld
@msg Expand: nothing to expand Udvid: intet at udvide
@@ -8382,7 +8389,7 @@ mark-style Japanese Japansk
@msg Unknown dimension orientation Ukendt målretning
@msg Unknown dimension style Ukendt målstil
@msg Unknown unit Ukendt enhed
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Luk de runde ender af åbne profiler. Delvise omdrejninger beholder deres skårne sider åbne.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Luk de runde ender af åbne profiler. Delvise omdrejninger lukker også deres skårne sider.
Darkness Mørke
Isolate Selected Object Isolér markeret objekt
Keep selected Behold markeret
@@ -8787,6 +8794,7 @@ swatch Bright Violet Kraftig violet
Single Word Justification: Justering af enkeltord:
Full Justify Lige margener
Minimum must not exceed Desired, nor Desired Maximum. Minimum må ikke overstige Ønsket, og Ønsket ikke Maksimum.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum må ikke overstige Ønsket, og Ønsket ikke Maksimum
Justification Justering
Add filters from the list above Tilføj filtre fra listen ovenfor
Add to Stack Tilføj til stak
@@ -9568,7 +9576,7 @@ breakText Glyphs Glyffer
@msg stroke cannot be set on a symbol instance stroke kan ikke angives for en symbolforekomst
@msg fill on a symbol instance must be a solid color or none fill på en symbolforekomst skal være en ensfarvet farve eller none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan ikke angives for et billede uden effekten Konvertér til form eller Objekt til kontur
@msg pass newName, registration, exportType, nineSlice and/or type angiv newName, registration, exportType, nineSlice og/eller type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid angiv newName, registration, exportType, nineSlice, type og/eller alignToPixelGrid
Text Flow Tekstflow
By Rows Efter rækker
By Columns Efter kolonner
Can't render this file because it is too large.
+12 -2
View File
@@ -1338,6 +1338,8 @@ file-filter Templates Vorlagen
Font Family & Style Schriftfamilie und -schnitt
Font Family, Style & Size Schriftfamilie, -schnitt und -grad
Font List Schriftliste
Show Similar Fonts Ähnliche Schriften anzeigen
Clear Similar Fonts Ähnliche Schriften zurücksetzen
Font Preview Size Größe der Schriftvorschau
Font Size Schriftgrad
Variable Font Variable Schrift
@@ -4520,6 +4522,7 @@ liquify-list-end {0}, {1} {0} und {1}
@msg Divide Objects Below: select exactly one path Darunterliegende Objekte aufteilen: Wählen Sie genau einen Pfad aus
@msg Downloaded {what} {what} heruntergeladen
@msg Expand Appearance: the selection has a basic appearance Aussehen umwandeln: Die Auswahl hat ein einfaches Aussehen
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all einige Rastereffekte wurden nicht in Bilder umgewandelt: Sie würden mehr als 1.024 Bilder oder insgesamt 256 Megapixel benötigen
@msg Expand: no brush strokes selected Umwandeln: keine Pinselkonturen ausgewählt
@msg Expand: no gradient fills Umwandeln: keine Verlaufsflächen
@msg Expand: nothing to expand Umwandeln: nichts umzuwandeln
@@ -5357,6 +5360,10 @@ liquify-list-end {0}, {1} {0} und {1}
Cap Height Versalhöhe
x-Height x-Höhe
ICF Box ICF-Rahmen
Show Sample Muster einblenden
Hide Sample Muster ausblenden
Max Ascent/Descent Max. Höhe/Tiefe
Max Ascender Max. Oberlänge
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` ist der Schrittverweis {r}, den nur `run` und `command_batch` auflösen
@msg `ids` must be an array of object ids, not {v} `ids` muss ein Array von Objekt-IDs sein, nicht {v}
@msg `colors` must be an array of colors, not {v} `colors` muss ein Array von Farben sein, nicht {v}
@@ -5937,7 +5944,7 @@ effect Soft Weich
@msg Unknown dimension style Unbekannter Bemaßungsstil
@msg Unknown unit Unbekannte Einheit
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Schließt die kreisförmigen Enden offener Profile. Bei einer Teildrehung bleiben die Schnittseiten offen.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Schließt die kreisförmigen Enden offener Profile. Bei einer Teildrehung werden auch die Schnittseiten geschlossen.
Distance Abstand
@msg span must be "object" or "selection", got {v} span muss "object" oder "selection" sein, nicht {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" platziert einen `gradient`, kein Farbfeld
@@ -6090,6 +6097,7 @@ effect Soft Weich
Single Word Justification: Ausrichtung einzelner Wörter:
Full Justify Blocksatz
Minimum must not exceed Desired, nor Desired Maximum. Das Minimum darf den optimalen Wert nicht übersteigen, der optimale Wert nicht das Maximum.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Das Minimum darf den optimalen Wert nicht übersteigen, der optimale Wert nicht das Maximum
Minimum Minimum
Justification Abstände
Add filters from the list above Filter aus der Liste oben hinzufügen
@@ -7108,7 +7116,7 @@ breakText Glyphs Glyphen
@msg stroke cannot be set on a symbol instance stroke kann nicht für eine Symbolinstanz gesetzt werden
@msg fill on a symbol instance must be a solid color or none fill einer Symbolinstanz muss eine Vollfarbe oder none sein
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kann nicht für ein Bild ohne den Effekt „In Form umwandeln“ oder „Objekt in Pfade umwandeln“ gesetzt werden
@msg pass newName, registration, exportType, nineSlice and/or type geben Sie newName, registration, exportType, nineSlice und/oder type an
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid geben Sie newName, registration, exportType, nineSlice, type und/oder alignToPixelGrid an
Text Flow Textfluss
By Rows Nach Zeilen
By Columns Nach Spalten
@@ -8692,7 +8700,9 @@ breakText Glyphs Glyphen
@msg position must be normal, superscript or subscript position muss normal, superscript oder subscript sein
@msg position must be topLeft, topRight, bottomLeft or bottomRight position muss topLeft, topRight, bottomLeft oder bottomRight sein
@msg positions must be between 0 and 100000 pt positions müssen zwischen 0 und 100000 pt liegen
@msg ppi can't be more than {max} for this image ppi darf für dieses Bild nicht mehr als {max} sein
@msg ppi must be a positive number, not {ppi} ppi muss eine positive Zahl sein, nicht {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim lässt die Pixel des Bildes unverändert: Lassen Sie ppi weg
@msg ppi must be between 1 and 2400 ppi muss zwischen 1 und 2400 liegen
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` ist nicht transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape muss clippingMask|transparency sein
Can't render this file because it is too large.
+10 -2
View File
@@ -1273,6 +1273,8 @@ font-technology Variable Μεταβλητές
Font Family & Style Οικογένεια και στυλ γραμματοσειράς
Font Family, Style & Size Οικογένεια, στυλ και μέγεθος γραμματοσειράς
Font List Λίστα γραμματοσειρών
Show Similar Fonts Εμφάνιση παρόμοιων γραμματοσειρών
Clear Similar Fonts Απαλοιφή παρόμοιων γραμματοσειρών
Font Preview Size Μέγεθος προεπισκόπησης γραμματοσειράς
Font Size Μέγεθος γραμματοσειράς
Variable Font Μεταβλητή γραμματοσειρά
@@ -2617,6 +2619,7 @@ liquify-list-end {0}, {1} {0} και {1}
@msg Divide Objects Below: select exactly one path Διαίρεση αντικειμένων από κάτω: επιλέξτε ακριβώς μία διαδρομή
@msg Downloaded {what} Έγινε λήψη του {what}
@msg Expand Appearance: the selection has a basic appearance Επέκταση εμφάνισης: η επιλογή έχει βασική εμφάνιση
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all ορισμένα εφέ ράστερ δεν μετατράπηκαν σε εικόνες: θα χρειάζονταν περισσότερες από 1.024 εικόνες ή συνολικά 256 megapixel
@msg Expand: no brush strokes selected Επέκταση: δεν επιλέχθηκαν πινελιές
@msg Expand: no gradient fills Επέκταση: δεν υπάρχουν γεμίσματα ντεγκραντέ
@msg Expand: nothing to expand Επέκταση: δεν υπάρχει περιεχόμενο προς επέκταση
@@ -5403,6 +5406,10 @@ digits Malayalam Μαλαγιάλαμ
Em Box Τετράγωνο em
x-Height Ύψος x
ICF Box Πλαίσιο ICF
Show Sample Εμφάνιση δείγματος
Hide Sample Απόκρυψη δείγματος
Max Ascent/Descent Μέγ. ύψος/βάθος
Max Ascender Μέγ. άνω επέκταση
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve το `id` είναι η αναφορά βήματος {r}, την οποία αναλύουν μόνο τα `run` και `command_batch`
@msg `ids` must be an array of object ids, not {v} το `ids` πρέπει να είναι πίνακας αναγνωριστικών αντικειμένων, όχι {v}
@msg `colors` must be an array of colors, not {v} το `colors` πρέπει να είναι πίνακας χρωμάτων, όχι {v}
@@ -6234,7 +6241,7 @@ effect Points Σημεία
By Object Ανά αντικείμενο
Check an artboard to save. Επιλέξτε έναν πίνακα σχεδίασης για αποθήκευση.
Clear All Εκκαθάριση όλων
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Κλείσιμο των κυκλικών άκρων των ανοιχτών προφίλ. Οι μερικές περιστροφές κρατούν ανοιχτές τις πλευρές τομής τους.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Κλείσιμο των κυκλικών άκρων των ανοιχτών προφίλ. Οι μερικές περιστροφές κλείνουν επίσης τις πλευρές τομής τους.
Color Panel Options Επιλογές πίνακα χρώματος
Color blindness – Tritanopia-type Αχρωματοψία – τύπου τριτανοπίας
Create Dimension Δημιουργία διάστασης
@@ -6488,6 +6495,7 @@ effect Points Σημεία
Single Word Justification: Στοίχιση μεμονωμένης λέξης:
Full Justify Στοίχιση και στα δύο άκρα
Minimum must not exceed Desired, nor Desired Maximum. Το ελάχιστο δεν πρέπει να υπερβαίνει το επιθυμητό, ούτε το επιθυμητό το μέγιστο.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: το ελάχιστο δεν πρέπει να υπερβαίνει το επιθυμητό, ούτε το επιθυμητό το μέγιστο
Justification Πλήρης στοίχιση
Add filters from the list above Προσθέστε φίλτρα από τη λίστα παραπάνω
Add to Stack Προσθήκη στη στοίβα
@@ -7499,7 +7507,7 @@ breakText Glyphs Γλύφοι
@msg stroke cannot be set on a symbol instance το stroke δεν μπορεί να οριστεί σε στιγμιότυπο συμβόλου
@msg fill on a symbol instance must be a solid color or none το fill ενός στιγμιότυπου συμβόλου πρέπει να είναι συμπαγές χρώμα ή none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it το {key} δεν μπορεί να οριστεί σε εικόνα χωρίς το εφέ «Μετατροπή σε σχήμα» ή «Μετατροπή αντικειμένου σε περιγράμματα»
@msg pass newName, registration, exportType, nineSlice and/or type δώστε newName, registration, exportType, nineSlice ή/και type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid δώστε newName, registration, exportType, nineSlice, type ή/και alignToPixelGrid
Text Flow Ροή κειμένου
By Rows Κατά γραμμές
By Columns Κατά στήλες
Can't render this file because it is too large.
+10 -2
View File
@@ -1036,6 +1036,10 @@ font-technology Variable Variables
Em Box Cuadro eme
x-Height Altura de la x
ICF Box Cuadro ICF
Show Sample Mostrar muestra
Hide Sample Ocultar muestra
Max Ascent/Descent Altura/profundidad máx.
Max Ascender Ascendente máx.
Em Dash Raya
Em Space Espacio eme
Embed Incrustar
@@ -1349,6 +1353,8 @@ font-technology Variable Variables
Font Family & Style Familia y estilo de fuente
Font Family, Style & Size Familia, estilo y tamaño de fuente
Font List Lista de fuentes
Show Similar Fonts Mostrar fuentes similares
Clear Similar Fonts Borrar fuentes similares
Font Preview Size Tamaño de vista previa de fuente
Font Size Tamaño de fuente
Variable Font Fuente variable
@@ -4622,6 +4628,7 @@ liquify-list-end {0}, {1} {0}, {1}
@msg Divide Objects Below: select exactly one path Dividir objetos inferiores: selecciona exactamente un trazado
@msg Downloaded {what} Se descargó {what}
@msg Expand Appearance: the selection has a basic appearance Expandir apariencia: la selección tiene una apariencia básica
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all algunos efectos ráster no se convirtieron en imágenes: ocuparían más de 1024 imágenes o 256 megapíxeles en total
@msg Expand: no brush strokes selected Expandir: no hay trazos de pincel seleccionados
@msg Expand: no gradient fills Expandir: no hay rellenos de degradado
@msg Expand: nothing to expand Expandir: no hay nada que expandir
@@ -6323,7 +6330,7 @@ mark-style Japanese Japonesas
@msg Unknown dimension style Estilo de cota desconocido
@msg Unknown unit Unidad desconocida
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Cierra los extremos circulares de los perfiles abiertos. Los giros parciales mantienen abiertos sus lados de corte.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Cierra los extremos circulares de los perfiles abiertos. Los giros parciales también cierran sus lados de corte.
Distance Distancia
@msg span must be "object" or "selection", got {v} span debe ser "object" o "selection", no {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" coloca un `gradient`, no una muestra
@@ -6476,6 +6483,7 @@ mark-style Japanese Japonesas
Single Word Justification: Justificación de una sola palabra:
Full Justify Justificar completamente
Minimum must not exceed Desired, nor Desired Maximum. El mínimo no puede superar el deseado, ni el deseado el máximo.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: el mínimo no puede superar el deseado, ni el deseado el máximo
Justification Justificación
Add filters from the list above Añada filtros de la lista de arriba
Add to Stack Añadir a la pila
@@ -7487,7 +7495,7 @@ breakText Glyphs Glifos
@msg stroke cannot be set on a symbol instance stroke no se puede definir en una instancia de símbolo
@msg fill on a symbol instance must be a solid color or none el fill de una instancia de símbolo debe ser un color sólido o none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} no se puede definir en una imagen sin el efecto Convertir en forma o Contornear objeto
@msg pass newName, registration, exportType, nineSlice and/or type indique newName, registration, exportType, nineSlice y/o type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indique newName, registration, exportType, nineSlice, type y/o alignToPixelGrid
Text Flow Flujo de texto
By Rows Por filas
By Columns Por columnas
Can't render this file because it contains an unexpected character in line 2 and column 73.
+10 -2
View File
@@ -1722,6 +1722,10 @@ digits Malayalam Malajalam
Em Box Em-laatikko
x-Height x-korkeus
ICF Box ICF-laatikko
Show Sample Näytä näyte
Hide Sample Piilota näyte
Max Ascent/Descent Suurin korkeus/syvyys
Max Ascender Suurin yläpidennys
Copy Color Value (Hex) Kopioi väriarvo (heksa)
Create New Swatch… Luo uusi värimalli…
Name 40% Nimi 40%
@@ -3635,6 +3639,8 @@ theme Appearance Ulkoasu
Find Font Files Etsi fonttitiedostoja
Add Font Files Lisää fonttitiedostoja
Font List Fonttiluettelo
Show Similar Fonts Näytä samankaltaiset fontit
Clear Similar Fonts Tyhjennä samankaltaiset fontit
Fonts in Document Asiakirjan fontit
Refresh Font List Päivitä fonttiluettelo
Replace Font Korvaa fontti
@@ -4855,6 +4861,7 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg Divide Objects Below: select exactly one path Jaa alla olevat objektit: valitse tasan yksi polku
@msg Downloaded {what} Ladattiin {what}
@msg Expand Appearance: the selection has a basic appearance Laajenna ulkoasu: valinnalla on perusulkoasu
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all joitakin rasteritehosteita ei muunnettu kuviksi: ne veisivät yli 1 024 kuvaa tai yhteensä 256 megapikseliä
@msg Expand: no brush strokes selected Laajenna: sivellinviivoja ei ole valittu
@msg Expand: no gradient fills Laajenna: ei liukuväritäyttöjä
@msg Expand: nothing to expand Laajenna: ei laajennettavaa
@@ -6244,7 +6251,7 @@ mark-style Japanese Japanilainen
By Object Objektin mukaan
Check an artboard to save. Valitse tallennettava piirtoalusta.
Clear All Tyhjennä kaikki
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Sulje avointen profiilien pyöreät päät. Osittaiset pyöräytykset jättävät leikkauspintansa auki.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Sulje avointen profiilien pyöreät päät. Osittaiset pyöräytykset sulkevat myös leikkauspintansa.
Color Panel Options Väri-paneelin asetukset
Color blindness – Tritanopia-type Värisokeus – tritanopia
Create Dimension Luo mitta
@@ -6498,6 +6505,7 @@ mark-style Japanese Japanilainen
Single Word Justification: Yksittäisen sanan tasaus:
Full Justify Täysi tasaus
Minimum must not exceed Desired, nor Desired Maximum. Minimi ei saa ylittää haluttua arvoa eikä haluttu arvo maksimia.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimi ei saa ylittää haluttua arvoa eikä haluttu arvo maksimia
Justification Tasaus
Add filters from the list above Lisää suodattimia yllä olevasta luettelosta
Add to Stack Lisää pinoon
@@ -7575,7 +7583,7 @@ breakText Glyphs Merkit
@msg stroke cannot be set on a symbol instance stroke-arvoa ei voi asettaa symbolin ilmentymälle
@msg fill on a symbol instance must be a solid color or none symbolin ilmentymän fill-arvon on oltava tasainen väri tai none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key}-arvoa ei voi asettaa kuvalle, jolla ei ole tehostetta Muunna muodoksi tai Muunna objekti ääriviivoiksi
@msg pass newName, registration, exportType, nineSlice and/or type anna newName, registration, exportType, nineSlice ja/tai type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid anna newName, registration, exportType, nineSlice, type ja/tai alignToPixelGrid
Text Flow Tekstin kulku
By Rows Riveittäin
By Columns Sarakkeittain
Can't render this file because it contains an unexpected character in line 2 and column 73.
+12 -2
View File
@@ -1343,6 +1343,8 @@ font-technology Variable Variables
Font Family & Style Famille et style de police
Font Family, Style & Size Famille, style et taille de police
Font List Liste des polices
Show Similar Fonts Afficher les polices similaires
Clear Similar Fonts Effacer les polices similaires
Font Preview Size Taille de l’aperçu des polices
Font Size Taille de police
Variable Font Police variable
@@ -4587,6 +4589,7 @@ liquify-list-end {0}, {1} {0} et {1}
@msg select a path sélectionnez un tracé
@msg Divide Objects Below: select exactly one path Diviser les objets inférieurs : sélectionnez exactement un tracé
@msg Downloaded {what} {what} téléchargé
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all certains effets pixellisés n’ont pas été convertis en images, car ils occuperaient plus de 1024 images ou 256 mégapixels au total
@msg Expand Appearance: the selection has a basic appearance Décomposer l’aspect : la sélection a un aspect de base
@msg Expand: no brush strokes selected Décomposer : aucun contour de forme sélectionné
@msg Expand: no gradient fills Décomposer : aucun fond en dégradé
@@ -5420,6 +5423,10 @@ liquify-list-end {0}, {1} {0} et {1}
Em Box Cadratin
x-Height Hauteur d’x
ICF Box Cadre ICF
Show Sample Afficher l'échantillon
Hide Sample Masquer l'échantillon
Max Ascent/Descent Hauteur/profondeur max.
Max Ascender Jambage ascendant max.
ICF Top/Right ICF haut/droite
ICF Bottom/Left ICF bas/gauche
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` est la référence d’étape {r}, que seuls `run` et `command_batch` résolvent
@@ -6351,7 +6358,7 @@ theme Appearance Apparence
@msg Unknown dimension style Style de cote inconnu
@msg Unknown unit Unité inconnue
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Ferme les extrémités circulaires des profils ouverts. Les rotations partielles conservent leurs faces de coupe ouvertes.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Ferme les extrémités circulaires des profils ouverts. Les rotations partielles ferment aussi leurs faces de coupe.
@msg span must be "object" or "selection", got {v} span doit être "object" ou "selection", pas {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" place un `gradient`, pas une nuance
@msg span: "selection" places a gradient: give `gradient` span: "selection" place un dégradé : indiquez `gradient`
@@ -6503,6 +6510,7 @@ theme Appearance Apparence
Single Word Justification: Justification d’un mot isolé :
Full Justify Justification complète
Minimum must not exceed Desired, nor Desired Maximum. Le minimum ne doit pas dépasser la valeur optimale, ni la valeur optimale le maximum.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}` : le minimum ne doit pas dépasser la valeur optimale, ni la valeur optimale le maximum
Justification Justification
Add filters from the list above Ajoutez des filtres à partir de la liste ci-dessus
Add to Stack Ajouter à la pile
@@ -7512,7 +7520,7 @@ breakText Glyphs Glyphes
@msg stroke cannot be set on a symbol instance stroke ne peut pas être défini sur une instance de symbole
@msg fill on a symbol instance must be a solid color or none le fill d’une instance de symbole doit être une couleur unie ou none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} ne peut pas être défini sur une image sans l’effet Convertir en forme ou Vectoriser l’objet
@msg pass newName, registration, exportType, nineSlice and/or type indiquez newName, registration, exportType, nineSlice et/ou type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indiquez newName, registration, exportType, nineSlice, type et/ou alignToPixelGrid
Text Flow Flux du texte
By Rows Par lignes
By Columns Par colonnes
@@ -8973,7 +8981,9 @@ breakText Glyphs Glyphes
@msg position must be normal, superscript or subscript position doit valoir normal, superscript ou subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position doit valoir topLeft, topRight, bottomLeft ou bottomRight
@msg positions must be between 0 and 100000 pt les positions doivent être comprises entre 0 et 100000 pt
@msg ppi can't be more than {max} for this image ppi ne peut pas dépasser {max} pour cette image
@msg ppi must be a positive number, not {ppi} ppi doit être un nombre positif, pas {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim conserve les pixels de l’image tels quels : omettez ppi
@msg ppi must be between 1 and 2400 ppi doit être compris entre 1 et 2400
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` n’est pas transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape doit valoir clippingMask|transparency
Can't render this file because it is too large.
+7 -1
View File
@@ -608,7 +608,7 @@
Close Path… પાથ બંધ કરો…
Close or Join બંધ કરો અથવા જોડો
Close paths when ends are within: છેડા આ અંતરમાં હોય ત્યારે પાથ બંધ કરો:
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. ખુલ્લી પ્રોફાઇલના ગોળ છેડા બંધ કરો. આંશિક સ્વીપ તેમની કાપેલી બાજુઓ ખુલ્લી રાખે છે.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. ખુલ્લી પ્રોફાઇલના ગોળ છેડા બંધ કરો. આંશિક સ્વીપ તેમની કાપેલી બાજુઓ પણ બંધ કરે છે.
Closing bracket with no opening one ખુલતા કૌંસ વગરનો બંધ થતો કૌંસ
Coincidence: સંયોગ:
Collapse Panel Group પેનલ ગ્રૂપ સંકોચો
@@ -1458,6 +1458,8 @@
Font Family, Style & Size ફોન્ટ ફેમિલી, સ્ટાઇલ અને સાઇઝ
Font Family: ફોન્ટ ફેમિલી:
Font List ફોન્ટ યાદી
Show Similar Fonts સમાન ફોન્ટ બતાવો
Clear Similar Fonts સમાન ફોન્ટ સાફ કરો
Font Preview Size ફોન્ટ પૂર્વાવલોકન સાઇઝ
Font Size ફોન્ટ સાઇઝ
Font Style: ફોન્ટ સ્ટાઇલ:
@@ -1739,6 +1741,10 @@
ICC Profile ICC પ્રોફાઇલ
ICF Bottom/Left ICF નીચે/ડાબે
ICF Box ICF બૉક્સ
Show Sample નમૂનો બતાવો
Hide Sample નમૂનો છુપાવો
Max Ascent/Descent મહત્તમ એસેન્ટ/ડિસેન્ટ
Max Ascender મહત્તમ એસેન્ડર
ICF Top/Right ICF ઉપર/જમણે
ID: {id} ID: {id}
Identify Objects By ઑબ્જેક્ટ્સ આ રીતે ઓળખો
Can't render this file because it contains an unexpected character in line 72 and column 5.
+11 -2
View File
@@ -881,7 +881,7 @@ antiAlias Sharp शार्प
Close Path: बंद पाथ:
Close Path… बंद पाथ…
Close paths when ends are within: जब समाप्त होता है तो बंद पाथ भीतर होते हैं:
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. खुली प्रोफ़ाइल के गोल सिरे बंद करें। आंशिक स्वीप की कटी हुई साइड खुली रहती हैं।
Close the circular ends of open profiles. Partial sweeps also close their cut sides. खुली प्रोफ़ाइल के गोल सिरे बंद करें। आंशिक स्वीप की कटी हुई साइड भी बंद होती हैं।
Closed बंद
Closing bracket with no opening one बंद करने वाला ब्रैकेट, जिसका कोई खोलने वाला ब्रैकेट नहीं है
Clumped गुच्छेदार
@@ -2005,6 +2005,8 @@ antiAlias Sharp शार्प
Font Family, Style & Size फ़ॉन्ट परिवार, स्टाइल और आकार
Font Family: फ़ॉन्ट परिवार:
Font List फ़ॉन्ट सूची
Show Similar Fonts समान फ़ॉन्ट दिखाएँ
Clear Similar Fonts समान फ़ॉन्ट साफ़ करें
Font Preview Size फ़ॉन्ट प्रीव्यू साइज़
Font Size फ़ॉन्ट साइज़
Font Size: फ़ॉन्ट साइज़:
@@ -2375,6 +2377,10 @@ antiAlias Sharp शार्प
ICC Profile ICC प्रोफ़ाइल
ICF Bottom/Left ICF बॉटम/लेफ्ट
ICF Box ICF बॉक्स
Show Sample नमूना दिखाएँ
Hide Sample नमूना छिपाएँ
Max Ascent/Descent अधिकतम एसेंट/डिसेंट
Max Ascender अधिकतम एसेंडर
ICF Top/Right ICF ऊपर/दाएँ
Identify Objects By ऑब्जेक्ट्स की पहचान करके
If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. अगर ड्रॉइंग टैबलेट के पेन से ड्रॉ नहीं हो रहा, तो X11 (XWayland) ऑप्शन चुनें।
@@ -7064,6 +7070,7 @@ liquify-list-end {0}, {1} {0} और {1}
@msg every search thread stopped on an internal error (please report this bug) प्रत्येक खोज धागा एक आंतरिक त्रुटि पर बंद कर दिया (कृपया इस बग की रिपोर्ट करें)
@msg exit isolation mode first पहले अलगाव मोड से बाहर निकलें
@msg Expand Appearance: the selection has a basic appearance उपस्थिति का विस्तार: सिलेक्शन में एक बुनियादी उपस्थिति है
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all कुछ रास्टर इफ़ेक्ट इमेज में नहीं बदले गए: उनके लिए 1,024 से अधिक इमेज या कुल 256 मेगापिक्सेल लगते
@msg Expand: no brush strokes selected विस्तार: सिलेक्टेड कोई ब्रश स्ट्रोक नहीं
@msg Expand: no gradient fills एक्सपैंड: कोई ग्रेडिएंट फ़िल नहीं
@msg Expand: nothing to expand विस्तार: विस्तार करने के लिए कुछ नहीं
@@ -7911,7 +7918,7 @@ liquify-list-end {0}, {1} {0} और {1}
@msg parameters must be an object parameters एक ऑब्जेक्ट होना चाहिए
@msg params must be an object params एक ऑब्जेक्ट होना चाहिए
@msg part of the program isn't valid PostScript text कार्यक्रम का हिस्सा मान्य नहीं है PostScript टेक्स्ट
@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice और/या type दें
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type और/या alignToPixelGrid दें
@msg passwords can have up to {MAX_PASSWORD} bytes पासवर्ड {MAX_PASSWORD} बाइट्स तक हो सकता है
@msg paste unavailable पेस्ट करें अनुपलब्ध
@msg Pasting चिपकाना
@@ -7964,7 +7971,9 @@ liquify-list-end {0}, {1} {0} और {1}
@msg position must be normal, superscript or subscript position normal, superscript या subscript होना चाहिए
@msg position must be topLeft, topRight, bottomLeft or bottomRight position को topLeft, topRight, bottomLeft या bottomRight होना चाहिए
@msg positions must be between 0 and 100000 pt positions 0 और 100000 pt के बीच होनी चाहिए
@msg ppi can't be more than {max} for this image इस छवि के लिए ppi {max} से अधिक नहीं हो सकता
@msg ppi must be a positive number, not {ppi} ppi एक धनात्मक संख्या होनी चाहिए, {ppi} नहीं
@msg trim keeps the image's pixels as they are: leave out ppi trim छवि के पिक्सेल जैसे हैं वैसे ही रखता है: ppi न दें
@msg ppi must be between 1 and 2400 ppi 1 और 2400 के बीच होना चाहिए
@msg precision must be from 0.001 to 10 pt precision 0.001 से 10 pt तक होनी चाहिए
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill में से नहीं है
Can't render this file because it is too large.
+12 -2
View File
@@ -1678,6 +1678,8 @@ file-filter Templates Sablonok
Font Family & Style Betűcsalád és stílus
Font Family, Style & Size Betűcsalád, stílus és méret
Font List Betűtípuslista
Show Similar Fonts Hasonló betűtípusok megjelenítése
Clear Similar Fonts Hasonló betűtípusok törlése
Font Preview Size Betűtípus-előnézet mérete
Font Size Betűméret
Variable Font Változó betűtípus
@@ -2155,6 +2157,10 @@ file-filter Templates Sablonok
Em Box Kvirtmező
x-Height x-magasság
ICF Box ICF-mező
Show Sample Minta megjelenítése
Hide Sample Minta elrejtése
Max Ascent/Descent Max. magasság/mélység
Max Ascender Max. felnyúló szár
ICF Top/Right ICF teteje/jobb oldala
Identify Objects By Objektumok azonosítása
Ignore Kihagy
@@ -5440,6 +5446,7 @@ liquify-list-end {0}, {1} {0} és {1}
@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it egy diagram adatsorában a diagramminta grafikája a mintából rajzolódik újra: a módosításához szerkeszd a mintát
@msg every search thread stopped on an internal error (please report this bug) minden keresési szál belső hibával leállt (kérjük, jelentsd ezt a hibát)
@msg Expand Appearance: the selection has a basic appearance Megjelenés kibontása: a kijelölésnek alapmegjelenése van
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all néhány raszteres effektus nem lett képpé alakítva: több mint 1024 képet vagy összesen 256 megapixelt foglalnának
@msg Expand: no brush strokes selected Kibontás: nincs kijelölt ecsetvonás
@msg Expand: no gradient fills Kibontás: nincs színátmenetes kitöltés
@msg Expand: nothing to expand Kibontás: nincs mit kibontani
@@ -6339,7 +6346,7 @@ liquify-list-end {0}, {1} {0} és {1}
@msg Unknown dimension style Ismeretlen méretezési stílus
@msg Unknown unit Ismeretlen mértékegység
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Nyitott profilok kör alakú végeinek lezárása. Részleges körforgatás esetén a vágott oldalak nyitva maradnak.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Nyitott profilok kör alakú végeinek lezárása. Részleges körforgatás esetén a vágott oldalak is lezáródnak.
Distance Távolság
@msg span must be "object" or "selection", got {v} a span értéke "object" vagy "selection" lehet, nem {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" egy `gradient` értéket helyez el, nem színmintát
@@ -6492,6 +6499,7 @@ liquify-list-end {0}, {1} {0} és {1}
Single Word Justification: Egyetlen szó igazítása:
Full Justify Teljes sorkizárás
Minimum must not exceed Desired, nor Desired Maximum. A minimum nem haladhatja meg a kívánt értéket, sem a kívánt érték a maximumot.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: a minimum nem haladhatja meg a kívánt értéket, sem a kívánt érték a maximumot
Justification Sorkizárás
Add filters from the list above Adjon hozzá szűrőket a fenti listából
Add to Stack Hozzáadás a veremhez
@@ -7502,7 +7510,7 @@ breakText Glyphs Glifák
@msg stroke cannot be set on a symbol instance a stroke nem állítható be szimbólumpéldányon
@msg fill on a symbol instance must be a solid color or none a szimbólumpéldány fill értéke csak egyszínű szín vagy none lehet
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it a {key} nem állítható be olyan képen, amelyen nincs Átalakítás alakzattá vagy Objektum útvonallá alakítása effektus
@msg pass newName, registration, exportType, nineSlice and/or type adja meg a newName, registration, exportType, nineSlice és/vagy type értékét
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid adja meg a newName, registration, exportType, nineSlice, type és/vagy alignToPixelGrid értékét
Text Flow Szövegfolyás
By Rows Soronként
By Columns Oszloponként
@@ -8983,7 +8991,9 @@ breakText Glyphs Glifák
@msg position must be normal, superscript or subscript position: normal, superscript vagy subscript kell
@msg position must be topLeft, topRight, bottomLeft or bottomRight position: topLeft, topRight, bottomLeft vagy bottomRight kell
@msg positions must be between 0 and 100000 pt positions: 0 és 100000 pt közötti értékek kellenek
@msg ppi can't be more than {max} for this image ppi: ennél a képnél legfeljebb {max} lehet
@msg ppi must be a positive number, not {ppi} ppi: pozitív szám kell, ez nem az: {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi a trim változatlanul hagyja a kép képpontjait: hagyja el a ppi értéket
@msg ppi must be between 1 and 2400 ppi: 1 és 2400 közötti érték kell
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`: nem transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape: clippingMask|transparency kell
Can't render this file because it is too large.
+8 -2
View File
@@ -1605,6 +1605,10 @@ digits Malayalam Malayalam
Em Box Em Box
x-Height Tinggi x
ICF Box Kotak ICF
Show Sample Tampilkan contoh
Hide Sample Sembunyikan contoh
Max Ascent/Descent Tinggi/kedalaman maks.
Max Ascender Ascender maks.
Copy Color Value (Hex) Salin nilai warna (Hex)
Create New Swatch… Buat swatch baru…
Name 40% Nama 40%
@@ -3371,6 +3375,8 @@ theme Appearance Tampilan
Find Font Files Cari file font
Add Font Files Tambahkan file font
Font List Daftar font
Show Similar Fonts Tampilkan font serupa
Clear Similar Fonts Hapus font serupa
Fonts in Document Font dalam dokumen
Refresh Font List Segarkan daftar font
Replace Font Ganti font
@@ -5657,7 +5663,7 @@ mark-style Japanese Jepang
@msg Unknown dimension orientation Orientasi dimensi tidak dikenal
@msg Unknown dimension style Gaya dimensi tidak dikenal
@msg Unknown unit Satuan tidak dikenal
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Menutup ujung melingkar profil terbuka. Sapuan parsial mempertahankan sisi potongannya tetap terbuka.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Menutup ujung melingkar profil terbuka. Sapuan parsial juga menutup sisi potongannya.
Darkness Kegelapan
Isolate Selected Object Isolasikan objek terpilih
Keep selected Tetap terseleksi
@@ -6840,7 +6846,7 @@ breakText Glyphs Glif
@msg stroke cannot be set on a symbol instance stroke tidak dapat diatur pada instans simbol
@msg fill on a symbol instance must be a solid color or none fill pada instans simbol harus berupa warna solid atau none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} tidak dapat diatur pada gambar tanpa efek Konversi ke bentuk atau Kerangka objek
@msg pass newName, registration, exportType, nineSlice and/or type berikan newName, registration, exportType, nineSlice dan/atau type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid berikan newName, registration, exportType, nineSlice, type dan/atau alignToPixelGrid
Text Flow Alur teks
By Rows Per baris
By Columns Per kolom
Can't render this file because it contains an unexpected character in line 2488 and column 5.
+12 -2
View File
@@ -1045,6 +1045,10 @@ font-technology Variable Variabili
Cap Height Altezza maiuscole
x-Height Altezza x
ICF Box Riquadro ICF
Show Sample Mostra campione
Hide Sample Nascondi campione
Max Ascent/Descent Altezza/profondità max
Max Ascender Ascendente max
Em Dash Lineetta
Em Space Spazio em
Embed Incorpora
@@ -1368,6 +1372,8 @@ file-filter Templates Modelli
Font Family & Style Famiglia e stile font
Font Family, Style & Size Famiglia, stile e dimensione font
Font List Elenco font
Show Similar Fonts Mostra font simili
Clear Similar Fonts Cancella font simili
Font Preview Size Dimensione anteprima font
Font Size Dimensione font
Variable Font Font variabile
@@ -4650,6 +4656,7 @@ liquify-list-end {0}, {1} {0} e {1}
@msg Divide Objects Below: select exactly one path Dividi oggetti sottostanti: seleziona esattamente un tracciato
@msg Downloaded {what} Scaricato {what}
@msg Expand Appearance: the selection has a basic appearance Espandi aspetto: la selezione ha un aspetto di base
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alcuni effetti raster non sono stati trasformati in immagini: richiederebbero più di 1.024 immagini o 256 megapixel in totale
@msg Expand: no brush strokes selected Espandi: nessuna traccia di pennello selezionata
@msg Expand: no gradient fills Espandi: nessun riempimento con sfumatura
@msg Expand: nothing to expand Espandi: niente da espandere
@@ -5974,7 +5981,7 @@ lighting Light Luce
@msg Unknown dimension style Stile di quota sconosciuto
@msg Unknown unit Unità sconosciuta
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Chiude le estremità circolari dei profili aperti. Le rotazioni parziali mantengono aperti i lati di taglio.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Chiude le estremità circolari dei profili aperti. Le rotazioni parziali chiudono anche i lati di taglio.
Distance Distanza
@msg span must be "object" or "selection", got {v} span deve essere "object" o "selection", non {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" posiziona un `gradient`, non un campione
@@ -6126,6 +6133,7 @@ lighting Light Luce
Single Word Justification: Giustificazione parola singola:
Full Justify Giustificazione completa
Minimum must not exceed Desired, nor Desired Maximum. Il minimo non può superare il valore desiderato, né il desiderato il massimo.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: il minimo non può superare il valore desiderato, né il desiderato il massimo
Minimum Minimo
Justification Giustificazione
Add filters from the list above Aggiungi filtri dall'elenco sopra
@@ -7144,7 +7152,7 @@ breakText Glyphs Glifi
@msg stroke cannot be set on a symbol instance stroke non può essere impostato su un’istanza di simbolo
@msg fill on a symbol instance must be a solid color or none il fill di un’istanza di simbolo deve essere un colore pieno o none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} non può essere impostato su un’immagine senza l’effetto Converti in forma o Contorna oggetto
@msg pass newName, registration, exportType, nineSlice and/or type specifica newName, registration, exportType, nineSlice e/o type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid specifica newName, registration, exportType, nineSlice, type e/o alignToPixelGrid
Text Flow Flusso del testo
By Rows Per righe
By Columns Per colonne
@@ -8742,7 +8750,9 @@ breakText Glyphs Glifi
@msg position must be normal, superscript or subscript position deve essere normal, superscript o subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position deve essere topLeft, topRight, bottomLeft o bottomRight
@msg positions must be between 0 and 100000 pt le posizioni devono essere comprese tra 0 e 100000 pt
@msg ppi can't be more than {max} for this image ppi non può superare {max} per questa immagine
@msg ppi must be a positive number, not {ppi} ppi deve essere un numero positivo, non {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim mantiene i pixel dell'immagine così come sono: ometti ppi
@msg ppi must be between 1 and 2400 ppi deve essere compreso tra 1 e 2400
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` non è transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape deve essere clippingMask|transparency
Can't render this file because it is too large.
+12 -2
View File
@@ -49,6 +49,10 @@ font-technology Variable バリアブル
Cap Height キャップハイト
x-Height x ハイト
ICF Box 平均字面
Show Sample サンプルを表示
Hide Sample サンプルを隠す
Max Ascent/Descent 最大アセント/ディセント
Max Ascender 最大アセンダ
Proportional Metrics プロポーショナルメトリクス
H or V Style 横組み・縦組み用かな
Roman Italics 欧文イタリック
@@ -1862,6 +1866,8 @@ antiAlias Sharp シャープ
Folder フォルダー
Folder Name: フォルダー名:
Font List フォントリスト
Show Similar Fonts 類似フォントを表示
Clear Similar Fonts 類似フォントの表示を解除
Font Preview Size フォントプレビューのサイズ
Font: フォント:
Fonts フォント
@@ -4619,6 +4625,7 @@ swatch Bright Violet ビビッドバイオレット
@msg no history to clear 消去するヒストリーがありません
@msg no history state {v} ヒストリーの状態 {v} はありません
@msg Expand Appearance: the selection has a basic appearance アピアランスを分割: 選択範囲は基本アピアランスです
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 一部のラスター効果は画像になりませんでした: 1,024 枚または合計 256 メガピクセルを超えるためです
@msg select (or target) objects whose appearance isn't basic 基本アピアランスではないオブジェクトを選択するか、ターゲットに指定してください
@msg {C}: no effect at index {from} {C}: インデックス {from} に効果がありません
@msg Expand: no gradient fills 拡張: グラデーションの塗りがありません
@@ -6019,7 +6026,7 @@ lighting Light ライト
@msg Unknown dimension style 寸法のスタイルが不明です
@msg Unknown unit 単位が不明です
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 開いたプロファイルの円形の端を閉じます。部分的な回転では切断面は開いたままです。
Close the circular ends of open profiles. Partial sweeps also close their cut sides. 開いたプロファイルの円形の端を閉じます。部分的な回転では切断面も閉じます。
Distance 距離
@msg span must be "object" or "selection", got {v} span は "object" または "selection" で指定してください ({v} は指定できません)
@msg span: "selection" places a `gradient`, not a swatch span: "selection" は `gradient` を配置します。スウォッチは配置できません
@@ -6173,6 +6180,7 @@ lighting Light ライト
Single Word Justification: 単語のみの行の揃え:
Full Justify 両端揃え
Minimum must not exceed Desired, nor Desired Maximum. 最小値は最適値を、最適値は最大値を超えることはできません。
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: 最小値は最適値を、最適値は最大値を超えることはできません
Minimum 最小
Justification 文字組み
Add filters from the list above 上のリストからフィルターを追加
@@ -7925,7 +7933,9 @@ axis Y Axis Y 軸
@msg position must be normal, superscript or subscript position には normal、superscript、subscript のいずれかを指定してください
@msg position must be topLeft, topRight, bottomLeft or bottomRight position には topLeft、topRight、bottomLeft、bottomRight のいずれかを指定してください
@msg positions must be between 0 and 100000 pt positions には 0 から 100000 pt までの値を指定してください
@msg ppi can't be more than {max} for this image この画像の ppi には {max} 以下の値を指定してください
@msg ppi must be a positive number, not {ppi} ppi には正の数値を指定してください ({ppi} は指定できません)
@msg trim keeps the image's pixels as they are: leave out ppi trim は画像のピクセルをそのまま残します: ppi は指定しないでください
@msg ppi must be between 1 and 2400 ppi には 1 から 2400 までの値を指定してください
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` は transforms|bounds|fileDimensions|fit|fill のいずれでもありません
@msg preserveShape must be clippingMask|transparency preserveShape には clippingMask|transparency のいずれかを指定してください
@@ -9021,7 +9031,7 @@ breakText Glyphs 字形
@msg stroke cannot be set on a symbol instance シンボルインスタンスには stroke を設定できません
@msg fill on a symbol instance must be a solid color or none シンボルインスタンスの fill は単色または none にしてください
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 「シェイプに変換」または「オブジェクトのアウトライン」効果のない画像には {key} を設定できません
@msg pass newName, registration, exportType, nineSlice and/or type newName、registration、exportType、nineSlice、type のいずれかを指定してください
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName、registration、exportType、nineSlice、type、alignToPixelGrid のいずれかを指定してください
Text Flow テキストの流れ
By Rows 行方向
By Columns 列方向
Can't render this file because it is too large.
+9 -2
View File
@@ -3670,6 +3670,10 @@ digits Malayalam მალაიალამური
Em Box Em-ბლოკი
x-Height x-სიმაღლე
ICF Box ICF-ბლოკი
Show Sample ნიმუშის ჩვენება
Hide Sample ნიმუშის დამალვა
Max Ascent/Descent მაქს. სიმაღლე/სიღრმე
Max Ascender მაქს. ზედა გამონაშვერი
Copy Color Value (Hex) ფერის მნიშვნელობის კოპირება (Hex)
Create New Swatch… ახალი ფერის ნიმუშის შექმნა…
Name 40% სახელი 40%
@@ -5351,6 +5355,8 @@ theme Appearance იერსახე
Find Font Files შრიფტის ფაილების ძებნა
Add Font Files შრიფტის ფაილების დამატება
Font List შრიფტების სია
Show Similar Fonts მსგავსი შრიფტების ჩვენება
Clear Similar Fonts მსგავსი შრიფტების გასუფთავება
Fonts in Document დოკუმენტის შრიფტები
Refresh Font List შრიფტების სიის განახლება
Replace Font შრიფტის ჩანაცვლება
@@ -6341,6 +6347,7 @@ font-technology Variable ცვლადი
@msg Divide Objects Below: select exactly one path ქვედა ობიექტების დაყოფა: მონიშნეთ ზუსტად ერთი ტრაექტორია
@msg Downloaded {what} ჩამოტვირთულია: {what}
@msg Expand Appearance: the selection has a basic appearance იერსახის გაშლა: მონიშნულს საბაზისო იერსახე აქვს
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all ზოგიერთი რასტრული ეფექტი გამოსახულებად არ გადაიქცა: მათ დასჭირდებოდა 1024-ზე მეტი გამოსახულება ან ჯამში 256 მეგაპიქსელი
@msg Expand: no brush strokes selected გაშლა: ფუნჯის შტრიხები მონიშნული არ არის
@msg Expand: no gradient fills გაშლა: გრადიენტული შევსებები არ არის
@msg Expand: nothing to expand გაშლა: გასაშლელი არაფერია
@@ -8061,7 +8068,7 @@ liquify-list-end {0}, {1} {0} და {1}
@msg Unknown dimension orientation ზომის უცნობი ორიენტაცია
@msg Unknown dimension style ზომის უცნობი სტილი
@msg Unknown unit უცნობი ერთეული
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. ღია პროფილების წრიული ბოლოების დახურვა. ნაწილობრივი ბრუნვისას ჭრის მხარეები ღია რჩება.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. ღია პროფილების წრიული ბოლოების დახურვა. ნაწილობრივი ბრუნვისას ჭრის მხარეებიც იხურება.
Distance მანძილი
# Upstream sync 2026-10-16 (2): Smart Blur modes, Layers panel filter, Color panel options, templates, PostScript files.
Mode რეჟიმი
@@ -9652,7 +9659,7 @@ breakText Glyphs გლიფები
@msg stroke cannot be set on a symbol instance stroke ვერ დაყენდება სიმბოლოს ეგზემპლარზე
@msg fill on a symbol instance must be a solid color or none სიმბოლოს ეგზემპლარის fill უნდა იყოს ერთფეროვანი ფერი ან none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} ვერ დაყენდება გამოსახულებაზე „ფიგურად გარდაქმნის“ ან „ობიექტის კონტურებად გარდაქმნის“ ეფექტის გარეშე
@msg pass newName, registration, exportType, nineSlice and/or type მიუთითეთ newName, registration, exportType, nineSlice და/ან type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid მიუთითეთ newName, registration, exportType, nineSlice, type და/ან alignToPixelGrid
Text Flow ტექსტის დინება
By Rows სტრიქონების მიხედვით
By Columns სვეტების მიხედვით
Can't render this file because it is too large.
+12 -2
View File
@@ -43,6 +43,10 @@ font-technology Variable 가변
Cap Height 대문자 높이
x-Height x 높이
ICF Box ICF 박스
Show Sample 샘플 표시
Hide Sample 샘플 숨기기
Max Ascent/Descent 최대 어센트/디센트
Max Ascender 최대 어센더
Proportional Metrics 비례 메트릭
H or V Style 가로 또는 세로 스타일
Roman Italics 로마자 이탤릭
@@ -1852,6 +1856,8 @@ antiAlias Sharp 날카롭게
Folder 폴더
Folder Name: 폴더 이름:
Font List 글꼴 목록
Show Similar Fonts 유사한 글꼴 표시
Clear Similar Fonts 유사한 글꼴 지우기
Font Preview Size 글꼴 미리 보기 크기
Font: 글꼴:
Fonts 글꼴
@@ -4546,6 +4552,7 @@ theme Appearance 외관
@msg no history to clear 지울 히스토리가 없습니다
@msg no history state {v} 히스토리 상태 {v}이(가) 없습니다
@msg Expand Appearance: the selection has a basic appearance 모양새 확장: 선택 항목은 기본 모양새입니다
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 일부 래스터 효과는 이미지로 만들지 않았습니다: 이미지 1,024개 또는 총 256메가픽셀을 넘기 때문입니다
@msg select (or target) objects whose appearance isn't basic 모양새가 기본이 아닌 개체를 선택(또는 대상 지정)하세요
@msg {C}: no effect at index {from} {C}: 인덱스 {from}에 효과가 없습니다
@msg Expand: no gradient fills 확장: 그레이디언트 칠이 없습니다
@@ -5936,7 +5943,7 @@ lighting Light 광원
@msg Unknown dimension style 알 수 없는 치수 스타일
@msg Unknown unit 알 수 없는 단위
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 열린 프로파일의 원형 끝을 닫습니다. 부분 회전에서는 절단 측면이 열린 상태로 유지됩니다.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. 열린 프로파일의 원형 끝을 닫습니다. 부분 회전에서는 절단 측면도 닫힙니다.
Distance 거리
@msg span must be "object" or "selection", got {v} span은 "object" 또는 "selection"이어야 합니다. {v}은(는) 사용할 수 없습니다
@msg span: "selection" places a `gradient`, not a swatch span: "selection"은 `gradient`를 배치합니다. 견본은 배치할 수 없습니다
@@ -6090,6 +6097,7 @@ lighting Light 광원
Single Word Justification: 단일 단어 정렬:
Full Justify 강제 양쪽 정렬
Minimum must not exceed Desired, nor Desired Maximum. 최소값은 희망값을, 희망값은 최대값을 넘을 수 없습니다.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: 최소값은 희망값을, 희망값은 최대값을 넘을 수 없습니다
Minimum 최소
Justification 양끝 맞춤
Add filters from the list above 위 목록에서 필터 추가
@@ -7108,7 +7116,7 @@ breakText Glyphs 글리프
@msg stroke cannot be set on a symbol instance 심볼 인스턴스에는 stroke를 설정할 수 없습니다
@msg fill on a symbol instance must be a solid color or none 심볼 인스턴스의 fill은 단색 또는 none이어야 합니다
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 모양으로 변환 또는 개체 윤곽선화 효과가 없는 이미지에는 {key}을(를) 설정할 수 없습니다
@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice 및/또는 type을 지정하세요
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type 및/또는 alignToPixelGrid을 지정하세요
Text Flow 텍스트 흐름
By Rows 행 방향
By Columns 열 방향
@@ -8708,7 +8716,9 @@ breakText Glyphs 글리프
@msg position must be normal, superscript or subscript position은 normal, superscript 또는 subscript여야 합니다
@msg position must be topLeft, topRight, bottomLeft or bottomRight position은 topLeft, topRight, bottomLeft 또는 bottomRight여야 합니다
@msg positions must be between 0 and 100000 pt positions는 0에서 100000 pt 사이여야 합니다
@msg ppi can't be more than {max} for this image 이 이미지의 ppi는 {max}보다 클 수 없습니다
@msg ppi must be a positive number, not {ppi} ppi는 양수여야 합니다: {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim은 이미지의 픽셀을 그대로 유지합니다: ppi를 지정하지 마세요
@msg ppi must be between 1 and 2400 ppi는 1에서 2400 사이여야 합니다
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`은(는) transforms|bounds|fileDimensions|fit|fill이 아닙니다
@msg preserveShape must be clippingMask|transparency preserveShape는 clippingMask|transparency여야 합니다
Can't render this file because it is too large.
+12 -2
View File
@@ -2213,6 +2213,10 @@ digits Malayalam Malayalam
Em Box Em-vak
x-Height x-hoogte
ICF Box ICF-vak
Show Sample Voorbeeld tonen
Hide Sample Voorbeeld verbergen
Max Ascent/Descent Max. hoogte/diepte
Max Ascender Max. stijger
Copy Color Value (Hex) Kleurwaarde kopiëren (Hex)
Create New Swatch… Nieuw staal maken…
Name 40% Naam 40%
@@ -3986,6 +3990,8 @@ theme Appearance Vormgeving
Find Font Files Lettertypebestanden zoeken
Add Font Files Lettertypebestanden toevoegen
Font List Lettertypelijst
Show Similar Fonts Vergelijkbare lettertypen tonen
Clear Similar Fonts Vergelijkbare lettertypen wissen
Fonts in Document Lettertypen in document
Refresh Font List Lettertypelijst vernieuwen
Replace Font Lettertype vervangen
@@ -5022,6 +5028,7 @@ imageTrace Outline Contour
@msg Divide Objects Below: select exactly one path Objecten eronder verdelen: selecteer precies één pad
@msg Downloaded {what} {what} gedownload
@msg Expand Appearance: the selection has a basic appearance Vormgeving uitbreiden: de selectie heeft een basisvormgeving
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all sommige rastereffecten zijn niet omgezet in afbeeldingen: ze zouden meer dan 1.024 afbeeldingen of in totaal 256 megapixel nodig hebben
@msg Expand: no brush strokes selected Uitbreiden: geen penseelstreken geselecteerd
@msg Expand: no gradient fills Uitbreiden: geen verloopvullingen
@msg Expand: nothing to expand Uitbreiden: niets om uit te breiden
@@ -7011,7 +7018,9 @@ imageTrace Outline Contour
@msg position must be normal, superscript or subscript position moet normal, superscript of subscript zijn
@msg position must be topLeft, topRight, bottomLeft or bottomRight position moet topLeft, topRight, bottomLeft of bottomRight zijn
@msg positions must be between 0 and 100000 pt positions moeten tussen 0 en 100000 pt liggen
@msg ppi can't be more than {max} for this image ppi kan voor deze afbeelding niet hoger zijn dan {max}
@msg ppi must be a positive number, not {ppi} ppi moet een positief getal zijn, niet {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim laat de pixels van de afbeelding zoals ze zijn: laat ppi weg
@msg ppi must be between 1 and 2400 ppi moet tussen 1 en 2400 liggen
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` is niet transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape moet clippingMask|transparency zijn
@@ -8163,7 +8172,7 @@ mark-style Japanese Japans
@msg Unknown dimension orientation Onbekende maatlijnrichting
@msg Unknown dimension style Onbekende maatlijnstijl
@msg Unknown unit Onbekende eenheid
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Sluit de ronde uiteinden van open profielen. Gedeeltelijke omwentelingen houden hun afgesneden zijden open.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Sluit de ronde uiteinden van open profielen. Gedeeltelijke omwentelingen sluiten ook hun afgesneden zijden.
Darkness Donkerte
Isolate Selected Object Geselecteerd object isoleren
Keep selected Geselecteerd houden
@@ -8610,6 +8619,7 @@ swatch Bright Violet Felviolet
Single Word Justification: Uitvullen van één woord:
Full Justify Volledig uitvullen
Minimum must not exceed Desired, nor Desired Maximum. Minimum mag niet groter zijn dan Gewenst, en Gewenst niet groter dan Maximum.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum mag niet groter zijn dan Gewenst, en Gewenst niet groter dan Maximum
Justification Uitvullen
Add filters from the list above Voeg filters toe uit de lijst hierboven
Add to Stack Toevoegen aan stapel
@@ -9391,7 +9401,7 @@ breakText Glyphs Glyphs
@msg stroke cannot be set on a symbol instance stroke kan niet worden ingesteld op een symboolinstantie
@msg fill on a symbol instance must be a solid color or none fill van een symboolinstantie moet een egale kleur of none zijn
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan niet worden ingesteld op een afbeelding zonder het effect Converteren naar vorm of Object omtrekken
@msg pass newName, registration, exportType, nineSlice and/or type geef newName, registration, exportType, nineSlice en/of type op
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid geef newName, registration, exportType, nineSlice, type en/of alignToPixelGrid op
Text Flow Tekstdoorloop
By Rows Per rij
By Columns Per kolom
Can't render this file because it is too large.
+12 -2
View File
@@ -1661,6 +1661,10 @@ digits Malayalam Malajalam
Em Box Ramka firetowa
x-Height Wysokość x
ICF Box Ramka ICF
Show Sample Pokaż próbkę
Hide Sample Ukryj próbkę
Max Ascent/Descent Maks. wysokość/głębokość
Max Ascender Maks. wydłużenie górne
Copy Color Value (Hex) Kopiuj wartość koloru (hex)
Create New Swatch… Utwórz nową próbkę…
Name 40% Nazwa 40%
@@ -3576,6 +3580,8 @@ theme Appearance Wygląd
Find Font Files Znajdź pliki czcionek
Add Font Files Dodaj pliki czcionek
Font List Lista czcionek
Show Similar Fonts Pokaż podobne czcionki
Clear Similar Fonts Wyczyść podobne czcionki
Fonts in Document Czcionki w dokumencie
Refresh Font List Odśwież listę czcionek
Replace Font Zastąp czcionkę
@@ -4741,6 +4747,7 @@ liquify-list-end {0}, {1} {0} i {1}
@msg Divide Objects Below: select exactly one path Podziel obiekty poniżej: zaznacz dokładnie jedną ścieżkę
@msg Downloaded {what} Pobrano {what}
@msg Expand Appearance: the selection has a basic appearance Rozszerz wygląd: zaznaczenie ma wygląd podstawowy
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all niektóre efekty rastrowe nie zostały zamienione na obrazy: zajęłyby więcej niż 1024 obrazy lub łącznie 256 megapikseli
@msg Expand: no brush strokes selected Rozszerz: nie zaznaczono pociągnięć pędzla
@msg Expand: no gradient fills Rozszerz: brak wypełnień gradientem
@msg Expand: nothing to expand Rozszerz: nie ma czego rozszerzać
@@ -6208,7 +6215,7 @@ mark-style Japanese Japońskie
@msg Unknown dimension style Nieznany styl wymiaru
@msg Unknown unit Nieznana jednostka
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Zamknij okrągłe końce otwartych profili. Przy częściowym obrocie boki przekroju pozostają otwarte.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Zamknij okrągłe końce otwartych profili. Przy częściowym obrocie boki przekroju również zostają zamknięte.
Distance Odległość
@msg span must be "object" or "selection", got {v} span musi mieć wartość "object" lub "selection", a nie {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" umieszcza `gradient`, a nie próbkę
@@ -6362,6 +6369,7 @@ mark-style Japanese Japońskie
Single Word Justification: Justowanie pojedynczego wyrazu:
Full Justify Pełne justowanie
Minimum must not exceed Desired, nor Desired Maximum. Minimum nie może przekraczać wartości optymalnej, a wartość optymalna maksimum.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimum nie może przekraczać wartości optymalnej, a wartość optymalna maksimum
Justification Justowanie
Add filters from the list above Dodaj filtry z listy powyżej
Add to Stack Dodaj do stosu
@@ -7373,7 +7381,7 @@ breakText Glyphs Glify
@msg stroke cannot be set on a symbol instance nie można ustawić stroke dla wystąpienia symbolu
@msg fill on a symbol instance must be a solid color or none fill wystąpienia symbolu musi być jednolitym kolorem lub none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it nie można ustawić {key} dla obrazu bez efektu Konwertuj na kształt lub Kontur obiektu
@msg pass newName, registration, exportType, nineSlice and/or type podaj newName, registration, exportType, nineSlice i/lub type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid podaj newName, registration, exportType, nineSlice, type i/lub alignToPixelGrid
Text Flow Przepływ tekstu
By Rows Wierszami
By Columns Kolumnami
@@ -8982,7 +8990,9 @@ breakText Glyphs Glify
@msg position must be normal, superscript or subscript position musi mieć wartość normal, superscript lub subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position musi mieć wartość topLeft, topRight, bottomLeft lub bottomRight
@msg positions must be between 0 and 100000 pt positions musi mieścić się w zakresie od 0 do 100000 pt
@msg ppi can't be more than {max} for this image ppi nie może przekraczać {max} dla tego obrazu
@msg ppi must be a positive number, not {ppi} ppi musi być liczbą dodatnią, a nie {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim zachowuje piksele obrazu bez zmian: pomiń ppi
@msg ppi must be between 1 and 2400 ppi musi mieścić się w zakresie od 1 do 2400
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` nie jest jedną z wartości transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape musi mieć wartość clippingMask|transparency
Can't render this file because it is too large.
+12 -2
View File
@@ -929,6 +929,10 @@ antiAlias Sharp Nítido
Em Box Caixa Eme
x-Height Altura do x
ICF Box Caixa ICF
Show Sample Mostrar Amostra
Hide Sample Ocultar Amostra
Max Ascent/Descent Altura/Profundidade Máx.
Max Ascender Ascendente Máx.
Em Dash Travessão
Em Space Espaço Em
Embed Incorporar
@@ -1208,6 +1212,8 @@ antiAlias Sharp Nítido
Font Family & Style Família e Estilo da Fonte
Font Family, Style & Size Família, Estilo e Tamanho da Fonte
Font List Lista de Fontes
Show Similar Fonts Mostrar Fontes Semelhantes
Clear Similar Fonts Limpar Fontes Semelhantes
Font Preview Size Tamanho da Visualização da Fonte
Font Size Tamanho da Fonte
Variable Font Fonte Variável
@@ -3938,6 +3944,7 @@ axis Both Ambos
@msg Divide Objects Below: select exactly one path Dividir objetos abaixo: selecione exatamente um traçado
@msg Downloaded {what} {what} baixado
@msg Expand Appearance: the selection has a basic appearance Expandir aparência: a seleção tem uma aparência básica
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alguns efeitos de raster não foram transformados em imagens: ocupariam mais de 1.024 imagens ou 256 megapixels no total
@msg Expand: no brush strokes selected Expandir: nenhum traço de pincel selecionado
@msg Expand: no gradient fills Expandir: nenhum preenchimento em gradiente
@msg Expand: nothing to expand Expandir: nada para expandir
@@ -6237,7 +6244,7 @@ mark-style Japanese Japonesas
Create Dimension Criar Cota
Update Dimensions Atualizar Cotas
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Fecha as extremidades circulares dos perfis abertos. Giros parciais mantêm as faces de corte abertas.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Fecha as extremidades circulares dos perfis abertos. Giros parciais também fecham as faces de corte.
@msg span must be "object" or "selection", got {v} span deve ser "object" ou "selection", não {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" posiciona um `gradient`, não uma amostra
@msg span: "selection" places a gradient: give `gradient` span: "selection" posiciona um degradê: informe `gradient`
@@ -6420,6 +6427,7 @@ mark-style Japanese Japonesas
Single Word Justification: Justificação de Palavra Única:
Full Justify Justificação Completa
Minimum must not exceed Desired, nor Desired Maximum. O mínimo não pode passar do desejado, nem o desejado do máximo.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: o mínimo não pode passar do desejado, nem o desejado do máximo
Justification Justificação
Add filters from the list above Adicione filtros da lista acima
Add to Stack Adicionar à Pilha
@@ -7548,7 +7556,7 @@ breakText Glyphs Glifos
@msg stroke cannot be set on a symbol instance stroke não pode ser definido em uma instância de símbolo
@msg fill on a symbol instance must be a solid color or none o fill de uma instância de símbolo deve ser uma cor sólida ou none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} não pode ser definido em uma imagem sem o efeito Converter em Forma ou Contornar Objeto
@msg pass newName, registration, exportType, nineSlice and/or type informe newName, registration, exportType, nineSlice e/ou type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid informe newName, registration, exportType, nineSlice, type e/ou alignToPixelGrid
# Strings the sibling catalogs translate that pt-BR did not yet cover (translated 2026-10-31).
on the canvas to create one na tela para criar um
1 Layer 1 camada
@@ -9173,7 +9181,9 @@ swatch Yellow Green Verde-amarelado
@msg position must be normal, superscript or subscript position deve ser normal, superscript ou subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position deve ser topLeft, topRight, bottomLeft ou bottomRight
@msg positions must be between 0 and 100000 pt positions deve estar entre 0 e 100000 pt
@msg ppi can't be more than {max} for this image ppi não pode ser maior que {max} para esta imagem
@msg ppi must be a positive number, not {ppi} ppi deve ser um número positivo, não {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim mantém os pixels da imagem como estão: omita ppi
@msg ppi must be between 1 and 2400 ppi deve estar entre 1 e 2400
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` não é transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape deve ser clippingMask|transparency
Can't render this file because it is too large.
+10 -2
View File
@@ -1034,6 +1034,10 @@ font-technology Variable Вариативные
Em Box Кегельная площадка
x-Height Высота строчных
ICF Box Рамка ICF
Show Sample Показать образец
Hide Sample Скрыть образец
Max Ascent/Descent Макс. высота/глубина
Max Ascender Макс. выносной элемент вверх
Em Dash Длинное тире
Em Space Круглая шпация
Embed Внедрить
@@ -1359,6 +1363,8 @@ file-filter Templates Шаблоны
Font Family & Style Семейство и стиль шрифта
Font Family, Style & Size Семейство, стиль и размер шрифта
Font List Список шрифтов
Show Similar Fonts Показать похожие шрифты
Clear Similar Fonts Сбросить похожие шрифты
Font Preview Size Размер предварительного просмотра шрифта
Font Size Размер шрифта
Variable Font Вариативный шрифт
@@ -4646,6 +4652,7 @@ liquify-list-end {0}, {1} {0} и {1}
@msg Divide Objects Below: select exactly one path Разделение объектов ниже: выделите ровно один контур
@msg Downloaded {what} Скачано: {what}
@msg Expand Appearance: the selection has a basic appearance Разбор оформления: у выделения основное оформление
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all некоторые растровые эффекты не преобразованы в изображения: для них нужно больше 1024 изображений или 256 мегапикселей в сумме
@msg Expand: no brush strokes selected Разбор: не выделены мазки кисти
@msg Expand: no gradient fills Разбор: нет градиентных заливок
@msg Expand: nothing to expand Разбор: нечего разбирать
@@ -5972,7 +5979,7 @@ lighting Light Свет
@msg Unknown dimension style Неизвестный стиль размера
@msg Unknown unit Неизвестная единица
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Закрывает круглые торцы открытых профилей. При неполном вращении боковые срезы остаются открытыми.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Закрывает круглые торцы открытых профилей. При неполном вращении боковые срезы тоже закрываются.
Distance Расстояние
@msg span must be "object" or "selection", got {v} span должен быть "object" или "selection", а не {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" размещает `gradient`, а не образец
@@ -6126,6 +6133,7 @@ lighting Light Свет
Single Word Justification: Выключка одного слова:
Full Justify Полная выключка
Minimum must not exceed Desired, nor Desired Maximum. Минимум не может превышать желательное значение, а желательное — максимум.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: минимум не может превышать желательное значение, а желательное — максимум
Minimum Минимум
Justification Выключка
Add filters from the list above Добавьте фильтры из списка выше
@@ -7507,7 +7515,7 @@ breakText Glyphs Глифы
@msg stroke cannot be set on a symbol instance stroke нельзя задать для экземпляра символа
@msg fill on a symbol instance must be a solid color or none fill экземпляра символа должен быть сплошным цветом или none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} нельзя задать для изображения без эффекта «Преобразовать в фигуру» или «Обвести объект»
@msg pass newName, registration, exportType, nineSlice and/or type укажите newName, registration, exportType, nineSlice и/или type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid укажите newName, registration, exportType, nineSlice, type и/или alignToPixelGrid
Text Flow Поток текста
By Rows По строкам
By Columns По столбцам
Can't render this file because it is too large.
+11 -2
View File
@@ -1306,6 +1306,8 @@ font-technology Variable Variabla
Font Family & Style Typsnittsfamilj och stil
Font Family, Style & Size Typsnittsfamilj, stil och storlek
Font List Typsnittslista
Show Similar Fonts Visa liknande typsnitt
Clear Similar Fonts Rensa liknande typsnitt
Font Preview Size Storlek på typsnittsförhandsgranskning
Font Size Teckenstorlek
Variable Font Variabelt typsnitt
@@ -4532,6 +4534,7 @@ liquify-list-end {0}, {1} {0} och {1}
@msg Divide Objects Below: select exactly one path Dela objekt under: markera exakt en bana
@msg Downloaded {what} Hämtade {what}
@msg Expand Appearance: the selection has a basic appearance Expandera utseende: markeringen har ett grundläggande utseende
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all vissa rastereffekter gjordes inte om till bilder: de skulle kräva mer än 1 024 bilder eller totalt 256 megapixlar
@msg Expand: no brush strokes selected Expandera: inga penseldrag är markerade
@msg Expand: no gradient fills Expandera: inga gradientfyllningar
@msg Expand: nothing to expand Expandera: ingenting att expandera
@@ -5349,6 +5352,10 @@ liquify-list-end {0}, {1} {0} och {1}
Em Box Em-ruta
x-Height x-höjd
ICF Box ICF-ruta
Show Sample Visa exempel
Hide Sample Dölj exempel
Max Ascent/Descent Max höjd/djup
Max Ascender Max uppstapel
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` är stegreferensen {r}, som bara `run` och `command_batch` löser upp
@msg `ids` must be an array of object ids, not {v} `ids` måste vara en array med objekt-id:n, inte {v}
@msg `colors` must be an array of colors, not {v} `colors` måste vara en array med färger, inte {v}
@@ -6229,7 +6236,7 @@ theme Appearance Utseende
By Object Efter objekt
Check an artboard to save. Markera en rityta som ska sparas.
Clear All Rensa alla
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Stäng de cirkulära ändarna på öppna profiler. Partiella svep behåller sina snittsidor öppna.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Stäng de cirkulära ändarna på öppna profiler. Partiella svep stänger även sina snittsidor.
Color Panel Options Alternativ för panelen Färg
Color blindness – Tritanopia-type Färgblindhet – tritanopi
Create Dimension Skapa mått
@@ -7546,7 +7553,7 @@ breakText Glyphs Glyfer
@msg stroke cannot be set on a symbol instance stroke kan inte anges för en symbolinstans
@msg fill on a symbol instance must be a solid color or none fill för en symbolinstans måste vara en enfärgad färg eller none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan inte anges för en bild utan effekten Konvertera till form eller Konvertera objekt till konturer
@msg pass newName, registration, exportType, nineSlice and/or type ange newName, registration, exportType, nineSlice och/eller type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid ange newName, registration, exportType, nineSlice, type och/eller alignToPixelGrid
Text Flow Textflöde
By Rows Radvis
By Columns Kolumnvis
@@ -8699,7 +8706,9 @@ digits Hindi Hindi
@msg position must be normal, superscript or subscript position måste vara normal, superscript eller subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position måste vara topLeft, topRight, bottomLeft eller bottomRight
@msg positions must be between 0 and 100000 pt positionerna måste vara mellan 0 och 100 000 pt
@msg ppi can't be more than {max} for this image ppi kan inte vara mer än {max} för den här bilden
@msg ppi must be a positive number, not {ppi} ppi måste vara ett positivt tal, inte {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim behåller bildens pixlar som de är: utelämna ppi
@msg ppi must be between 1 and 2400 ppi måste vara mellan 1 och 2400
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` är inte transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape måste vara clippingMask|transparency
Can't render this file because it is too large.
+16
View File
@@ -2194,6 +2194,22 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() {
}
}
/// The error that `text.setFormat` and the paragraph style commands give when a justification
/// setting's Minimum, Desired and Maximum are out of order is translated in every
/// complete-message language, with the setting's name kept.
#[test]
fn justification_order_error_translates_with_the_setting_name() {
for name in ["wordSpacing", "justification.glyph_scaling"] {
let error = format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum");
for code in COMPLETE_MESSAGES {
let lang = Lang::from_code(code).expect("registered");
let shown = message(lang, &error);
assert!(shown != error && !shown.contains("Desired"), "{code}: {shown}");
assert!(shown.contains(&format!("`{name}`")), "{code}: {shown}");
}
}
}
/// A script's error about unused `answers` and Liquify's note on the objects it left as they were
/// are translated whole for one object as well as for several, in every complete-message language,
/// and keep their counts.
+12 -2
View File
@@ -1302,6 +1302,8 @@ font-technology Variable Değişken
Font Family & Style Yazı Tipi Ailesi ve Stili
Font Family, Style & Size Yazı Tipi Ailesi, Stili ve Boyutu
Font List Yazı Tipi Listesi
Show Similar Fonts Benzer Yazı Tiplerini Göster
Clear Similar Fonts Benzer Yazı Tiplerini Temizle
Font Preview Size Yazı Tipi Önizleme Boyutu
Font Size Yazı Tipi Boyutu
Font: Yazı tipi:
@@ -3054,6 +3056,7 @@ digits Malayalam Malayalam
Letter Spacing: Harf Boşluğu:
Lights Işıklar
Minimum must not exceed Desired, nor Desired Maximum. Minimum, İstenen'i; İstenen ise Maksimum'u aşmamalıdır.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum, İstenen'i; İstenen ise Maksimum'u aşmamalıdır
Select by Color Renge Göre Seç
Set History Limit… Geçmiş Sınırını Ayarla…
Single Word Justification: Tek Sözcük Yaslama:
@@ -4364,6 +4367,7 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg Divide Objects Below: select exactly one path Aşağıdaki Nesneleri Böl: tam olarak bir yol seçin
@msg Downloaded {what} {what} indirildi
@msg Expand Appearance: the selection has a basic appearance Görünümü Genişlet: seçimin temel bir görünümü vardır
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all bazı raster efektleri görüntüye dönüştürülmedi: toplamda 1.024'ten fazla görüntü veya 256 megapiksel gerektirirlerdi
@msg Expand: no brush strokes selected Genişlet: seçili fırça darbesi yok
@msg Expand: no gradient fills Genişlet: degrade dolgu yok
@msg Expand: nothing to expand Genişlet: genişletilecek bir şey yok
@@ -5177,6 +5181,10 @@ liquify-list-end {0}, {1} {0} ve {1}
Em Box Em Kutusu
x-Height x-Yüksekliği
ICF Box ICF Kutusu
Show Sample Örneği Göster
Hide Sample Örneği Gizle
Max Ascent/Descent Maks. Yükseklik/Derinlik
Max Ascender Maks. Yükselen
@msg `colors` must be an array of colors, not {v} `colors` {v} değil, bir renk dizisi olmalıdır
@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id`, yalnızca `run` ve `command_batch` komutlarının çözümlediği {r} adım referansıdır
@msg `ids` must be an array of object ids, not {v} `ids` bir nesne kimlikleri dizisi olmalıdır, {v} değil
@@ -6110,7 +6118,7 @@ theme Appearance Görünüm
@msg Unknown dimension orientation Bilinmeyen boyut yönü
@msg Unknown dimension style Bilinmeyen boyut stili
@msg Unknown unit Bilinmeyen birim
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Açık profillerin dairesel uçlarını kapatın. Kısmi süpürmeler kesik taraflarını açık tutar.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Açık profillerin dairesel uçlarını kapatın. Kısmi süpürmeler kesik taraflarını da kapatır.
@msg span must be "object" or "selection", got {v} span "object" veya "selection" olmalıdır, {v} değil
@msg span: "selection" places a `gradient`, not a swatch span: "selection" bir renk örneği değil, bir `gradient` yerleştirir
@msg span: "selection" places a gradient: give `gradient` span: "selection" bir degrade yerleştirir: `gradient` verin
@@ -8306,7 +8314,9 @@ axis Y Axis Y ekseni
@msg position must be normal, superscript or subscript position normal, superscript veya subscript olmalıdır
@msg position must be topLeft, topRight, bottomLeft or bottomRight position topLeft, topRight, bottomLeft veya bottomRight olmalıdır
@msg positions must be between 0 and 100000 pt konumlar 0 ile 100000 pt arasında olmalıdır
@msg ppi can't be more than {max} for this image bu görüntü için ppi {max} değerinden büyük olamaz
@msg ppi must be a positive number, not {ppi} ppi pozitif bir sayı olmalıdır, {ppi} değil
@msg trim keeps the image's pixels as they are: leave out ppi trim görüntünün piksellerini olduğu gibi korur: ppi belirtmeyin
@msg ppi must be between 1 and 2400 ppi 1 ile 2400 arasında olmalıdır
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill değerlerinden biri değil
@msg preserveShape must be clippingMask|transparency preserveShape clippingMask|transparency olmalıdır
@@ -9395,7 +9405,7 @@ breakText Glyphs Glifler
@msg stroke cannot be set on a symbol instance stroke bir sembol örneğinde ayarlanamaz
@msg fill on a symbol instance must be a solid color or none bir sembol örneğinin fill değeri düz renk veya none olmalıdır
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key}, Şekle Dönüştür veya Anahat Nesnesi efekti olmayan bir görüntüde ayarlanamaz
@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice ve/veya type verin
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type ve/veya alignToPixelGrid verin
Text Flow Metin Akışı
By Rows Satırlara Göre
By Columns Sütunlara Göre
Can't render this file because it is too large.
+12 -2
View File
@@ -1039,6 +1039,10 @@ font-technology Variable Варіативні
Cap Height Висота великих літер
x-Height Висота малих літер
ICF Box Рамка ICF
Show Sample Показати зразок
Hide Sample Приховати зразок
Max Ascent/Descent Макс. висота/глибина
Max Ascender Макс. виносний елемент вгору
Em Dash Довге тире
Em Space Кругла шпація
Embed Вбудувати
@@ -1362,6 +1366,8 @@ file-filter Templates Шаблони
Font Family & Style Сімейство та стиль шрифту
Font Family, Style & Size Сімейство, стиль та розмір шрифту
Font List Список шрифтів
Show Similar Fonts Показати схожі шрифти
Clear Similar Fonts Скинути схожі шрифти
Font Preview Size Розмір попереднього перегляду шрифту
Font Size Розмір шрифту
Variable Font Варіативний шрифт
@@ -4634,6 +4640,7 @@ liquify-list-end {0}, {1} {0} і {1}
@msg Divide Objects Below: select exactly one path Поділ об’єктів нижче: виділіть рівно один контур
@msg Downloaded {what} Завантажено: {what}
@msg Expand Appearance: the selection has a basic appearance Розбір оформлення: виділення основне оформлення
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all деякі растрові ефекти не перетворено на зображення: для них потрібно понад 1024 зображення або загалом 256 мегапікселів
@msg Expand: no brush strokes selected Розбір: не виділено мазки пензлі
@msg Expand: no gradient fills Розбір: немає градієнтних заливок
@msg Expand: nothing to expand Розбір: нема чого розбирати
@@ -5954,7 +5961,7 @@ lighting Light Світло
@msg Unknown dimension style Невідомий стиль розміру
@msg Unknown unit Невідома одиниця
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Закриває круглі торці відкритих профілів. За неповного обертання бічні зрізи залишаються відкритими.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Закриває круглі торці відкритих профілів. За неповного обертання бічні зрізи теж закриваються.
Distance Відстань
@msg span must be "object" or "selection", got {v} span має бути "object" або "selection", а не {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" розміщує `gradient`, а не зразок
@@ -6108,6 +6115,7 @@ lighting Light Світло
Single Word Justification: Вирівнювання одного слова:
Full Justify Повне вирівнювання
Minimum must not exceed Desired, nor Desired Maximum. Мінімум не може перевищувати бажане значення, а бажане — максимум.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: мінімум не може перевищувати бажане значення, а бажане — максимум
Minimum Мінімум
Justification Вирівнювання за шириною
Add filters from the list above Додайте фільтри зі списку вище
@@ -7126,7 +7134,7 @@ breakText Glyphs Гліфи
@msg stroke cannot be set on a symbol instance stroke не можна задати для екземпляра символу
@msg fill on a symbol instance must be a solid color or none fill екземпляра символу має бути суцільним кольором або none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} не можна задати для зображення без ефекту «Перетворити на фігуру» або «Обвести об’єкт»
@msg pass newName, registration, exportType, nineSlice and/or type вкажіть newName, registration, exportType, nineSlice та/або type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid вкажіть newName, registration, exportType, nineSlice, type та/або alignToPixelGrid
Text Flow Потік тексту
By Rows За рядками
By Columns За стовпцями
@@ -8709,7 +8717,9 @@ breakText Glyphs Гліфи
@msg position must be normal, superscript or subscript position має бути normal, superscript або subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position має бути topLeft, topRight, bottomLeft або bottomRight
@msg positions must be between 0 and 100000 pt positions мають бути від 0 до 100000 pt
@msg ppi can't be more than {max} for this image ppi для цього зображення не може перевищувати {max}
@msg ppi must be a positive number, not {ppi} ppi має бути додатним числом, а не {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim залишає пікселі зображення без змін: не вказуйте ppi
@msg ppi must be between 1 and 2400 ppi має бути від 1 до 2400
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` не є transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape має бути clippingMask|transparency
Can't render this file because it is too large.
+10 -2
View File
@@ -1589,6 +1589,8 @@ file-filter Templates Mẫu
Font Family & Style Họ phông & kiểu
Font Family, Style & Size Họ phông, kiểu & cỡ
Font List Danh sách phông
Show Similar Fonts Hiển thị phông tương tự
Clear Similar Fonts Xóa phông tương tự
Font Preview Size Cỡ xem trước phông
Font Size Cỡ chữ
Variable Font Phông chữ biến thiên
@@ -2008,6 +2010,10 @@ digits Hindi Hindi
Cap Height Chiều cao chữ hoa
x-Height Chiều cao chữ x
ICF Box Ô ICF
Show Sample Hiện mẫu
Hide Sample Ẩn mẫu
Max Ascent/Descent Độ cao/sâu tối đa
Max Ascender Nét chân chữ trên tối đa
ICF Top/Right ICF Trên/Phải
Identify Objects By Nhận diện đối tượng theo
Ignore Bỏ qua
@@ -5115,6 +5121,7 @@ liquify-list-end {0}, {1} {0} và {1}
@msg every numbered name for {name} is taken in the document's folder mọi tên đánh số cho {name} đã được dùng trong thư mục tài liệu
@msg every search thread stopped on an internal error (please report this bug) mọi luồng tìm kiếm đã dừng do lỗi nội bộ (vui lòng báo cáo lỗi này)
@msg Expand Appearance: the selection has a basic appearance Mở rộng diện mạo: vùng chọn có diện mạo cơ bản
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all một số hiệu ứng raster không được chuyển thành hình ảnh: chúng sẽ cần hơn 1.024 hình ảnh hoặc tổng cộng 256 megapixel
@msg Expand: no brush strokes selected Mở rộng: chưa chọn nét cọ
@msg Expand: no gradient fills Mở rộng: không có tô chuyển sắc
@msg Expand: nothing to expand Mở rộng: không có gì để mở rộng
@@ -5983,7 +5990,7 @@ liquify-list-end {0}, {1} {0} và {1}
@msg Unknown dimension style Kiểu kích thước không xác định
@msg Unknown unit Đơn vị không xác định
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Đóng các đầu tròn của biên dạng mở. Khi xoay một phần, các mặt cắt bên vẫn mở.
Close the circular ends of open profiles. Partial sweeps also close their cut sides. Đóng các đầu tròn của biên dạng mở. Khi xoay một phần, các mặt cắt bên cũng được đóng.
Distance Khoảng cách
@msg span must be "object" or "selection", got {v} span phải là "object" hoặc "selection", không phải {v}
@msg span: "selection" places a `gradient`, not a swatch span: "selection" đặt một `gradient`, không phải mẫu màu
@@ -6137,6 +6144,7 @@ liquify-list-end {0}, {1} {0} và {1}
Single Word Justification: Căn đều một từ:
Full Justify Căn đều hoàn toàn
Minimum must not exceed Desired, nor Desired Maximum. Giá trị tối thiểu không được vượt quá giá trị mong muốn, và giá trị mong muốn không được vượt quá tối đa.
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: giá trị tối thiểu không được vượt quá giá trị mong muốn, và giá trị mong muốn không được vượt quá tối đa
Minimum Tối thiểu
Justification Căn đều
Add filters from the list above Thêm bộ lọc từ danh sách phía trên
@@ -7156,7 +7164,7 @@ breakText Glyphs Glyph
@msg stroke cannot be set on a symbol instance không thể đặt stroke cho thực thể ký hiệu
@msg fill on a symbol instance must be a solid color or none fill của thực thể ký hiệu phải là màu đặc hoặc none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it không thể đặt {key} cho hình ảnh không có hiệu ứng Chuyển thành hình dạng hoặc Đường bao đối tượng
@msg pass newName, registration, exportType, nineSlice and/or type hãy cung cấp newName, registration, exportType, nineSlice và/hoặc type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid hãy cung cấp newName, registration, exportType, nineSlice, type và/hoặc alignToPixelGrid
Text Flow Luồng văn bản
By Rows Theo hàng
By Columns Theo cột
Can't render this file because it contains an unexpected character in line 205 and column 5.
+12 -2
View File
@@ -976,6 +976,10 @@ antiAlias Sharp 锐利
Cap Height 大写字母高度
x-Height x 字高
ICF Box ICF 框
Show Sample 显示样本
Hide Sample 隐藏样本
Max Ascent/Descent 最大上升/下降
Max Ascender 最大上伸部
Em Dash 长破折号
Em Space 全角空格
Embed 嵌入
@@ -1297,6 +1301,8 @@ file-filter Templates 模板
Font Family & Style 字体系列和样式
Font Family, Style & Size 字体系列、样式和字号
Font List 字体列表
Show Similar Fonts 显示相似字体
Clear Similar Fonts 清除相似字体
Font Preview Size 字体预览大小
Font Size 字号
Variable Font 可变字体
@@ -4320,6 +4326,7 @@ imageTrace Outline 轮廓
@msg no history to clear 没有可清除的历史记录
@msg no history state {v} 没有历史记录状态 {v}
@msg Expand Appearance: the selection has a basic appearance 扩展外观:所选对象只有基本外观
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 部分栅格效果未转换为图像:它们会超过 1,024 个图像或总计 256 兆像素
@msg select (or target) objects whose appearance isn't basic 请选择 (或定位) 外观不是基本外观的对象
@msg {C}: no effect at index {from} {C}:索引 {from} 处没有效果
@msg Expand: no gradient fills 扩展:没有渐变填色
@@ -6201,7 +6208,7 @@ lighting Light 光源
@msg Choose a circle or a perfect arc 请选择圆或标准圆弧
@msg Choose a precision from 0 to 6 请选择 0 到 6 之间的精度
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 封闭开放轮廓的圆形端部。部分旋转的切割侧面保持开放。
Close the circular ends of open profiles. Partial sweeps also close their cut sides. 封闭开放轮廓的圆形端部。部分旋转的切割侧面也会封闭。
Distance 距离
Make Image Dynamic 使图像动态化
Import Data Sets… 导入数据集…
@@ -6344,6 +6351,7 @@ lighting Light 光源
Single Word Justification: 单字对齐:
Full Justify 全部强制双齐
Minimum must not exceed Desired, nor Desired Maximum. 最小值不能超过所需值,所需值不能超过最大值。
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`:最小值不能超过所需值,所需值不能超过最大值
Minimum 最小值
Justification 对齐设置
Add filters from the list above 从上方列表添加滤镜
@@ -7358,7 +7366,7 @@ breakText Glyphs 字形
@msg stroke cannot be set on a symbol instance 无法为符号实例设置 stroke
@msg fill on a symbol instance must be a solid color or none 符号实例的 fill 必须是纯色或 none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 无法为没有“转换为形状”或“轮廓化对象”效果的图像设置 {key}
@msg pass newName, registration, exportType, nineSlice and/or type 请提供 newName、registration、exportType、nineSlice 和/或 type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid 请提供 newName、registration、exportType、nineSlice、type 和/或 alignToPixelGrid
Text Flow 文本流向
By Rows 按行
By Columns 按列
@@ -8968,7 +8976,9 @@ breakText Glyphs 字形
@msg position must be normal, superscript or subscript position 必须是 normal、superscript 或 subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position 必须是 topLeft、topRight、bottomLeft 或 bottomRight
@msg positions must be between 0 and 100000 pt positions 必须介于 0 到 100000 pt 之间
@msg ppi can't be more than {max} for this image 此图像的 ppi 不能超过 {max}
@msg ppi must be a positive number, not {ppi} ppi 必须是正数,不能是 {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim 会保持图像像素不变:请省略 ppi
@msg ppi must be between 1 and 2400 ppi 必须介于 1 到 2400 之间
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` 不是 transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape 必须是 clippingMask|transparency
Can't render this file because it is too large.
+12 -2
View File
@@ -1007,6 +1007,10 @@ font-technology Variable 可變
Cap Height 大寫字母高度
x-Height x 字高
ICF Box ICF 框
Show Sample 顯示樣本
Hide Sample 隱藏樣本
Max Ascent/Descent 最大上升/下降
Max Ascender 最大上伸部
Em Dash 長破折號
Em Space 全形空格
Embed 嵌入
@@ -1332,6 +1336,8 @@ file-filter Templates 範本
Font Family & Style 字體家族與樣式
Font Family, Style & Size 字體家族、樣式與大小
Font List 字體清單
Show Similar Fonts 顯示相似字體
Clear Similar Fonts 清除相似字體
Font Preview Size 字體預覽大小
Font Size 字體大小
Variable Font 可變字體
@@ -1953,6 +1959,7 @@ file-filter Templates 範本
@msg no history to clear 沒有可清除的步驟記錄
@msg no history state {v} 沒有步驟記錄 {v}
@msg Expand Appearance: the selection has a basic appearance 展開外觀:選取範圍只有基本外觀
@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 部分點陣效果未轉換為影像:它們會超過 1,024 個影像或總計 256 百萬像素
@msg select (or target) objects whose appearance isn't basic 請選取 (或指定目標) 外觀不是基本外觀的物件
@msg {C}: no effect at index {from} {C}:索引 {from} 處沒有效果
@msg Expand: no gradient fills 展開:沒有漸層填色
@@ -6036,7 +6043,7 @@ lighting Light 光源
X: X:
Y: Y:
# Revolve cap description
Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 封閉開放輪廓的圓形端部。部分旋轉的切割側面保持開放。
Close the circular ends of open profiles. Partial sweeps also close their cut sides. 封閉開放輪廓的圓形端部。部分旋轉的切割側面也會封閉。
Distance 距離
Make Image Dynamic 使影像動態化
Import Data Sets… 匯入資料集…
@@ -6142,6 +6149,7 @@ lighting Light 光源
Single Word Justification: 單字對齊:
Full Justify 全部強迫齊行
Minimum must not exceed Desired, nor Desired Maximum. 最小值不可超過所需值,所需值不可超過最大值。
@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`:最小值不可超過所需值,所需值不可超過最大值
Minimum 最小值
Justification 對齊設定
Add filters from the list above 從上方清單新增濾鏡
@@ -7167,7 +7175,7 @@ breakText Glyphs 字符
@msg stroke cannot be set on a symbol instance 無法為符號範例設定 stroke
@msg fill on a symbol instance must be a solid color or none 符號範例的 fill 必須是純色或 none
@msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 無法為沒有「轉換為形狀」或「外框物件」效果的影像設定 {key}
@msg pass newName, registration, exportType, nineSlice and/or type 請提供 newName、registration、exportType、nineSlice 和/或 type
@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid 請提供 newName、registration、exportType、nineSlice、type 和/或 alignToPixelGrid
Text Flow 文字流向
By Rows 依列
By Columns 依欄
@@ -8896,7 +8904,9 @@ breakText Glyphs 字符
@msg position must be normal, superscript or subscript position 必須是 normal、superscript 或 subscript
@msg position must be topLeft, topRight, bottomLeft or bottomRight position 必須是 topLeft、topRight、bottomLeft 或 bottomRight
@msg positions must be between 0 and 100000 pt positions 必須介於 0 到 100000 pt 之間
@msg ppi can't be more than {max} for this image 此影像的 ppi 不能超過 {max}
@msg ppi must be a positive number, not {ppi} ppi 必須是正數,而非 {ppi}
@msg trim keeps the image's pixels as they are: leave out ppi trim 會保持影像像素不變:請勿指定 ppi
@msg ppi must be between 1 and 2400 ppi 必須介於 1 和 2400 之間
@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` 不是 transforms|bounds|fileDimensions|fit|fill
@msg preserveShape must be clippingMask|transparency preserveShape 必須是 clippingMask|transparency
Can't render this file because it is too large.
+1 -1
View File
@@ -855,7 +855,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.cropImage",
"Crop Image",
"",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box. → {tool}; a tool that cannot be chosen returns the error",
"{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is and it can be cropped to it), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error",
),
("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"),
(
+10 -2
View File
@@ -674,6 +674,12 @@ fn spectrum(ui: &mut Ui, mode: Mode, size: egui::Vec2) -> Option<SpectrumHit> {
/// Draw numeric paint controls, retaining live components while the color and settings match.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
show_sized(app, ui, 0.0);
}
/// Draw the Color panel in a sized dock body; compact mixers use [`show`].
pub(crate) fn show_sized(app: &mut VectorcraftApp, ui: &mut Ui, height: f32) {
let top = ui.next_widget_position().y;
let t = Tokens::get(ui.ctx());
let tgt = target(app, ui);
let color = tgt.color();
@@ -684,7 +690,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let hit = ui
.horizontal(|ui| {
super::proxy(app, ui, 40.0);
spectrum(ui, mode, vec2(ui.available_width(), 40.0))
spectrum(ui, mode, vec2(ui.available_width(), height.max(40.0)))
})
.inner;
match hit {
@@ -851,7 +857,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
});
ui.add_space(4.0);
match spectrum(ui, mode, vec2(ui.available_width(), 46.0)) {
// Measure from the content origin so scrolling moves the ramp without stretching it.
let remaining = height - (ui.next_widget_position().y - top);
match spectrum(ui, mode, vec2(ui.available_width(), remaining.max(46.0))) {
Some(SpectrumHit::Pick(c, phase)) => pick(c, phase, &mut new),
Some(SpectrumHit::Cycle) => set_mode(app, &tgt, mode.next()),
Some(SpectrumHit::Recolor { invert }) => recolor(app, ui, &tgt, invert, alt),
+54
View File
@@ -8,6 +8,60 @@ fn app() -> VectorcraftApp {
app
}
fn painted_spectrum(shape: &egui::Shape) -> Option<Rect> {
match shape {
egui::Shape::Mesh(mesh) if mesh.vertices.len() > 500 => Some(mesh.calc_bounds()),
egui::Shape::Vec(shapes) => shapes.iter().find_map(painted_spectrum),
_ => None,
}
}
/// #8005: enlarging the Color panel gives the spectrum the added vertical space.
#[test]
fn the_spectrum_grows_with_the_color_panel() {
for hidden in [false, true] {
let mut app = app();
app.ui.color_hide_options = hidden;
let ctx = egui::Context::default();
let mut rects = Vec::new();
for height in [300.0, 480.0] {
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, height))), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
let info = egui::UiStackInfo::default().with_tag_value(crate::widgets::PANEL_FOOTER, Some(ui.max_rect().bottom()));
ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| {
crate::dock::panel_body(&mut app, ui, "color", 300.0, height - 20.0);
});
});
rects.push(out.shapes.iter().find_map(|shape| painted_spectrum(&shape.shape)).expect("the spectrum is painted"));
out.textures_delta.clear();
}
assert!((rects[1].top() - rects[0].top()).abs() < 1.0, "resizing keeps the ramp's top stable");
assert!((rects[1].height() - rects[0].height() - 180.0).abs() < 1.0, "options hidden={hidden}: {rects:?}");
}
}
#[test]
fn a_short_color_panel_scrolls_without_stretching_the_spectrum() {
let mut app = app();
let ctx = egui::Context::default();
for offset in [0.0, 100.0] {
for _ in 0..3 {
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 120.0))), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
let info = egui::UiStackInfo::default().with_tag_value(crate::widgets::PANEL_FOOTER, Some(ui.max_rect().bottom()));
ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| {
widgets::panel_scroll(ui, egui::ScrollArea::vertical().vertical_scroll_offset(offset), |ui| {
crate::dock::panel_body(&mut app, ui, "color", 300.0, 100.0);
});
});
});
let r = out.shapes.iter().find_map(|shape| painted_spectrum(&shape.shape)).expect("the spectrum is painted");
assert!((r.height() - 46.0).abs() < 1.0, "offset={offset}: {r:?}");
out.textures_delta.clear();
}
}
}
/// Run the panel for one frame with `events` and `modifiers`; returns the spectrum's rect (when
/// the options are shown) and the panel's height.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, modifiers: egui::Modifiers) -> (Option<Rect>, f32) {
+8 -3
View File
@@ -764,9 +764,11 @@ pub fn image_summary(i: &Value) -> (String, String) {
/// The Control bar for the one selected image: Linked File or Embedded, its file name, colour mode
/// and effective resolution, Embed or Unembed, Edit Original (a linked file), Image Trace, Mask,
/// Crop Image and Remove Background. Whether one image is selected. A file name the row has no room
/// for is left out alone; after it, each control shows only while the row has room for it and
/// `reserve` after it, and the controls after one left out are left out too.
/// Crop Image and Remove Background. While the Crop Image tool is in use, the bar shows the file
/// name, colour mode and resolution only, and the tool's cropping options follow them. Whether one
/// image is selected. A file name the row has no room for is left out alone; after it, each control
/// shows only while the row has room for it and `reserve` after it, and the controls after one left
/// out are left out too.
pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve: f32) -> bool {
let Some(i) = selected_image_info(app) else { return false };
let (name, details) = image_summary(i);
@@ -786,6 +788,9 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve:
ui.label(details);
}
fit.separator(ui);
if app.session.tool_id() == vectorcraft_tools::cropimage::ID {
return true;
}
link_buttons(app, ui, id, linked, &name, LinkButtons::Fit(&mut fit));
// The Image Trace button grows past its usual width for a longer translated label.
let arrow = widgets::SPLIT_ARROW;
+64 -19
View File
@@ -543,35 +543,80 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32)
/// The width of Mirror & Cut's Axis and Keep menus in the Control bar.
const MIRROR_DROPDOWN_WIDTH: f32 = 96.0;
/// Crop Image's box: its centre (X, Y) and size (W, H) in the general unit, set through the tool's
/// `rect` option, then Apply (Enter) and Cancel (Escape), each while the row has room for it and
/// `reserve` after it.
/// Crop Image's cropping options: the cropped image's resolution (PPI: a list, with the
/// resolutions above what the image allows disabled, or a typed value), the reference point, the
/// box's X and Y (that point) and size (W, H) in the general unit with the link that keeps their
/// proportions, all set through the tool's options; then Apply (Enter) and Cancel (Escape), each
/// while the row has room for it and `reserve` after it.
fn crop_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) {
let set = app.session.tool_options()["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::<Vec<_>>()[..] {
use vectorcraft_tools::cropimage::{self as crop, PPI_CHOICES};
let opts = app.session.tool_options();
let set = opts["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::<Vec<_>>()[..] {
[x, y, w, h] => Some(vectorcraft_geom::Rect::new(x, y, x + w, y + h)),
_ => None,
});
let Some((_, _, r)) = app.session.active().and_then(|st| vectorcraft_tools::cropimage::crop_box(&st.doc, &st.selection, set)) else { return };
let Some((r, image, own, max)) = app.session.active().and_then(|st| {
let (id, image, r) = crop::crop_box(&st.doc, &st.selection, set)?;
let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id)?.kind else { return None };
let (own, max) = crop::image_ppi(im);
Some((r, image, own, max.min(2400.0)))
}) else {
return;
};
let reference = opts["reference"].as_u64().filter(|v| *v <= 8).map_or(crop::CENTER, |v| v as usize);
let linked = opts["linked"].as_bool().unwrap_or(false);
let t = Tokens::get(ui.ctx());
let units = app.session.general_unit();
let c = r.center();
let set_option = |app: &mut VectorcraftApp, key: &str, value: Value| {
app.run("tool.setOption", json!({ "key": key, "value": value })).ok();
};
// Resolution: the list's choices above the image's limit are disabled; a typed value is held to it.
let ppi = opts["ppi"].as_f64().unwrap_or(own);
let label = |v: f64| crate::i18n::fill_once(tl!("{n} ppi"), &[("n", &format!("{}", (v * 100.0).round() / 100.0))]);
let labels: Vec<String> = PPI_CHOICES.iter().map(|v| label(*v)).collect();
let names: Vec<&str> = labels.iter().map(String::as_str).collect();
let mut fit = crate::chrome::Fit::new(reserve);
for (k, lbl, v) in [("x", "X:", c.x), ("y", "Y:", c.y), ("width", "W:", r.width()), ("height", "H:", r.height())] {
let text = egui::RichText::new(tl!("PPI")).size(12.0).color(t.text_dim);
if fit.room(ui, &[widgets::text_width(ui, text.clone()), 80.0, 56.0]) {
widgets::field_label(ui, text);
let current = label(ppi);
if let Some(v) =
widgets::dropdown_with(ui, ("cb-crop", "ppi-list"), &current, &names, 80.0, |i| PPI_CHOICES.get(i).is_some_and(|v| *v <= max + 1e-6))
.and_then(|i| PPI_CHOICES.get(i))
{
set_option(app, "ppi", json!(v));
}
// An image's own resolution above the limit (a linked image's, or one past 2400 ppi) still
// shows as it is; an edit there sets at most the limit.
if let Some(v) = widgets::range_field(ui, ("cb-crop", "ppi"), ppi, 1.0..=max.max(ppi).max(1.0), "", 2, 56.0) {
set_option(app, "ppi", json!(v.min(max.max(1.0))));
}
}
fit.separator(ui);
// The reference point locator is 23 pt square.
if fit.room(ui, &[23.0])
&& let Some(i) = widgets::reference_point(ui, reference)
{
set_option(app, "reference", json!(i));
}
let units = app.session.general_unit();
let p = vectorcraft_geom::reference_point(r, reference);
for (k, lbl, v) in [("x", "X:", p.x), ("y", "Y:", p.y), ("width", "W:", r.width()), ("height", "H:", r.height())] {
let text = egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim);
if !fit.room(ui, &[widgets::text_width(ui, text.clone()), 80.0]) {
let widths =
if k == "height" { vec![22.0, widgets::text_width(ui, text.clone()), 80.0] } else { vec![widgets::text_width(ui, text.clone()), 80.0] };
if !fit.room(ui, &widths) {
break;
}
if k == "height"
&& widgets::icon_button(ui, if linked { "link" } else { "unlink" }, tl!("Constrain Width and Height Proportions"), linked, 22.0).clicked()
{
set_option(app, "linked", json!(!linked));
}
widgets::field_label(ui, text);
if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0) {
let (mut c, mut w, mut h) = (c, r.width(), r.height());
match k {
"x" => c.x = nv,
"y" => c.y = nv,
"width" => w = nv.max(0.0),
_ => h = nv.max(0.0),
}
let rect = [c.x - w / 2.0, c.y - h / 2.0, w, h];
app.run("tool.setOption", json!({ "key": "rect", "value": rect })).ok();
if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0)
&& let Some(b) = crop::edited_box(r, image, reference, linked, k, nv)
{
set_option(app, "rect", json!([b.x0, b.y0, b.width(), b.height()]));
}
}
fit.separator(ui);