Merge main into feat/decorative-brush-library

This commit is contained in:
dotCooCoo committed 2026-11-19 10:59:13 -08:00
commit 29695edb0f
96 files changed
+7147 -191

No files matched your search

+1
View File
@@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-anchor-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-appearance.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arc.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arc-three-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Three-Point Arc tool: an arc through its two ends and a third point |
| `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline |
+2
View File
@@ -128,6 +128,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
- 2026-11-18: Built-in Paint brush library: Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep, original art brushes generated in code that take the stroke color as tints. Thirteen built-in brush libraries; headline numbers unchanged.
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged.
@@ -162,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 18 A8.67 8.67 0 1 1 20 18"/><circle cx="4" cy="18" r="1.6"/><circle cx="12" cy="6" r="1.6"/><circle cx="20" cy="18" r="1.6"/></svg>

After

Width:  |  Height:  |  Size: 327 B

+97
View File
@@ -10,6 +10,7 @@ pub mod freeform;
pub mod gradient;
pub mod harmony;
pub mod libraries;
pub mod oklab;
pub mod palette_io;
pub mod recolor;
pub mod swatch;
@@ -340,6 +341,49 @@ pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
[r + m, g + m, b + m]
}
/// HSL (hue in degrees 0..360, saturation and lightness 0..1) of RGB numbers 0..1, with no color
/// conversion, as CSS Color 4 converts sRGB to HSL
/// (<https://www.w3.org/TR/css-color-4/#rgb-to-hsl>). The hue is 0 while the saturation is
/// powerless, and a color outside 0..1 that gives a negative saturation turns its hue by 180°. As in
/// the specification's conversion, a lightness of 0.00001 or less, a lightness less than 0.00001
/// below 1, or a saturation of 0.00001 or less reads as a gray.
pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] {
const EPSILON: f32 = 1e-5;
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let d = max - min;
let l = (max + min) / 2.0;
if d <= 0.0 {
return [0.0, 0.0, l];
}
let mut s = if l.abs() <= EPSILON || (1.0 - l).abs() < EPSILON { 0.0 } else { (max - l) / l.min(1.0 - l) };
let mut h = rgb_to_hsb([r, g, b])[0];
if s < 0.0 {
h += 180.0;
s = -s;
}
if s <= EPSILON {
return [0.0, 0.0, l];
}
let h = h.rem_euclid(360.0);
[if h >= 360.0 { 0.0 } else { h }, s, l]
}
/// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS
/// Color 4 converts HSL to sRGB (<https://www.w3.org/TR/css-color-4/#hsl-to-rgb>): the inverse of
/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range before the conversion, so -120°
/// gives the color of 240° and a hue of 10,000,000,000° the color of 280°. The specification's
/// sample code uses JavaScript's remainder operator and gives a different color for a negative hue.
pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] {
let h = h.rem_euclid(360.0);
let a = s * l.min(1.0 - l);
let f = |n: f32| {
let k = (n + h / 30.0).rem_euclid(12.0);
l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
};
[f(0.0), f(8.0), f(4.0)]
}
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
pub fn keep_model(orig: Color, new: Color) -> Color {
@@ -499,6 +543,59 @@ mod tests {
}
}
/// The HSL examples of CSS Color 4, section 7 (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>),
/// the first six rows, and two hues outside 0..360 that wrap into that range.
#[test]
fn hsl_follows_css_color_4() {
for (hsl, hex) in [
([0.0, 1.0, 0.5], "#ff0000"),
([120.0, 1.0, 0.5], "#00ff00"),
([120.0, 1.0, 0.25], "#008000"),
([120.0, 1.0, 0.75], "#80ff80"),
([240.0, 1.0, 0.5], "#0000ff"),
([60.0, 1.0, 0.5], "#ffff00"),
([360.0, 1.0, 0.5], "#ff0000"),
([-120.0, 1.0, 0.5], "#0000ff"),
] {
let [r, g, b] = hsl_to_rgb(hsl);
assert_eq!(Color::rgb(r, g, b).to_hex(), hex, "{hsl:?}");
}
let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]);
assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}");
let [h, s, l] = rgb_to_hsl(Color::rgb8(255, 128, 0).to_rgb_uncalibrated());
assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}");
// A gray has no hue: the hue is 0 and the saturation 0, at any lightness.
for v in [0.0, 0.25, 0.5, 1.0] {
assert_eq!(rgb_to_hsl([v, v, v]), [0.0, 0.0, v]);
}
// Black and white keep any hue and saturation they are given.
assert_eq!(hsl_to_rgb([200.0, 0.7, 0.0]), [0.0, 0.0, 0.0]);
assert_eq!(hsl_to_rgb([200.0, 0.7, 1.0]), [1.0, 1.0, 1.0]);
// A color past the gamut that gives a negative saturation turns its hue by 180°.
let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]);
assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}");
// A huge hue wraps before the channels are worked out: 10,000,000,000° is 280°.
let (huge, wrapped) = (hsl_to_rgb([10_000_000_000.0, 1.0, 0.5]), hsl_to_rgb([280.0, 1.0, 0.5]));
assert!((0..3).all(|i| (huge[i] - wrapped[i]).abs() < 1e-6), "{huge:?} {wrapped:?}");
}
/// The 216 web colors go to HSL and back to the same 8-bit color.
#[test]
fn hsl_roundtrip() {
let steps = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff];
for r in steps {
for g in steps {
for b in steps {
let c = Color::rgb8(r, g, b);
let [h, s, l] = rgb_to_hsl(c.to_rgb_uncalibrated());
assert!((0.0..360.0).contains(&h) && (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&l), "{}", c.to_hex());
let back = hsl_to_rgb([h, s, l]).map(|v| (v * 255.0).round() as u8);
assert_eq!(back, [r, g, b], "{}", c.to_hex());
}
}
}
}
#[test]
fn cmyk_conversions() {
assert_eq!(Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgb_uncalibrated(), [0.0, 0.0, 0.0]);
+14 -6
View File
@@ -99,18 +99,24 @@ pub fn builtin_library(id: &str) -> Option<Arc<SwatchLibrary>> {
// ---------- colour construction ----------
/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped.
/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. A linear channel below
/// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does
/// (<https://www.w3.org/TR/css-color-4/#color-conversion-code>).
pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
oklab_to_linear_srgb(l, a, b).map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) })
}
/// Linear sRGB of OKLab `(l, a, b)`, unclamped.
pub(crate) fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
let lin = [
[
4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3,
-1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3,
-0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3,
];
lin.map(|v| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 })
]
}
/// OKLab `[l, a, b]` of a colour's display RGB.
@@ -118,11 +124,13 @@ pub fn to_oklab(c: &Color) -> [f64; 3] {
srgb_to_oklab(c.to_rgb_uncalibrated())
}
/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded).
/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). A channel below −0.04045 is decoded
/// with the curve's sign turned, as CSS Color 4's extended sRGB does
/// (<https://www.w3.org/TR/css-color-4/#color-conversion-code>).
pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] {
let [r, g, b] = rgb.map(|v| {
let v = f64::from(v);
if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
if v.abs() <= 0.040_45 { v / 12.92 } else { v.signum() * ((v.abs() + 0.055) / 1.055).powf(2.4) }
});
let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt();
let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt();
+266
View File
@@ -0,0 +1,266 @@
//! OKLCH, the polar form of Oklab, as CSS Color 4 defines it
//! (<https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch>): lightness L from 0 to 1, chroma
//! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take
//! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`].
use crate::libraries::{oklab_to_linear_srgb, oklab_to_srgb, srgb_to_oklab};
/// The chroma CSS reads as 100%.
pub const CHROMA_FULL: f64 = 0.4;
/// Chroma at or below which the hue is powerless (CSS Color 4's ε); [`to_oklch`] gives hue 0 there.
pub const POWERLESS_CHROMA: f64 = 0.000_004;
/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
const GAMUT_SLACK: f64 = 1e-4;
/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
/// are. The hue is in 0..360, and 0 while the chroma is powerless.
pub fn to_oklch(rgb: [f32; 3]) -> [f64; 3] {
let [l, a, b] = srgb_to_oklab(rgb);
let c = a.hypot(b);
if c <= POWERLESS_CHROMA {
return [l, 0.0, 0.0];
}
[l, c, b.atan2(a).to_degrees().rem_euclid(360.0)]
}
/// sRGB (gamma encoded) of OKLCH `(l, c, h°)`, unclamped.
pub fn oklch_to_srgb(l: f64, c: f64, h: f64) -> [f64; 3] {
let (sin, cos) = h.to_radians().sin_cos();
oklab_to_srgb(l, c * cos, c * sin)
}
/// Whether sRGB `rgb` lies inside the sRGB gamut.
pub fn in_srgb(rgb: [f64; 3]) -> bool {
rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v))
}
/// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white.
pub fn max_chroma(l: f64, h: f64) -> f64 {
largest_fitting_chroma(l, h, f64::INFINITY)
}
/// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or
/// outside black and white.
///
/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
/// search finds each such chroma between the cubic's turning points and takes the largest one that
/// fits.
fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
if !(l > 0.0 && l < 1.0) || !h.is_finite() {
return 0.0;
}
let top = limit.min(0.5);
if top <= 0.0 {
return 0.0;
}
let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h));
if fits(top) {
return top;
}
let (sin, cos) = h.to_radians().sin_cos();
let lin = |c: f64| oklab_to_linear_srgb(l, c * cos, c * sin);
// The linear channels at chromas 0, s, 2s and 3s give each cubic's coefficients in t = c / s.
let s = top / 3.0;
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
let mut ends = vec![0.0];
for ch in 0..3 {
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
// The cubic rises or falls on each stretch between its turning points.
let mut cuts = vec![0.0, 3.0];
cuts.extend(turning_points(3.0 * k[3], 2.0 * k[2], k[1]).into_iter().filter(|t| *t > 0.0 && *t < 3.0));
cuts.sort_by(f64::total_cmp);
ends.extend(cuts.iter().map(|t| t * s));
for w in cuts.windows(2) {
for bound in bounds {
let (mut a, mut b) = (w[0], w[1]);
let fa = p(a) - bound;
if fa * (p(b) - bound) > 0.0 {
continue;
}
for _ in 0..60 {
let mid = (a + b) / 2.0;
if (p(mid) - bound) * fa > 0.0 { a = mid } else { b = mid }
}
ends.extend([a * s, b * s]);
}
}
}
ends.sort_by(|a, b| b.total_cmp(a));
ends.into_iter().flat_map(|c| [c, c - 1e-9]).find(|c| (0.0..=top).contains(c) && fits(*c)).unwrap_or(0.0)
}
/// The real roots of `a t² + b t + c`.
fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {
if a.abs() < 1e-15 {
return if b.abs() < 1e-15 { Vec::new() } else { vec![-c / b] };
}
let disc = b * b - 4.0 * a * c;
if disc < 0.0 {
return Vec::new();
}
let r = disc.sqrt();
vec![(-b - r) / (2.0 * a), (-b + r) / (2.0 * a)]
}
/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
let h = if h.is_finite() { h } else { 0.0 };
let exact = oklch_to_srgb(l, c, h);
let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
(rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
}
#[cfg(test)]
mod tests {
use super::*;
fn eight(rgb: [f32; 3]) -> [u8; 3] {
rgb.map(|v| (v * 255.0).round() as u8)
}
#[test]
fn red_has_the_oklch_of_the_oklab_matrices_and_converts_back() {
let [l, c, h] = to_oklch([1.0, 0.0, 0.0]);
assert!((l - 0.6280).abs() < 5e-5 && (c - 0.2577).abs() < 5e-5 && (h - 29.23).abs() < 5e-3, "{l} {c} {h}");
let (rgb, lowered) = from_oklch(l, c, h);
assert_eq!((eight(rgb), lowered), ([255, 0, 0], false));
}
/// CSS Color 4's examples convert to the hue its oklab() and oklch() forms give.
#[test]
fn the_polar_form_matches_the_css_examples() {
for ([l, a, b], [cl, cc, ch]) in
[([0.40101, 0.1147, 0.0453], [0.40101, 0.12332, 21.555]), ([0.65125, -0.0320, 0.1274], [0.65125, 0.13138, 104.097])]
{
let rgb = oklab_to_srgb(l, a, b).map(|v| v as f32);
let [ol, oc, oh] = to_oklch(rgb);
assert!((ol - cl).abs() < 1e-4 && (oc - cc).abs() < 1e-4 && (oh - ch).abs() < 0.05, "{ol} {oc} {oh}");
}
}
#[test]
fn the_216_web_colors_round_trip() {
let steps = [0u8, 0x33, 0x66, 0x99, 0xcc, 0xff];
for r in steps {
for g in steps {
for b in steps {
let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
let [l, c, h] = to_oklch(rgb);
assert_eq!(eight(from_oklch(l, c, h).0), [r, g, b], "{l} {c} {h}");
}
}
}
}
#[test]
fn grays_have_no_chroma_and_hue_zero() {
for v in [0.0, 0.5, 1.0] {
let [_, c, h] = to_oklch([v, v, v]);
assert!(c <= POWERLESS_CHROMA && h == 0.0, "{c} {h}");
}
}
/// A chroma past the gamut gives a color inside it with the same lightness and hue, and says so.
#[test]
fn a_chroma_past_the_gamut_is_lowered_keeping_lightness_and_hue() {
let (l, h) = (0.7, 150.0);
let max = max_chroma(l, h);
assert!(max > 0.05 && max < CHROMA_FULL, "{max}");
assert!(in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h)));
let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
assert!(lowered);
let [ol, oc, oh] = to_oklch(rgb);
assert!((ol - l).abs() < 2e-3 && (oh - h).abs() < 1.0 && (oc - max).abs() < 2e-3, "{ol} {oc} {oh}");
assert!(!from_oklch(l, max * 0.5, h).1);
}
/// At the lightness and hue of blue the ray leaves sRGB and comes back at blue itself, so the
/// largest chroma is blue's, and a chroma past it gives blue.
#[test]
fn the_largest_chroma_at_blues_hue_is_blues() {
let [l, c, h] = to_oklch([0.0, 0.0, 1.0]);
let max = max_chroma(l, h);
assert!((max - c).abs() < 1e-4 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}");
let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
assert_eq!((eight(rgb), lowered), ([0, 0, 255], true));
// A chroma between the two stretches takes the end of the first one, inside sRGB.
let (rgb, lowered) = from_oklch(l, 0.29, h);
let [_, gc, _] = to_oklch(rgb);
assert!(lowered && gc < 0.27 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
// A hue just past blue's: a narrow second stretch ends just below the line from black to blue.
let (l, h) = (0.44, 264.06);
let max = max_chroma(l, h);
assert!(max > 0.304 && max < 0.305 && in_srgb(oklch_to_srgb(l, max, h)), "{max}");
let [_, got, _] = to_oklch(from_oklch(l, 0.35, h).0);
assert!(got > 0.303, "{got}");
// A darker blue on the line from black to blue.
let [l, c, h] = to_oklch([0.0, 0.0, 0.25]);
assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h));
}
/// Just below blue's lightness the line from black to blue passes a chroma of 0.3125, where a
/// search from 0 to 0.5 lands first. A chroma asked for below that line still gives a color
/// inside sRGB with the lightness and hue asked for.
#[test]
fn a_chroma_below_the_line_from_black_to_blue_stays_inside_srgb() {
let [bl, bc, h] = to_oklch([0.0, 0.0, 1.0]);
let l = bl * 0.3125 / bc;
let (rgb, lowered) = from_oklch(l, 0.29, h);
let [gl, gc, gh] = to_oklch(rgb);
assert!(lowered && gc < 0.29 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
assert!((gl - l).abs() < 2e-3 && (gh - h).abs() < 1.0, "{gl} {gh}");
}
/// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's
/// extended sRGB does, in both directions.
#[test]
fn negative_channels_use_the_signed_transfer_curve() {
let linear = -((0.5_f64 + 0.055) / 1.055).powf(2.4);
let [l, c, _] = to_oklch([-0.5; 3]);
assert!((l - linear.cbrt()).abs() < 1e-4 && c <= POWERLESS_CHROMA, "{l} {c}");
for v in oklch_to_srgb(linear.cbrt(), 0.0, 0.0) {
assert!((v + 0.5).abs() < 1e-4, "{v}");
}
// Small values near 0 keep the straight part of the curve.
let [l, _, _] = to_oklch([-0.01; 3]);
assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}");
}
/// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
/// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
/// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
#[test]
fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
let max = max_chroma(l, h);
assert!(in_srgb(oklch_to_srgb(l, max, h)) && max >= scan(l, h), "L {l} H {h}: {max} < {}", scan(l, h));
}
}
}
#[test]
fn black_white_and_bad_numbers_hold_no_chroma() {
assert_eq!(max_chroma(0.0, 30.0), 0.0);
assert_eq!(max_chroma(1.0, 30.0), 0.0);
assert_eq!(max_chroma(f64::NAN, 30.0), 0.0);
assert_eq!(max_chroma(0.5, f64::INFINITY), 0.0);
assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
}
}
+13
View File
@@ -451,12 +451,25 @@ impl TextObject {
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
/// exist, a degenerate `xf` or a path that would not be finite.
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
self.set_path_handle_with_symmetry((si, ai), out, pos, independent, false)
}
/// [`Self::set_path_handle`] with an optional mirror of the opposite handle about the anchor
/// in document space, preserving the anchor kind. `independent` takes precedence, and at an
/// open end of the path, where no segment leaves the anchor on that side, the handle moves as
/// it would without `symmetric`. Both handles are edited in one reshape, using the same validated
/// document-to-text map.
pub fn set_path_handle_with_symmetry(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool, symmetric: bool) -> bool {
let xf = self.xf;
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|path, to_text| {
let mirror = symmetric && !independent && path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, !out));
let Some(a) = path.anchor_mut(si, ai) else { return false };
let mut drawn = a.transform(xf);
drawn.set_handle(out, pos, independent);
if mirror {
let opposite = drawn.p - (pos - drawn.p);
if out { drawn.h_in = opposite } else { drawn.h_out = opposite }
}
*a = drawn.transform(to_text);
true
})
+84 -3
View File
@@ -175,6 +175,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
@@ -186,6 +187,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic },
];
/// Built-in library `id`, made once.
@@ -239,6 +241,42 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
}
/// Artistic: four original vector compositions that stretch along a path and take its color.
fn artistic() -> BrushLibrary {
let orbit = group(vec![
black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
]);
let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))];
for i in 0..6 {
let x = 9.0 + 16.0 * i as f64;
let side = if i % 2 == 0 { 1.0 } else { -1.0 };
petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)])));
}
let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))];
for i in 0..5 {
let x = 20.0 * i as f64;
lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)])));
lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)])));
}
let mut facets = Vec::new();
for i in 0..8 {
let x = 12.5 * i as f64;
let high = if i % 2 == 0 { 6.0 } else { 3.5 };
facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)])));
}
built(
"Artistic Brushes",
Document::new(100.0, 100.0),
vec![
art("Orbit Lines", orbit, Colorization::Tints),
art("Petal Garland", group(petals), Colorization::Tints),
art("Lattice Braid", group(lattice), Colorization::Tints),
art("Facet Sweep", group(facets), Colorization::Tints),
],
)
}
/// Original fine-line art for an engraving-style brush library.
fn engraving() -> BrushLibrary {
let lines = |count: usize, width: f64, spacing: f64| {
@@ -595,6 +633,45 @@ fn spacer(r: Rect) -> Node {
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
}
/// Paint: original filled vector art with broad, broken, loaded, and fanned marks. Each is one
/// stroke stretched along the path, with an intentionally different edge and paint distribution.
fn paint() -> BrushLibrary {
let flat_sweep = group(vec![
black(band(100.0, 5.0, 64, |x| 0.8 * (x / 100.0 * std::f64::consts::TAU).sin())),
black(polygon(&[(0.0, -2.5), (7.0, -3.8), (18.0, -2.5)])),
black(polygon(&[(78.0, 2.5), (94.0, 4.0), (100.0, 2.5)])),
]);
let mut dry_drag = vec![];
for (y, shift) in [(-5.0, 0.0), (-3.2, 4.0), (-1.3, 1.0), (0.8, 6.0), (2.8, 3.0), (4.8, 8.0)] {
dry_drag.push(black(shapes::rectangle(Rect::new(2.0 + shift, y, 35.0 + shift, y + 0.8))));
dry_drag.push(black(shapes::rectangle(Rect::new(40.0 + shift, y, 75.0 - shift / 2.0, y + 0.8))));
dry_drag.push(black(shapes::rectangle(Rect::new(80.0 - shift / 2.0, y, 98.0, y + 0.8))));
}
let mut loaded_stroke = vec![black(band(100.0, 6.0, 64, |x| 1.2 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin()))];
for (x, r) in [(12.0, 4.2), (39.0, 3.6), (64.0, 4.8), (88.0, 3.9)] {
loaded_stroke.push(black(shapes::ellipse(Rect::new(x - r, -r - 1.5, x + r, r + 1.5))));
}
let mut fan_sweep = vec![];
for i in -2..=2 {
let offset = i as f64;
fan_sweep.push(black(band(100.0, 1.2, 48, |x| offset * (1.4 + x * 0.045) + 0.3 * (x / 100.0 * std::f64::consts::TAU).sin())));
}
let paint_art = |name: &str, art: Node| Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush { art, width: 150.0, colorization: Colorization::Tints, ..Default::default() }),
};
built(
"Paint",
Document::new(100.0, 100.0),
vec![
paint_art("Flat Sweep", flat_sweep),
paint_art("Dry Drag", group(dry_drag)),
paint_art("Loaded Stroke", group(loaded_stroke)),
paint_art("Fan Sweep", group(fan_sweep)),
],
)
}
/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles.
fn pattern_borders() -> BrushLibrary {
let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)]));
@@ -1078,10 +1155,14 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>
return Some(found);
}
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
return Some((builtin_info(b), builtin_library(key)?));
return Some((builtin_info(b), builtin_library(b.id)?));
}
let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id;
library(s, &id)
if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) {
return library(s, &id);
}
// Keep the short built-in alias, but let a user or loaded library own its display name.
let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?;
Some((builtin_info(b), builtin_library(b.id)?))
}
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<BrushLibrary>)> {
+10 -5
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Color",
[],
None,
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first",
always,
convert_color
),
@@ -1362,10 +1362,15 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
let lab = c.lab(&col);
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
"rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
"cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
"gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
"lab" => ("lab", vec![lab.l, lab.a, lab.b]),
"rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))),
"cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))),
"gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))),
"lab" => ("lab", json!([lab.l, lab.a, lab.b])),
"oklch" => {
// RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them.
let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0)));
("oklch", json!([l * 100.0, ch, h]))
}
other => return Err(bad(C, format!("unknown model `{other}`"))),
};
let de = c.gamut_error(&col);
+53
View File
@@ -105,6 +105,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
arc
),
cmd!(
"shape.threePointArc",
"Three-Point Arc",
[],
None,
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
has_doc,
three_point_arc
),
cmd!(
"shape.rectangularGrid",
"Rectangular Grid",
@@ -680,6 +689,50 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
}
/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or
/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is.
fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.threePointArc";
let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]")));
let (start, end) = (point("start")?, point("end")?);
let from_end = match p.get("at") {
None => false,
Some(Value::String(v)) if v == "start" || v == "end" => v == "end",
Some(_) => return Err(bad(C, "`at` must be \"start\" or \"end\"")),
};
// The arc, and the point it passes through (an anchor of the path, so the path meets it exactly).
let (arc, via) = match (p.get("through"), p.get("toward")) {
(Some(_), None) if p.get("at").is_some() => return Err(bad(C, "give `at` only with `toward`")),
(Some(_), None) => {
let through = point("through")?;
(shapes::CircularArc::through(start, end, through), Some(through))
}
(None, Some(_)) if from_end => {
let toward = point("toward")?;
(shapes::CircularArc::arriving(start, end, end - toward), None)
}
(None, Some(_)) => {
let toward = point("toward")?;
(shapes::CircularArc::leaving(start, toward - start, end), None)
}
_ => return Err(bad(C, "give exactly one of `through` and `toward`")),
};
let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?;
let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v));
let look = s.new_art_look(
vectorcraft_color::Paint::None,
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
s.paint.stroke_width.max(0.1),
);
// Not pixel-aligned: the ends stay on the given points.
let mut out = insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, 0.0, false)?;
out["cx"] = json!(arc.center.x);
out["cy"] = json!(arc.center.y);
out["radius"] = json!(arc.radius);
out["sweep"] = json!(arc.sweep.to_degrees());
Ok(out)
}
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
/// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group
/// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle).
+16
View File
@@ -244,12 +244,22 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
Some(_) => return Err(bad(C, "handle must be in or out")),
};
let independent = switch_or(p, "independent", false, C)?;
let symmetric = switch_or(p, "symmetric", false, C)?;
let link = switch_or(p, "link", false, C)?;
let with = spine_points_param(p, C)?;
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "`with` moves points, not a handle"));
}
if symmetric && independent {
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
}
if symmetric && handle.is_none() {
return Err(bad(C, "`symmetric` places a handle: give `handle`"));
}
if link && symmetric {
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
}
if link && independent {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
@@ -264,6 +274,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
}
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
// At an open end of the spine the handle moves as it would without `symmetric`.
let symmetric = symmetric && pull_out;
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
if let Some(out) = handle {
if link {
@@ -271,6 +283,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
} else {
a.set_handle(out, q, independent);
}
if symmetric {
let opposite = a.p - (q - a.p);
if out { a.h_in = opposite } else { a.h_out = opposite }
}
return Ok(());
}
let delta = q - a.p;
+1 -1
View File
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Spine Point",
[],
None,
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `symmetric` and `link` need `handle`, `symmetric` cannot go with `independent`, and `link` cannot go with `independent` or `symmetric`; all default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
has_doc,
spine_move_anchor
),
+26 -1
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Direction Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle",
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
has_doc,
set_handle
),
@@ -461,6 +461,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
return link_handle(s, p, id, si, ai, out, pos);
}
let independent = switch_or(p, "independent", false, "path.setHandle")?;
let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?;
if symmetric && independent {
return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true"));
}
// The other handle is mirrored only where a segment leaves the anchor on its side: at an open
// end the handle moves as it would without `symmetric`.
let symmetric = symmetric && has_segment(s, id, si, ai, !out)?;
let at = match p.get("at").filter(|v| !v.is_null()) {
None => None,
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?),
@@ -472,6 +479,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
&& at.is_none_or(|to| to == a.p)
&& (if out { a.h_out } else { a.h_in }) == pos
&& !(independent && a.kind != AnchorKind::Corner)
&& (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p))
{
return ok();
}
@@ -504,6 +512,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
} else {
a.set_handle(out, pos, independent);
}
if symmetric {
let opposite = a.p - (pos - a.p);
if out { a.h_in = opposite } else { a.h_out = opposite }
}
Ok(())
})?;
ok()
@@ -519,6 +531,9 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
if switch_or(p, "independent", false, C)? {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
if switch_or(p, "symmetric", false, C)? {
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
}
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
return Err(bad(C, "x and y must be finite"));
}
@@ -655,6 +670,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anc
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
}
/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or
/// incoming side; false when the path, subpath or anchor is not there.
fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result<bool> {
if s.script_running() {
return Err(EngineError::Busy);
}
let d = &s.doc()?.doc;
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
}
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?;
let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?;
@@ -572,6 +572,7 @@ pub(super) const ALLOWED: &[&str] = &[
"shape.rectangularGrid",
"shape.spiral",
"shape.star",
"shape.threePointArc",
"shapeBuilder.merge",
"shapeBuilder.regions",
"shaper.expand",
+7
View File
@@ -752,6 +752,13 @@ impl Session {
t.set_option("cornerRadius", &r);
}
}
// A press of the tool that is dropped keeps the new radius, also when the tool lent a
// selection tool for the press.
if self.press_taken_by("roundedRectangle")
&& let Some((_, saved)) = self.press_options.as_mut()
{
saved.insert("cornerRadius".into(), r);
}
}
if fonts_folder_changed {
let folder = self.prefs.fonts_folder.trim();
+6 -2
View File
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Type Path Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
has_doc,
set_path_handle
),
@@ -1449,6 +1449,10 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
let independent = switch_or(p, "independent", false, C)?;
let symmetric = switch_or(p, "symmetric", false, C)?;
if symmetric && independent {
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
}
let node = s.doc()?.doc.node(id);
let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. }));
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
@@ -1461,7 +1465,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
let within = |t: &TextObject| {
t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD))
};
if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) {
if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) {
t.kind = before;
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
}
+3
View File
@@ -329,6 +329,9 @@ pub struct Session {
/// The id and persistent options of the tool when the press under way began, which a dropped
/// press puts back ([`Session::drop_tool_press`]).
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
/// An option of the active tool was set during the press under way, which stored all of its
/// options, so a dropped press stores the options it puts back.
pub(crate) press_options_stored: bool,
/// The engine saves the selection and active layer before a Type press and restores them if it drops.
pub(crate) press_type_selection: Option<(Selection, Option<NodeId>)>,
/// The freeform gradient point selected once the tool took the press under way, which a
+1
View File
@@ -137,6 +137,7 @@ impl Session {
plane_widget_press: false,
pointer_held: false,
press_options: None,
press_options_stored: false,
press_type_selection: None,
press_point: None,
ruler_guide: None,
+1
View File
@@ -208,6 +208,7 @@ mod targeting;
mod textcombos;
mod textedit;
pub(super) mod textimport;
mod three_point_arc;
mod tileedge;
mod tints;
mod toolsettings;
+96 -1
View File
@@ -112,6 +112,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"calligraphic-nibs",
"pressure-sensitive",
"bristle-brushes",
"paint",
"pattern-borders",
"decorative",
"scatter-shapes",
@@ -122,7 +123,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"tech-circuit",
"engraving",
"arrows",
"image-brush"
"image-brush",
"artistic"
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
@@ -191,6 +193,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
("calligraphic-nibs", "calligraphic"),
("pressure-sensitive", "art"),
("bristle-brushes", "bristle"),
("paint", "art"),
("pattern-borders", "pattern"),
("decorative", "pattern"),
("scatter-shapes", "scatter"),
@@ -200,6 +203,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
("dry-media", "art"),
("arrows", "art"),
("image-brush", "scatter"),
("artistic", "art"),
] {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.len() >= 4, "{id}");
@@ -228,6 +232,46 @@ fn builtin_library_brushes_bring_the_resources_their_art_uses() {
assert!(shapes.doc.symbols.iter().any(|x| x.name == "Sparkle"));
}
#[test]
fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap();
let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap();
assert_eq!(alias.brushes, lib.brushes);
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic");
let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap();
let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0);
for b in &lib.brushes {
let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) };
assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name);
for path in [line_to(180.0), line_to(1.0)] {
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name);
}
// The art is black, so with Tints every path takes the stroke color itself.
let mut fills = vec![];
for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) {
piece.walk(&mut |n| {
if n.path_data().is_some() {
fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb()));
}
});
}
let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5);
assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name);
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([line]));
assert_eq!(undo_len(&s), before + 1);
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
let mut s = session();
@@ -265,6 +309,26 @@ fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
assert_eq!(reopened.images, lib.doc.images);
}
#[test]
fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() {
let mut file = vectorcraft_doc::Document::new(100.0, 100.0);
vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]);
let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file));
let mut s = session();
let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"}));
assert_eq!(loaded["name"], "Artistic");
let id = loaded["library"].as_str().unwrap();
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id);
assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id);
assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works");
// A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id.
let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"}));
assert_eq!(full["name"], "Artistic Brushes");
let full_id = full["library"].as_str().unwrap();
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic");
assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id);
}
/// Every path of brush art `n`: (anchors, opacity).
fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> {
let mut out = vec![];
@@ -599,6 +663,37 @@ fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_librar
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn paint_brushes_draw_distinct_marks_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Paint").unwrap();
let names = ["Flat Sweep", "Dry Drag", "Loaded Stroke", "Fan Sweep"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
let mut curve = line_to(20.0);
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
for b in &lib.brushes {
let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) };
assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints);
assert_eq!(art.width, 150.0);
for line in [line_to(2.0), line_to(180.0), curve.clone()] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
let points = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
}
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "paint", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([path]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
/// translucent washes, with names of their own and a few paths of art each.
#[test]
+39
View File
@@ -318,6 +318,45 @@ fn convert_query_and_intents() {
assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err());
}
/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color;
/// a CMYK color's display color, not its naive separation, sets them.
#[test]
fn convert_to_oklch_answers_lightness_chroma_and_hue() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap();
assert_eq!(r["model"], "oklch");
let v: Vec<f64> = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}");
let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]);
assert!(!lowered);
assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000");
assert_eq!(r["hex"], "#ff0000");
let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap();
assert_eq!(gray["values"][2], 0.0, "{gray}");
let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0});
let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap();
let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0)));
let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]);
let c: Vec<f64> = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let got = [c[0] / 100.0, c[1], c[2]];
assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}");
assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}");
// A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB.
let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap();
let w: Vec<f64> = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0));
let clipped = vectorcraft_color::oklab::to_oklch(shown);
assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}");
assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}");
assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}");
// RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white.
let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap();
assert_eq!(past["hex"], "#ffffff");
let l = past["values"][0].as_f64().unwrap();
assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}");
}
#[test]
fn assign_profile_is_stored_and_undoable() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+220
View File
@@ -0,0 +1,220 @@
//! `shape.threePointArc`: an open circular arc between two ends, through a third point or
//! leaving an end toward it, and the Three-Point Arc tool's clicks that run it.
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_geom::Point;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::*;
const C: &str = "shape.threePointArc";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).unwrap().clone()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn object_count(s: &Session) -> usize {
let mut n = 0;
s.doc().unwrap().doc.walk(|_| n += 1);
n
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
/// The largest distance of `points` from the path of `id`.
fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 {
let n = node(s, id);
let path = n.path_data().unwrap();
points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max)
}
/// The arc from (0, 0) to (80, 0) through (40, -40) is the upper half of the circle about
/// (40, 0) with radius 40: an open path from one end to the other, through the third point, with
/// no fill and a stroke, selected, and one undo step.
#[test]
fn the_arc_through_a_third_point_is_an_open_path_and_one_undo_step() {
let mut s = session();
let undo = undo_len(&s);
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "through": [40, -40]})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}");
// From (0, 0) over the top to (80, 0): clockwise on the page.
assert!((out["sweep"].as_f64().unwrap() - 180.0).abs() < 1e-9, "{out}");
let id = id_of(&out);
let n = node(&s, id);
let NodeKind::Path { path, live: None, .. } = &n.kind else { panic!("not a plain path: {:?}", n.kind) };
let sp = &path.subpaths[0];
assert!(!sp.closed && path.subpaths.len() == 1);
assert_eq!((sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)), (Some(Point::ORIGIN), Some(Point::new(80.0, 0.0))));
assert!(farthest_from_path(&s, id, &[Point::new(40.0, -40.0)]) < 1e-9);
assert!(n.appearance.fill_paint().is_none(), "no fill");
assert!(!n.appearance.stroke_paint().is_none(), "a stroke");
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert_eq!(undo_len(&s), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(id).is_none());
// A third point between the quarter turns is an anchor too, so the path meets it exactly.
let via = Point::new(1000.0 * 20f64.to_radians().cos(), 1000.0 * 20f64.to_radians().sin());
let out = s.execute(C, &json!({"start": [1000, 0], "end": [0, 1000], "through": [via.x, via.y]})).unwrap();
let id = id_of(&out);
assert!(node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().any(|a| a.p == via));
assert!(farthest_from_path(&s, id, &[via]) < 1e-9);
}
/// With `toward`, the arc leaves `start` heading at the point (its first handle points there),
/// or with `at: "end"` arrives at `end` along the line from the point to `end` (run backward, the
/// arc leaves `end` heading at the point).
#[test]
fn the_arc_toward_a_point_has_that_tangent_at_its_end() {
let mut s = session();
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [30, -30]})).unwrap();
let n = node(&s, id_of(&out));
let first = n.path_data().unwrap().subpaths[0].anchors[0];
let d = (first.h_out - first.p).normalize();
assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, -1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}");
// A quarter turn's tangent: the center is at (40, 40) and the radius √3200.
assert!((out["radius"].as_f64().unwrap() - 3200f64.sqrt()).abs() < 1e-9, "{out}");
let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [50, -30], "at": "end"})).unwrap();
let n = node(&s, id_of(&out));
let last = *n.path_data().unwrap().subpaths[0].anchors.last().unwrap();
let d = (last.p - last.h_in).normalize();
assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, 1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}");
// The direction from the start and from the end mirror each other.
assert!((out["cx"].as_f64().unwrap() - 40.0).abs() < 1e-9 && (out["cy"].as_f64().unwrap() - 40.0).abs() < 1e-9, "{out}");
}
/// Points that are the same, a third point on the line through the ends, and an arc reaching past
/// the canvas are refused with a message; nothing is drawn and no undo step is added.
#[test]
fn points_with_no_arc_are_refused() {
let mut s = session();
let (undo, count) = (undo_len(&s), object_count(&s));
for p in [
json!({"start": [0, 0], "end": [0, 0], "through": [10, 10]}),
json!({"start": [0, 0], "end": [80, 0], "through": [40, 0]}),
json!({"start": [0, 0], "end": [80, 0], "through": [120, 0]}),
json!({"start": [0, 0], "end": [80, 0], "through": [80, 0]}),
json!({"start": [0, 0], "end": [80, 0], "toward": [0, 0]}),
json!({"start": [0, 0], "end": [80, 0], "toward": [-50, 0]}),
json!({"start": [0, 0], "end": [80, 0], "toward": [40, 0], "at": "end"}),
json!({"start": [0, 0], "end": [0, 0], "toward": [10, 10]}),
] {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains("no arc fits these points"), "{p}: {e}");
}
// Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt down the page, and the
// arc goes round the far side of it.
let far = json!({"start": [0, 0], "end": [80, 0], "through": [200, 0.001]});
let e = s.execute(C, &far).unwrap_err().to_string();
assert!(e.contains("result would exceed the canvas"), "{e}");
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// Missing or malformed points, both or neither of `through` and `toward`, an `at` that is not
/// "start" or "end", and an `at` with `through` are errors; nothing is drawn.
#[test]
fn malformed_params_are_refused() {
let mut s = session();
let count = object_count(&s);
for (p, want) in [
(json!({"end": [80, 0], "through": [40, 40]}), "`start` must be [x, y]"),
(json!({"start": [0, 0], "end": [80], "through": [40, 40]}), "`end` must be [x, y]"),
(json!({"start": [0, 0], "end": [80, 0], "through": [40, "a"]}), "`through` must be [x, y]"),
(json!({"start": [0, 0], "end": [80, 0], "through": null}), "`through` must be [x, y]"),
(json!({"start": [0, 0], "end": [80, 0], "toward": [10, 0, 0]}), "`toward` must be [x, y]"),
(json!({"start": [0, 0], "end": [80, 0]}), "give exactly one of `through` and `toward`"),
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "toward": [0, 40]}), "give exactly one of `through` and `toward`"),
(json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": "middle"}), "`at` must be \"start\" or \"end\""),
(json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": null}), "`at` must be \"start\" or \"end\""),
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "end"}), "give `at` only with `toward`"),
(json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "start"}), "give `at` only with `toward`"),
] {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
}
assert_eq!(object_count(&s), count);
}
/// With Align New Objects to Pixel Grid on, the ends stay on the given points.
#[test]
fn the_arc_is_not_moved_onto_the_pixel_grid() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let id = id_of(&s.execute(C, &json!({"start": [0.3, 0.2], "end": [80.6, 0.1], "through": [40.4, -39.7]})).unwrap());
let n = node(&s, id);
let sp = &n.path_data().unwrap().subpaths[0];
assert_eq!(sp.anchors.first().map(|a| a.p), Some(Point::new(0.3, 0.2)));
assert_eq!(sp.anchors.last().map(|a| a.p), Some(Point::new(80.6, 0.1)));
assert!(!n.extras().pixel_aligned);
}
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..ViewInfo::default() }
}
fn click(s: &mut Session, x: f64, y: f64) {
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, x, y).with_mods(Mods::default()), view()).unwrap();
}
}
/// With the Three-Point Arc tool, three clicks draw the arc in one undo step; `]` before the third
/// click makes the third point give the direction instead. Escape drops the ends.
#[test]
fn three_clicks_with_the_tool_draw_the_arc() {
let mut s = session();
s.select_tool("threePointArc", view()).unwrap();
let (undo, count) = (undo_len(&s), object_count(&s));
click(&mut s, 100.0, 200.0);
click(&mut s, 180.0, 200.0);
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two ends draw nothing yet");
click(&mut s, 140.0, 160.0);
assert_eq!(undo_len(&s), undo + 1);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(farthest_from_path(&s, id, &[Point::new(100.0, 200.0), Point::new(140.0, 160.0), Point::new(180.0, 200.0)]) < 1e-9);
// Escape after the ends: the next clicks start afresh.
click(&mut s, 0.0, 0.0);
click(&mut s, 10.0, 300.0);
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
click(&mut s, 100.0, 300.0);
click(&mut s, 180.0, 300.0);
s.tool_key(ToolKey::BracketRight, Mods::default(), view()).unwrap();
let undo = undo_len(&s);
// Straight up from the first end: the upper half circle about (140, 300).
click(&mut s, 100.0, 250.0);
assert_eq!(undo_len(&s), undo + 1);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9);
}
/// `tool.setOption` (the Tool Options dialog's Save) sets the tool's `direction` option, and
/// refuses a value that is not true or false, or an option the tool doesn't have.
#[test]
fn set_option_sets_the_direction_and_refuses_bad_values() {
let mut s = session();
for on in [true, false] {
let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"direction": on}})).unwrap();
assert_eq!(set["direction"], json!(on));
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(on));
}
let cases = [
(json!({"tool": "threePointArc", "key": "direction", "value": "yes"}), "tool `threePointArc`: `direction` must be true or false"),
(json!({"tool": "threePointArc", "key": "bogus", "value": true}), "tool `threePointArc`: unknown option `bogus`"),
];
for (p, want) in cases {
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
}
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false));
}
+80
View File
@@ -138,6 +138,86 @@ fn a_dropped_press_does_not_keep_what_its_drag_changed() {
assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides");
}
/// An option set with `tool.setOption` while a press is held survives the dropped press, in the
/// tool and in the stored options, while what the drag itself changed is put back in both.
#[test]
fn an_option_set_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "rectangularGrid");
let v = ViewInfo { smart_guides: false, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!((s.tool_options()["rows"].clone(), s.tool_options()["columns"].clone()), (json!(6), json!(6)));
s.set_tool_option_cmd(&json!({"key": "columns", "value": 9})).unwrap();
s.drop_tool_press(v).unwrap();
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "the drag's rows go back; the set columns stay");
let saved = &s.prefs.tool_settings["rectangularGrid"];
assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(9)), "the drag's rows are not stored; the set columns are");
select(&mut s, "selection");
select(&mut s, "rectangularGrid");
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "a tool switch keeps the set columns");
// The same through the desktop app's setter.
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
s.set_tool_option("columns", &json!(3));
s.drop_tool_press(v).unwrap();
let o = s.tool_options();
assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(3)));
let saved = &s.prefs.tool_settings["rectangularGrid"];
assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(3)));
}
/// A Corner Radius preference set while a Rounded Rectangle press is held survives the dropped
/// press, in the tool and in the preference.
#[test]
fn a_corner_radius_set_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "roundedRectangle");
let v = ViewInfo { smart_guides: false, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
let mut p = s.prefs.clone();
p.corner_radius = 30.0;
s.apply_prefs(p);
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
}
/// An option set with `tool.setOption` on a tool that lent a selection tool for a Cmd-drag
/// survives the dropped press, in the tool and in the stored options. So does a Corner Radius
/// preference set while the Rounded Rectangle lends one.
#[test]
fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() {
let mut s = session();
select(&mut s, "rectangularGrid");
let v = ViewInfo { smart_guides: false, ..Default::default() };
let cmd = Mods { cmd: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("rectangularGrid"), "the press lent a selection tool");
s.set_tool_option_cmd(&json!({"tool": "rectangularGrid", "key": "columns", "value": 9})).unwrap();
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_id(), "rectangularGrid", "the lending tool is back");
assert_eq!(s.tool_options()["columns"], json!(9), "the tool keeps the set columns");
assert_eq!(s.prefs.tool_settings["rectangularGrid"]["columns"], json!(9), "and stores them");
select(&mut s, "roundedRectangle");
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap();
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("roundedRectangle"), "the press lent a selection tool");
let mut p = s.prefs.clone();
p.corner_radius = 30.0;
s.apply_prefs(p);
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius");
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
}
/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with
/// the next click.
#[test]
+66 -7
View File
@@ -298,6 +298,10 @@ impl Session {
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
lent.set_option("meshPoints", &points);
}
// The Cmd/Ctrl held for the loan is not the Cmd/Ctrl that mirrors a dragged handle (#7842).
if id == "directSelection" {
lent.set_option("lentByCmd", &Value::Bool(true));
}
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
@@ -611,13 +615,18 @@ impl Session {
/// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what
/// the tool asks for along the way, only a cancel and a notify run, so a marquee selects
/// nothing and a click opens no size dialog. The tool gets back the persistent options it had
/// when the press began, and none of the press's changes to them are stored. A dropped Type
/// press restores the prior selection. The freeform gradient point selected once the tool
/// took the press is selected again. A press held while the tool computes an edit on another
/// thread has not reached the tool: it is removed from the held input with the pointer events
/// and tool keys held after it, and the tool is left as it is. A perspective plane key held
/// after it stays held, since the plane it picks outlasts a dropped press. Pointer events held
/// after the last held release belong to the press the tool has, and are removed with it.
/// when the press began, and none of the press's changes to them are stored. An option set
/// during the press with [`Self::set_tool_option`] or [`Self::set_tool_options`], or a General ›
/// Corner Radius change during a Rounded Rectangle press, keeps its new value, also when the
/// tool lent a selection tool for the press (a Cmd-drag). Setting an option stores all of the
/// tool's options, the press's changes included, so the dropped press then stores the options
/// it puts back. A dropped Type press restores the prior selection. The freeform gradient
/// point selected once the tool took the press is selected again. A press held while the tool
/// computes an edit on another thread has not reached the tool: it is removed from the held
/// input with the pointer events and tool keys held after it, and the tool is left as it is.
/// A perspective plane key held after it stays held, since the plane it picks outlasts a
/// dropped press. Pointer events held after the last held release belong to the press the tool
/// has, and are removed with it.
pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> {
let (from, held) = self.held_press();
let keep: Vec<bool> = (self.held_input.iter().enumerate())
@@ -635,6 +644,7 @@ impl Session {
// Nothing to roll back without a document; the tool still drops the press and gets the release.
let _ = self.cancel_interaction();
let before = self.press_options.take();
let stored = std::mem::take(&mut self.press_options_stored);
let type_selection = self.press_type_selection.take();
let point = self.press_point.take();
let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx));
@@ -669,6 +679,11 @@ impl Session {
self.tool.set_option(k, v);
}
}
// An option set during the press stored every option the tool had then, the press's
// changes included: those stored values are put back too.
if stored {
self.keep_tool_settings();
}
}
r.map(drop)
}
@@ -706,6 +721,7 @@ impl Session {
match ev.kind {
PointerKind::Down => {
self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref())));
self.press_options_stored = false;
self.press_type_selection =
if matches!(self.tool.id(), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath") {
self.active().map(|st| (st.selection.clone(), st.active_layer))
@@ -715,6 +731,7 @@ impl Session {
}
PointerKind::Up => {
self.press_options = None;
self.press_options_stored = false;
self.press_type_selection = None;
}
_ => {}
@@ -1309,9 +1326,12 @@ impl Session {
if key == "queue" && self.tool.id() == "place" {
self.note_place_queue_roots();
}
let before_press = self.options_before_press_set();
let sets_pressed = self.press_taken_by(self.tool.id());
self.tool.set_option(key, v);
self.tool_set_since_reset = true;
self.keep_tool_settings();
self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed);
}
/// Keep the automation roots in force now as those the place cursor's queue, being loaded,
@@ -1356,6 +1376,8 @@ impl Session {
self.note_place_queue_roots();
}
let active = id.is_none_or(|id| id == self.tool.id());
let before_press = self.options_before_press_set();
let sets_pressed = self.press_taken_by(id.unwrap_or(self.tool.id()));
// The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again
// when the drag ends.
let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id));
@@ -1393,9 +1415,46 @@ impl Session {
let set = other.id();
Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store));
}
self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed);
out
}
/// The tool that took the press under way: the active tool, or the tool that lent a selection
/// tool for it (a Cmd-drag), which the dropped press gives its options back to.
fn pressed_tool(&self) -> Option<&dyn Tool> {
let (pressed, _) = self.press_options.as_ref()?;
std::iter::once(&self.tool).chain(self.lender.as_ref()).map(|t| t.as_ref()).find(|t| t.id() == pressed)
}
/// Tool `id` took the press under way ([`Self::pressed_tool`]).
pub(crate) fn press_taken_by(&self, id: &str) -> bool {
self.pressed_tool().is_some_and(|t| t.id() == id)
}
/// The persistent options of the tool that took the press under way ([`Self::pressed_tool`])
/// before an option is set: a dropped press puts back the options it began with, except those
/// the set changes ([`Self::keep_press_set`]).
fn options_before_press_set(&self) -> Option<Map<String, Value>> {
self.pressed_tool().map(Self::persistent_options)
}
/// After an option is set during a held press, the press's saved options take the options of
/// the tool that took the press that the set changed from `before` or named (`named`), so a
/// dropped press keeps them. `stored`: the set stored that tool's options, the press's changes
/// included, so a dropped press stores the options it puts back.
fn keep_press_set(&mut self, before: Option<Map<String, Value>>, named: impl Fn(&str) -> bool, stored: bool) {
let Some(before) = before else { return };
let Some(now) = self.pressed_tool().map(Self::persistent_options) else { return };
self.press_options_stored |= stored;
if let Some((_, saved)) = self.press_options.as_mut() {
for (k, v) in now {
if before.get(&k) != Some(&v) || named(&k) {
saved.insert(k, v);
}
}
}
}
/// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the
/// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default:
/// the tool active when the call arrives, named before the edit in progress is finished) → its
+630
View File
@@ -0,0 +1,630 @@
//! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeId};
use vectorcraft_engine::{Session, ViewInfo};
use vectorcraft_geom::{Anchor, AnchorKind, Point};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
fn run(s: &mut Session, command: &str, params: Value) -> Value {
s.execute(command, &params).unwrap()
}
fn view() -> ViewInfo {
ViewInfo {
smart_guides: false,
guides: false,
snap_to_point: false,
snap_to_grid: false,
snap_to_pixel: false,
snap_to_glyph: false,
corner_widgets: false,
show_bbox: false,
..ViewInfo::default()
}
}
fn session() -> Session {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 900, "height": 700}));
for (key, value) in [("constrainAngle", json!(0)), ("showHandlesMultipleAnchors", json!(true)), ("realTimeDrawing", json!(true))] {
run(&mut s, "prefs.set", json!({"key": key, "value": value}));
}
s
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).unwrap().clone()
}
fn curve(s: &mut Session, incoming: Point) -> NodeId {
let id = run(
s,
"path.create",
json!({"anchors": [
{"x": 20, "y": 220},
{"x": 100, "y": 100, "in": [incoming.x, incoming.y], "out": [180, 100]},
{"x": 320, "y": 220}
]}),
);
let id = NodeId(id["id"].as_u64().unwrap());
s.select_tool("directSelection", view()).unwrap();
id
}
fn anchor(s: &Session, id: NodeId) -> Anchor {
node(s, id).path_data().unwrap().subpaths[0].anchors[1]
}
fn pointer(s: &mut Session, kind: PointerKind, at: Point, mods: Mods) {
s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(mods), view()).unwrap();
}
fn press_handle(s: &mut Session, at: Point) {
pointer(s, PointerKind::Down, at, Mods::default());
assert_eq!(s.tool_id(), "directSelection");
assert!(s.in_interaction(), "the visible handle press begins Reshape");
}
fn near(actual: Point, expected: Point) {
assert!(actual.distance(expected) < 1e-6, "point {actual:?}, expected {expected:?}");
}
fn handles(a: Anchor, incoming: Point, outgoing: Point, kind: AnchorKind) {
near(a.h_in, incoming);
near(a.h_out, outgoing);
assert_eq!(a.kind, kind);
}
fn assert_other_geometry(s: &Session, id: NodeId, before: &Node) {
let after = node(s, id);
let (old, new) = (before.path_data().unwrap(), after.path_data().unwrap());
assert_eq!(new.subpaths.len(), old.subpaths.len());
assert_eq!(new.subpaths[0].closed, old.subpaths[0].closed);
assert_eq!(new.subpaths[0].anchors.len(), 3);
assert_eq!(new.subpaths[0].anchors[0], old.subpaths[0].anchors[0]);
assert_eq!(new.subpaths[0].anchors[2], old.subpaths[0].anchors[2]);
assert_eq!(new.subpaths[0].anchors[1].p, old.subpaths[0].anchors[1].p);
assert_eq!(after.appearance, before.appearance);
}
#[test]
fn direct_handle_baseline_ordinary_smooth_keeps_the_opposite_length() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let before = node(&s, id);
assert_eq!(anchor(&s, id).kind, AnchorKind::Smooth);
let selection = json!(s.doc().unwrap().selection);
let undo = s.doc().unwrap().history.undo.len();
press_handle(&mut s, Point::new(180.0, 100.0));
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, Mods::default());
handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
assert_other_geometry(&s, id, &before);
pointer(&mut s, PointerKind::Up, q, Mods::default());
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
assert_eq!(json!(s.doc().unwrap().selection), selection);
}
#[test]
fn direct_handle_baseline_cmd_added_mid_drag_mirrors_the_opposite() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let before = node(&s, id);
press_handle(&mut s, Point::new(180.0, 100.0));
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, Mods::default());
handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
pointer(&mut s, PointerKind::Drag, q, Mods { cmd: true, ..Mods::default() });
handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth);
assert_other_geometry(&s, id, &before);
pointer(&mut s, PointerKind::Up, q, Mods { cmd: true, ..Mods::default() });
}
#[test]
fn direct_handle_cmd_mirror_holds_through_a_space_translation() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
press_handle(&mut s, Point::new(180.0, 100.0));
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth);
// Space moves the anchor and both handles; the opposite handle stays mirrored.
let moved = Point::new(200.0, 190.0);
pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() });
let a = anchor(&s, id);
near(a.p, Point::new(120.0, 130.0));
handles(a, Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth);
// Releasing Space without moving keeps the translated, mirrored handles.
pointer(&mut s, PointerKind::Drag, moved, cmd());
handles(anchor(&s, id), Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth);
let next = Point::new(220.0, 190.0);
pointer(&mut s, PointerKind::Drag, next, cmd());
assert_mirrored(anchor(&s, id), next, AnchorKind::Smooth);
pointer(&mut s, PointerKind::Up, next, cmd());
}
#[test]
fn direct_handle_modifiers_changed_during_a_space_translation_apply_at_once() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
press_handle(&mut s, Point::new(180.0, 100.0));
pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd());
let moved = Point::new(200.0, 190.0);
pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() });
handles(anchor(&s, id), Point::new(40.0, 70.0), moved, AnchorKind::Smooth);
// Releasing Cmd while Space is held gives the opposite handle its own length again.
pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..Mods::default() });
let a = anchor(&s, id);
near(a.p, Point::new(120.0, 130.0));
handles(a, Point::new(80.0, 100.0), moved, AnchorKind::Smooth);
// Alt while Space is held leaves the opposite handle where the translation put it.
pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, alt: true, ..cmd() });
handles(anchor(&s, id), Point::new(70.0, 130.0), moved, AnchorKind::Corner);
pointer(&mut s, PointerKind::Up, moved, Mods { alt: true, ..cmd() });
}
#[derive(Debug, PartialEq)]
struct Snapshot {
document: Value,
selection: Value,
undo: usize,
redo: usize,
}
fn snapshot(s: &Session) -> Snapshot {
let st = s.doc().unwrap();
Snapshot { document: json!(st.doc), selection: json!(st.selection), undo: st.history.undo.len(), redo: st.history.redo.len() }
}
fn assert_content(s: &Session, expected: &Snapshot) {
let got = snapshot(s);
assert_eq!(got.document, expected.document);
assert_eq!(got.selection, expected.selection);
}
fn cmd() -> Mods {
Mods { cmd: true, ..Mods::default() }
}
fn reflected(a: Point, q: Point) -> Point {
a - (q - a)
}
fn constrained(a: Point, q: Point) -> Point {
a + vectorcraft_geom::constrain_angle_from(q - a, 45.0, 0.0)
}
fn assert_mirrored(a: Anchor, q: Point, kind: AnchorKind) {
handles(a, reflected(a.p, q), q, kind);
}
#[test]
fn direct_handle_stationary_cmd_release_repress_commit_and_next_gesture() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let before = snapshot(&s);
press_handle(&mut s, Point::new(180.0, 100.0));
let q = Point::new(180.0, 160.0);
for (mods, opposite) in [(cmd(), Point::new(20.0, 40.0)), (Mods::default(), Point::new(60.0, 70.0)), (cmd(), Point::new(20.0, 40.0))] {
pointer(&mut s, PointerKind::Drag, q, mods);
handles(anchor(&s, id), opposite, q, AnchorKind::Smooth);
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo, "previews are not separate edits");
}
pointer(&mut s, PointerKind::Up, q, cmd());
let committed = snapshot(&s);
assert_eq!(committed.undo, before.undo + 1);
assert_eq!(committed.selection, before.selection);
run(&mut s, "edit.undo", json!({}));
assert_content(&s, &before);
run(&mut s, "edit.redo", json!({}));
assert_content(&s, &committed);
// Cmd did not install a persistent coupling mode: a later ordinary Smooth drag keeps
// the opposite handle's committed length, rather than matching the newly dragged length.
press_handle(&mut s, q);
let next = Point::new(180.0, 200.0);
pointer(&mut s, PointerKind::Drag, next, Mods::default());
let a = anchor(&s, id);
near(a.h_out, next);
assert_eq!(a.kind, AnchorKind::Smooth);
assert!((a.h_in.distance(a.p) - 100.0).abs() < 1e-6);
assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 20.0);
assert!(((a.h_in - a.p).cross(a.h_out - a.p)).abs() < 1e-6);
pointer(&mut s, PointerKind::Up, next, Mods::default());
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 2);
}
#[test]
fn direct_handle_shift_constrains_before_mirroring_and_alt_takes_priority() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let p = anchor(&s, id).p;
press_handle(&mut s, Point::new(180.0, 100.0));
let raw = Point::new(180.0, 150.0);
let q = constrained(p, raw);
let shifted = Mods { shift: true, ..cmd() };
pointer(&mut s, PointerKind::Drag, raw, shifted);
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..shifted });
handles(anchor(&s, id), Point::new(50.0, 100.0), q, AnchorKind::Corner);
// Removing Alt rebuilds from the original Smooth anchor, not the Corner preview.
pointer(&mut s, PointerKind::Drag, raw, shifted);
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..cmd() });
handles(anchor(&s, id), Point::new(50.0, 100.0), raw, AnchorKind::Corner);
pointer(&mut s, PointerKind::Up, raw, Mods { alt: true, ..cmd() });
}
#[test]
fn direct_handle_corner_with_collapsed_partner_is_reversible_without_changing_kind() {
let mut s = session();
let id = curve(&mut s, Point::new(100.0, 100.0));
let before = snapshot(&s);
assert_eq!(anchor(&s, id).kind, AnchorKind::Corner);
press_handle(&mut s, Point::new(180.0, 100.0));
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
assert_mirrored(anchor(&s, id), q, AnchorKind::Corner);
pointer(&mut s, PointerKind::Drag, q, Mods::default());
handles(anchor(&s, id), Point::new(100.0, 100.0), q, AnchorKind::Corner);
pointer(&mut s, PointerKind::Drag, q, cmd());
assert_mirrored(anchor(&s, id), q, AnchorKind::Corner);
s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap();
assert_eq!(snapshot(&s), before);
}
#[test]
fn direct_handle_stationary_drag_still_mirrors_unequal_partner_but_equal_is_noop() {
for (incoming, changes) in [(Point::new(50.0, 100.0), true), (Point::new(20.0, 100.0), false)] {
let mut s = session();
let id = curve(&mut s, incoming);
let before = snapshot(&s);
let q = Point::new(180.0, 100.0);
press_handle(&mut s, q);
pointer(&mut s, PointerKind::Drag, q, cmd());
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
pointer(&mut s, PointerKind::Up, q, cmd());
if changes {
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_content(&s, &before);
} else {
assert_eq!(snapshot(&s), before, "an already reflected pair records no edit");
}
}
}
#[test]
fn direct_handle_escape_restores_document_selection_and_existing_redo() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
run(&mut s, "shape.rectangle", json!({"x": 500, "y": 400, "width": 25, "height": 30}));
let redo_document = snapshot(&s).document;
run(&mut s, "edit.undo", json!({}));
run(&mut s, "select.set", json!({"ids": [id.0]}));
let before = snapshot(&s);
assert_eq!(before.redo, 1, "a real existing Redo is the cancellation control");
press_handle(&mut s, Point::new(180.0, 100.0));
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap();
assert!(!s.in_interaction());
assert_eq!(snapshot(&s), before);
pointer(&mut s, PointerKind::Up, q, Mods::default());
assert_eq!(snapshot(&s), before, "a later release does not commit the canceled preview");
run(&mut s, "edit.redo", json!({}));
assert_eq!(snapshot(&s).document, redo_document, "the prior Redo still restores its actual content");
}
#[test]
fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let before = snapshot(&s);
let a = anchor(&s, id);
pointer(&mut s, PointerKind::Down, a.p, cmd());
assert_eq!(s.tool_id(), "selection", "Cmd before Down keeps the existing Selection loan");
pointer(&mut s, PointerKind::Up, a.p, cmd());
assert_eq!(s.tool_id(), "directSelection");
assert_eq!(anchor(&s, id), a);
assert_eq!(snapshot(&s).document, before.document);
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo);
}
#[test]
fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
s.select_tool("pen", view()).unwrap();
let before = node(&s, id);
let undo = s.doc().unwrap().history.undo.len();
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd());
assert_eq!(s.tool_id(), "directSelection", "Cmd lends the Pen the last selection tool");
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
// Cmd let go and pressed again during the drag mirrors, as it does in Direct Selection itself.
pointer(&mut s, PointerKind::Drag, q, Mods::default());
handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
pointer(&mut s, PointerKind::Drag, q, cmd());
handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth);
assert_other_geometry(&s, id, &before);
pointer(&mut s, PointerKind::Up, q, cmd());
assert_eq!(s.tool_id(), "pen");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn direct_handle_cmd_held_through_a_pen_lent_drag_leaves_the_opposite_length() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
s.select_tool("pen", view()).unwrap();
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd());
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
pointer(&mut s, PointerKind::Up, q, cmd());
assert_eq!(s.tool_id(), "pen");
handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth);
}
fn text_anchor(s: &Session, id: NodeId) -> Anchor {
let n = node(s, id);
let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") };
t.type_path().unwrap().subpaths[0].anchors[1]
}
fn text_properties(s: &Session, id: NodeId) -> Value {
let n = node(s, id);
let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") };
let vectorcraft_doc::TextKind::OnPath { start, end, .. } = &t.kind else { panic!("path text") };
json!({"runs": t.runs, "para": t.para, "paras": t.paras, "xf": t.xf, "start": start, "end": end,
"effect": t.path_effect, "align": t.path_align, "spacing": t.path_spacing, "appearance": n.appearance})
}
fn path_text(s: &mut Session) -> NodeId {
let path = curve(s, Point::new(50.0, 100.0));
let made = run(
s,
"text.createInPath",
json!({"path": path.0, "mode": "onPath", "text": "Along the original curve", "font": "Source Sans 3", "size": 12}),
);
let id = NodeId(made["id"].as_u64().unwrap());
run(s, "type.pathOptions", json!({"id": id.0, "start": 0.15, "end": 0.85}));
run(s, "object.transform", json!({"ids": [id.0], "matrix": [1.5, 0.4, 0.25, 0.9, 250, 80]}));
s.select_tool("directSelection", view()).unwrap();
id
}
#[test]
fn direct_handle_affine_path_text_mirrors_in_drawn_space_and_keeps_brackets() {
let mut s = session();
let id = path_text(&mut s);
let before = snapshot(&s);
let properties = text_properties(&s, id);
assert_eq!(properties["start"], json!(0.15));
assert_eq!(properties["end"], json!(0.85));
let a = text_anchor(&s, id);
assert_eq!(a.kind, AnchorKind::Smooth);
near(a.p, Point::new(425.0, 210.0));
near(a.h_out, Point::new(545.0, 242.0));
assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 40.0);
press_handle(&mut s, a.h_out);
let raw = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0);
pointer(&mut s, PointerKind::Drag, raw, cmd());
assert_mirrored(text_anchor(&s, id), raw, AnchorKind::Smooth);
assert_eq!(text_properties(&s, id), properties);
let shifted = Mods { shift: true, ..cmd() };
pointer(&mut s, PointerKind::Drag, raw, shifted);
assert_mirrored(text_anchor(&s, id), constrained(a.p, raw), AnchorKind::Smooth);
assert_eq!(text_properties(&s, id), properties);
pointer(&mut s, PointerKind::Up, raw, shifted);
let after = snapshot(&s);
assert_eq!(after.undo, before.undo + 1);
run(&mut s, "edit.undo", json!({}));
assert_content(&s, &before);
run(&mut s, "edit.redo", json!({}));
assert_content(&s, &after);
}
fn blend_state(s: &Session, id: NodeId) -> (Anchor, Value, Vec<u32>) {
let n = node(s, id);
let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") };
assert!(spec.spine.is_some(), "the fixture uses an already pinned spine");
let path = vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0;
(path.subpaths[0].anchors[1], json!(children), spec.key_anchors.clone())
}
fn blend(s: &mut Session) -> NodeId {
let a = run(s, "shape.rectangle", json!({"x": 15, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap();
let b = run(s, "shape.rectangle", json!({"x": 295, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap();
let made = run(s, "object.blend.make", json!({"ids": [a, b], "steps": 2}));
let id = NodeId(made["id"].as_u64().unwrap());
let added = run(s, "object.blend.spine.addAnchor", json!({"id": id.0, "x": 100, "y": 100}));
assert_eq!(added["anchor"], json!(1));
run(s, "object.blend.spine.convertAnchor", json!({"id": id.0, "anchor": 1, "to": "smooth", "x": 180, "y": 100}));
run(s, "object.blend.spine.moveAnchor", json!({"id": id.0, "anchor": 1, "handle": "in", "x": 50, "y": 100}));
run(s, "select.set", json!({"ids": [id.0]}));
s.select_tool("directSelection", view()).unwrap();
let (middle, _, keys) = blend_state(s, id);
near(middle.p, Point::new(100.0, 100.0));
handles(middle, Point::new(50.0, 100.0), Point::new(180.0, 100.0), AnchorKind::Smooth);
assert_eq!(keys, [0, 2]);
// An actual spine-point click makes its handles visible to Direct Selection.
pointer(s, PointerKind::Down, middle.p, Mods::default());
pointer(s, PointerKind::Up, middle.p, Mods::default());
assert!(!s.in_interaction());
id
}
#[test]
fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() {
let mut s = session();
let id = blend(&mut s);
let before = snapshot(&s);
let (a, keys, mapping) = blend_state(&s, id);
press_handle(&mut s, a.h_out);
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
assert_mirrored(blend_state(&s, id).0, q, AnchorKind::Smooth);
let raw = Point::new(180.0, 150.0);
let shifted = Mods { shift: true, ..cmd() };
pointer(&mut s, PointerKind::Drag, raw, shifted);
assert_mirrored(blend_state(&s, id).0, constrained(a.p, raw), AnchorKind::Smooth);
// The existing spine Shift-only path is deliberately unconstrained; Cmd's new rule
// must not leak into that old branch after the modifier is released.
pointer(&mut s, PointerKind::Drag, raw, Mods { shift: true, ..Mods::default() });
near(blend_state(&s, id).0.h_out, raw);
pointer(&mut s, PointerKind::Drag, raw, shifted);
let (after_anchor, after_keys, after_mapping) = blend_state(&s, id);
assert_mirrored(after_anchor, constrained(a.p, raw), AnchorKind::Smooth);
assert_eq!(after_keys, keys, "handle edits leave the actual key art unchanged");
assert_eq!(after_mapping, mapping);
pointer(&mut s, PointerKind::Up, raw, shifted);
let after = snapshot(&s);
assert_eq!(after.undo, before.undo + 1);
assert_eq!(after.selection, before.selection);
run(&mut s, "edit.undo", json!({}));
assert_content(&s, &before);
run(&mut s, "edit.redo", json!({}));
assert_content(&s, &after);
}
#[test]
fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let before = snapshot(&s);
let original = node(&s, id);
press_handle(&mut s, Point::new(50.0, 100.0));
let q = Point::new(40.0, 20.0);
pointer(&mut s, PointerKind::Drag, q, Mods::default());
handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth);
pointer(&mut s, PointerKind::Drag, q, cmd());
handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth);
pointer(&mut s, PointerKind::Drag, q, Mods::default());
handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth);
pointer(&mut s, PointerKind::Drag, q, cmd());
assert_other_geometry(&s, id, &original);
pointer(&mut s, PointerKind::Up, q, cmd());
handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth);
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1);
assert_eq!(snapshot(&s).selection, before.selection);
run(&mut s, "edit.undo", json!({}));
assert_content(&s, &before);
}
/// `command` with `params` is refused with an error containing `message`, and the document,
/// selection and undo history stay as they were.
fn refused(s: &mut Session, command: &str, params: Value, message: &str) {
let before = snapshot(s);
let err = s.execute(command, &params).unwrap_err().to_string();
assert!(err.contains(message), "{command} {params}: {err}");
assert_eq!(snapshot(s), before);
}
#[test]
fn path_set_handle_symmetric_mirrors_refuses_bad_values_and_records_no_step_when_in_place() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let at = |x: f64, y: f64| json!({"id": id.0, "anchor": 1, "which": "out", "x": x, "y": y});
for bad in [json!("yes"), json!(1)] {
let mut p = at(180.0, 160.0);
p["symmetric"] = bad;
refused(&mut s, "path.setHandle", p, "`symmetric` must be true or false");
}
let mut both = at(180.0, 160.0);
both["symmetric"] = json!(true);
both["independent"] = json!(true);
refused(&mut s, "path.setHandle", both, "`independent` and `symmetric` cannot both be true");
let undo = s.doc().unwrap().history.undo.len();
let mut mirror = at(180.0, 160.0);
mirror["symmetric"] = json!(true);
run(&mut s, "path.setHandle", mirror.clone());
handles(anchor(&s, id), Point::new(20.0, 40.0), Point::new(180.0, 160.0), AnchorKind::Smooth);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
let placed = snapshot(&s);
run(&mut s, "path.setHandle", mirror);
assert_eq!(snapshot(&s), placed, "both handles already in place record no undo step");
}
#[test]
fn symmetric_leaves_the_other_handle_retracted_at_an_open_end() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let first = |s: &Session| node(s, id).path_data().unwrap().subpaths[0].anchors[0];
let p = first(&s).p;
run(&mut s, "path.setHandle", json!({"id": id.0, "anchor": 0, "which": "out", "x": 60, "y": 180, "symmetric": true}));
handles(first(&s), p, Point::new(60.0, 180.0), AnchorKind::Corner);
let mut s = session();
let blend_id = blend(&mut s);
let end = |s: &Session| {
let n = node(s, blend_id);
let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") };
vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0.subpaths[0].anchors[0]
};
let start = end(&s);
run(&mut s, "object.blend.spine.moveAnchor", json!({"id": blend_id.0, "anchor": 0, "handle": "out", "x": 60, "y": 60, "symmetric": true}));
near(end(&s).h_out, Point::new(60.0, 60.0));
near(end(&s).h_in, start.h_in);
near(end(&s).h_in, start.p);
}
#[test]
fn spine_and_type_path_handles_refuse_bad_symmetric_values() {
let mut s = session();
let id = blend(&mut s);
let spine = |extra: Value| {
let mut p = json!({"id": id.0, "anchor": 1, "handle": "out", "x": 180, "y": 160});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
p
};
refused(&mut s, "object.blend.spine.moveAnchor", spine(json!({"symmetric": "yes"})), "`symmetric` must be true or false");
refused(
&mut s,
"object.blend.spine.moveAnchor",
spine(json!({"symmetric": true, "independent": true})),
"`independent` and `symmetric` cannot both be true",
);
refused(
&mut s,
"object.blend.spine.moveAnchor",
json!({"id": id.0, "anchor": 1, "x": 180, "y": 160, "symmetric": true}),
"`symmetric` places a handle",
);
let text = path_text(&mut s);
let a = text_anchor(&s, text);
let at = json!({"id": text.0, "anchor": 1, "which": "out", "x": a.h_out.x, "y": a.h_out.y + 20.0});
let mut bad = at.clone();
bad["symmetric"] = json!(0);
refused(&mut s, "text.setPathHandle", bad, "`symmetric` must be true or false");
let mut both = at;
both["symmetric"] = json!(true);
both["independent"] = json!(true);
refused(&mut s, "text.setPathHandle", both, "`independent` and `symmetric` cannot both be true");
}
#[test]
fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror_type_on_a_path() {
let mut s = session();
let id = path_text(&mut s);
let a = text_anchor(&s, id);
let length = a.h_in.distance(a.p);
s.select_tool("pen", view()).unwrap();
pointer(&mut s, PointerKind::Down, a.h_out, cmd());
assert_eq!(s.tool_id(), "directSelection");
let q = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
let held = text_anchor(&s, id);
near(held.h_out, q);
assert!((held.h_in.distance(held.p) - length).abs() < 1e-6, "the other handle keeps its length");
pointer(&mut s, PointerKind::Drag, q, Mods::default());
pointer(&mut s, PointerKind::Drag, q, cmd());
assert_mirrored(text_anchor(&s, id), q, AnchorKind::Smooth);
pointer(&mut s, PointerKind::Up, q, cmd());
assert_eq!(s.tool_id(), "pen");
}
+275
View File
@@ -570,6 +570,143 @@ pub fn arc(a: Point, b: Point, slope: f64, closed: bool, _base_along_x: bool) ->
PathData::single(SubPath::new(anchors, closed))
}
/// A circular arc from `start` to `end`: its circle's `center` and `radius`, and the turn from
/// `start` to `end` about the center in radians, positive the way the angle `atan2(y, x)` grows
/// (clockwise on the y-down page). The turn is never 0 and never a whole turn.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CircularArc {
pub start: Point,
pub end: Point,
pub center: Point,
pub radius: f64,
pub sweep: f64,
}
impl CircularArc {
/// The arc from `start` to `end` that passes through `through`. `None` when two of the points
/// are the same or the three lie on one line ([`circle_through`]).
pub fn through(start: Point, end: Point, through: Point) -> Option<Self> {
let (center, radius) = circle_through(start, end, through)?;
let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x);
let a = angle(start);
let to_end = (angle(end) - a).rem_euclid(TAU);
let to_through = (angle(through) - a).rem_euclid(TAU);
// The turn that goes past `through` on its way to `end`.
let sweep = if to_through < to_end { to_end } else { to_end - TAU };
Self::checked(start, end, center, radius, sweep)
}
/// The arc that leaves `start` heading along `direction` (its tangent there) and ends at
/// `end`. `None` when `start` and `end` are the same, `direction` is zero, or `end` lies on the
/// line through `start` along `direction` (no circle touches that line at `start` and passes
/// through `end`). The same test as [`circle_through`] decides that: twice the area of the
/// triangle `start`, `end` and `start + direction` scaled to the chord's length is at most
/// 10⁻¹⁰ of the chord's length squared.
pub fn leaving(start: Point, direction: Vec2, end: Point) -> Option<Self> {
let len = direction.hypot();
let chord = end - start;
let c2 = chord.hypot2();
if !(len.is_finite() && len > 0.0 && c2.is_finite() && c2 > 0.0) {
return None;
}
let t = direction / len;
// Twice the triangle's area with the tangent as long as the chord.
let cross = t.cross(chord);
if cross.is_nan() || (cross * c2.sqrt()).abs() <= 1e-10 * c2 {
return None;
}
// The center lies on the normal at `start` on the side `end` is: `start + n * s` with
// `|n * s - chord| = |s|`, so `s = |chord|² / (2 n·chord)`.
let n = Vec2::new(-t.y, t.x);
let s = c2 / (2.0 * n.dot(chord));
let center = start + n * s;
let radius = s.abs();
let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x);
let a = angle(start);
let to_end = (angle(end) - a).rem_euclid(TAU);
// Leaving along `t`: the turn grows when `t` points the way the angle grows at `start`.
let grows = Vec2::new(-(start.y - center.y), start.x - center.x).dot(t) > 0.0;
let sweep = if grows { to_end } else { to_end - TAU };
Self::checked(start, end, center, radius, sweep)
}
/// The arc that ends at `end` arriving along `direction` and starts at `start`: [`Self::leaving`]
/// from `end` back along `-direction`, turned round.
pub fn arriving(start: Point, end: Point, direction: Vec2) -> Option<Self> {
let back = Self::leaving(end, -direction, start)?;
Some(Self { start, end, center: back.center, radius: back.radius, sweep: -back.sweep })
}
fn checked(start: Point, end: Point, center: Point, radius: f64, sweep: f64) -> Option<Self> {
let ok = center.is_finite() && radius.is_finite() && radius > 0.0 && sweep.is_finite() && sweep != 0.0 && sweep.abs() < TAU;
ok.then_some(Self { start, end, center, radius, sweep })
}
/// The point at `t` (0 at `start`, 1 at `end`) along the arc.
pub fn at(&self, t: f64) -> Point {
let a = (self.start.y - self.center.y).atan2(self.start.x - self.center.x) + self.sweep * t;
Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin())
}
/// The open path of the arc: an anchor at `start`, at `end`, and between them as many smooth
/// anchors, evenly spaced, as keep each cubic piece to a quarter turn at most. The ends are the
/// given points exactly.
pub fn to_path(&self) -> PathData {
let quarter = std::f64::consts::FRAC_PI_2;
// A quarter turn and a hair more is still one piece.
let pieces = ((self.sweep.abs() / quarter) - 1e-9).ceil().clamp(1.0, 4.0) as u32;
let step = self.sweep / f64::from(pieces);
// The handle length of a cubic that follows a circle through the turn `step`, per unit
// of radius; negative when the arc runs the other way.
let k = 4.0 / 3.0 * (step / 4.0).tan();
let a0 = (self.start.y - self.center.y).atan2(self.start.x - self.center.x);
let mut anchors = Vec::with_capacity(pieces as usize + 1);
for i in 0..=pieces {
let a = a0 + step * f64::from(i);
let p = if i == 0 {
self.start
} else if i == pieces {
self.end
} else {
Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin())
};
// The handle along the tangent the way the arc runs.
let d = Vec2::new(-a.sin(), a.cos()) * (self.radius * k);
let h_in = if i == 0 { p } else { p - d };
let h_out = if i == pieces { p } else { p + d };
let kind = if i == 0 || i == pieces { AnchorKind::Corner } else { AnchorKind::Smooth };
anchors.push(Anchor { p, h_in, h_out, kind });
}
PathData::single(SubPath::new(anchors, false))
}
/// [`Self::to_path`] with a smooth anchor at `via`, a point on the arc such as the one
/// [`Self::through`] passes through, so the path passes through it exactly: the arc to `via`
/// and the arc on from it, each cut into quarter turns at most. A `via` at an end, or off the
/// stretch between the ends, gives [`Self::to_path`].
pub fn to_path_via(&self, via: Point) -> PathData {
let angle = |p: Point| (p.y - self.center.y).atan2(p.x - self.center.x);
let turn = (angle(via) - angle(self.start)).rem_euclid(TAU);
// The turn from `start` to `via` the way the arc runs.
let to_via = if self.sweep > 0.0 { turn } else { turn - TAU };
let share = to_via / self.sweep;
if !(share > 0.0 && share < 1.0) || via == self.start || via == self.end {
return self.to_path();
}
let first = Self { end: via, sweep: to_via, ..*self }.to_path();
let second = Self { start: via, sweep: self.sweep - to_via, ..*self }.to_path();
let (Some(a), Some(b)) = (first.subpaths.into_iter().next(), second.subpaths.into_iter().next()) else { return self.to_path() };
let mut anchors: Vec<Anchor> = a.anchors.iter().copied().collect();
let mut rest = b.anchors.iter().copied();
if let (Some(joint), Some(next)) = (anchors.last_mut(), rest.next()) {
joint.h_out = next.h_out;
joint.kind = AnchorKind::Smooth;
}
anchors.extend(rest);
PathData::single(SubPath::new(anchors, false))
}
}
/// Logarithmic spiral with decay per full wind (`segments` quarter turns).
pub fn spiral(center: Point, radius: f64, decay_percent: f64, segments: u32, clockwise: bool) -> PathData {
let decay = (decay_percent / 100.0).clamp(0.05, 0.9999);
@@ -846,6 +983,144 @@ mod tests {
assert!(c.distance(Point::new(4.0, 3.0) + far) < 1e-6 && (radius - 5.0).abs() < 1e-6, "{c:?} {radius}");
}
/// Every point of `path`'s cubics lies on the arc's circle (to 3·10⁻⁴ of the radius, the
/// quarter-turn cubic's error), and the path runs from the arc's start to its end.
fn assert_on_circle(arc: &CircularArc) {
use kurbo::ParamCurve;
let path = arc.to_path();
let sp = &path.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.anchors.first().map(|a| a.p), Some(arc.start));
assert_eq!(sp.anchors.last().map(|a| a.p), Some(arc.end));
for seg in path.to_bezpath().segments() {
for i in 0..=8 {
let p = seg.eval(f64::from(i) / 8.0);
assert!((p.distance(arc.center) - arc.radius).abs() <= 3e-4 * arc.radius, "{p:?} off the circle");
}
}
}
/// The arc through a third point: from (0, 0) to (8, 0) through (4, -2) (above the chord on the
/// page) bulges up; through (4, 2) it bulges down; each has the circle through the three points
/// and goes past the third point. Through (4, 10) it is the larger part of its circle.
#[test]
fn the_arc_through_a_point_passes_through_it() {
let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0));
for (c, major) in
[(Point::new(4.0, -2.0), false), (Point::new(4.0, 2.0), false), (Point::new(4.0, 10.0), true), (Point::new(-1.0, -3.0), true)]
{
let arc = CircularArc::through(a, b, c).unwrap();
let (center, radius) = circle_through(a, b, c).unwrap();
assert!(arc.center.distance(center) < 1e-12 && (arc.radius - radius).abs() < 1e-12);
assert_eq!(arc.sweep.abs() > PI, major, "{c:?}: {}", arc.sweep);
// The third point is on the arc: some point along it is the third point.
let nearest = (0..=10_000).map(|i| arc.at(f64::from(i) / 10_000.0).distance(c)).fold(f64::INFINITY, f64::min);
assert!(nearest < 0.01, "{c:?}: {nearest}");
assert!(arc.at(0.0).distance(a) < 1e-12 && arc.at(1.0).distance(b) < 1e-9);
assert_on_circle(&arc);
}
// A half circle: two pieces, its middle anchor at the third point.
let arc = CircularArc::through(a, b, Point::new(4.0, -4.0)).unwrap();
let path = arc.to_path();
assert_eq!(path.subpaths[0].anchors.len(), 3);
assert!(path.subpaths[0].anchors[1].p.distance(Point::new(4.0, -4.0)) < 1e-12);
assert_eq!(path.subpaths[0].anchors[1].kind, AnchorKind::Smooth);
// Almost a whole circle: four pieces.
let arc = CircularArc::through(a, Point::new(0.0, 0.01), Point::new(8.0, 0.0)).unwrap();
assert_eq!(arc.to_path().subpaths[0].anchors.len(), 5);
assert_on_circle(&arc);
}
/// With an anchor at the third point, the path passes through it exactly, whichever way the
/// arc runs, even where one cubic would miss it (a quarter turn of radius 1000 misses a point
/// 20° along by about 0.27). Each part keeps to a quarter turn, the anchor there is smooth, and
/// a point at an end leaves the path as `to_path` makes it.
#[test]
fn the_path_via_the_third_point_passes_through_it_exactly() {
let center = Point::new(0.0, 0.0);
let on = |deg: f64| Point::new(1000.0 * deg.to_radians().cos(), 1000.0 * deg.to_radians().sin());
for (a, b, c) in [(0.0, 90.0, 20.0), (90.0, 0.0, 20.0), (0.0, 300.0, 170.0), (300.0, 0.0, 10.0)] {
let arc = CircularArc::through(on(a), on(b), on(c)).unwrap();
assert!(arc.center.distance(center) < 1e-6);
let path = arc.to_path_via(on(c));
let sp = &path.subpaths[0];
let joint = sp.anchors.iter().find(|x| x.p == on(c)).expect("an anchor at the third point");
assert_eq!(joint.kind, AnchorKind::Smooth);
assert_eq!((sp.anchors.first().map(|x| x.p), sp.anchors.last().map(|x| x.p)), (Some(arc.start), Some(arc.end)));
// No piece turns more than a quarter turn.
let points: Vec<Point> = sp.anchors.iter().map(|x| x.p).collect();
for w in points.windows(2) {
let (u, v) = (w[0] - arc.center, w[1] - arc.center);
assert!(u.cross(v).atan2(u.dot(v)).abs() <= std::f64::consts::FRAC_PI_2 + 1e-9, "{a} {b} {c}");
}
use kurbo::ParamCurve;
for seg in path.to_bezpath().segments() {
for i in 0..=8 {
let p = seg.eval(f64::from(i) / 8.0);
assert!((p.distance(arc.center) - arc.radius).abs() <= 0.3, "{p:?} off the circle");
}
}
}
// A third point a hair from an end is still an anchor.
let near = Point::new(1000.0, 0.0000005);
let arc = CircularArc::through(on(0.0), on(90.0), near).unwrap();
assert!(arc.to_path_via(near).subpaths[0].anchors.iter().any(|x| x.p == near));
let arc = CircularArc::through(on(0.0), on(90.0), on(20.0)).unwrap();
assert_eq!(arc.to_path_via(on(0.0)), arc.to_path());
assert_eq!(arc.to_path_via(on(180.0)), arc.to_path());
}
/// The arc that leaves its start along a direction: from (0, 0) heading up the page (-y) to
/// (8, 0) is the upper half circle about (4, 0); heading down, the lower one. Its tangent at the
/// start is the direction, and arriving at the end mirrors it.
#[test]
fn the_arc_leaving_along_a_direction_has_that_tangent() {
let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0));
let up = CircularArc::leaving(a, Vec2::new(0.0, -3.0), b).unwrap();
assert!(up.center.distance(Point::new(4.0, 0.0)) < 1e-12 && (up.radius - 4.0).abs() < 1e-12);
assert!(up.at(0.5).distance(Point::new(4.0, -4.0)) < 1e-9, "{:?}", up.at(0.5));
let down = CircularArc::leaving(a, Vec2::new(0.0, 3.0), b).unwrap();
assert!(down.at(0.5).distance(Point::new(4.0, 4.0)) < 1e-9, "{:?}", down.at(0.5));
// Leaving at 45° up and right: a quarter circle, tangent along the direction.
for d in [Vec2::new(1.0, -1.0), Vec2::new(1.0, 1.0), Vec2::new(-1.0, -0.2), Vec2::new(-1.0, 3.0)] {
let arc = CircularArc::leaving(a, d, b).unwrap();
let first = &arc.to_path().subpaths[0].anchors[0];
let tangent = first.h_out - first.p;
assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}");
assert_on_circle(&arc);
// Arriving along a direction at the end: the tangent into the end is the direction.
let arc = CircularArc::arriving(a, b, d).unwrap();
let last = arc.to_path().subpaths[0].anchors.last().copied().unwrap();
let tangent = last.p - last.h_in;
assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}");
assert_eq!((arc.start, arc.end), (a, b));
assert_on_circle(&arc);
}
}
/// No arc for points that are the same, a third point on the chord's line, a zero or not
/// finite direction, or a direction along the chord's line.
#[test]
fn degenerate_points_give_no_arc() {
let (a, b) = (Point::new(1.0, 2.0), Point::new(5.0, 7.0));
assert_eq!(CircularArc::through(a, a, b), None);
assert_eq!(CircularArc::through(a, b, b), None);
assert_eq!(CircularArc::through(a, b, a.midpoint(b)), None);
assert_eq!(CircularArc::through(a, b, a + (b - a) * 3.0), None);
assert_eq!(CircularArc::through(a, b, Point::new(f64::INFINITY, 0.0)), None);
assert_eq!(CircularArc::leaving(a, Vec2::new(1.0, 0.0), a), None);
assert_eq!(CircularArc::leaving(a, Vec2::ZERO, b), None);
assert_eq!(CircularArc::leaving(a, Vec2::new(f64::NAN, 1.0), b), None);
assert_eq!(CircularArc::leaving(a, b - a, b), None);
assert_eq!(CircularArc::leaving(a, a - b, b), None);
assert_eq!(CircularArc::arriving(a, b, b - a), None);
// Off the line by 10⁻⁴ over a chord of 2000 still makes an arc.
let (p, q) = (Point::new(-1000.0, 0.0), Point::new(1000.0, 0.0));
assert!(CircularArc::leaving(p, Vec2::new(2000.0, 1e-4), q).is_some());
// Off the line by 10⁻¹² of the chord is in line: no arc, rather than a circle 10¹² chords wide.
assert_eq!(CircularArc::leaving(p, Vec2::new(1.0, 1e-12), q), None);
}
/// Two points that are the same, or three on one line, give no circle.
#[test]
fn coincident_or_collinear_points_give_no_circle() {
+13 -1
View File
@@ -687,6 +687,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state",
),
("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"),
(
"window.taskBar.actions",
"Bar Actions",
"",
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
),
(
"window.taskBar.resetActions",
"Reset Bar Actions",
"",
"{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again",
),
(
"window.dock",
"Panels",
@@ -1561,7 +1573,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, harmony, harmonyRule, vision}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}",
),
(
"ui.savePdfDialog",
+237 -34
View File
@@ -16,7 +16,11 @@
//! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between.
//! It is also carried on to the end of the last character's advance. Type on more than one line
//! is placed a line at a time: each line is aligned by its own advances and split as a single
//! line is.
//! line is. A character cell runs from the font's OS/2 usWinAscent above the baseline to its
//! usWinDescent below it, and top or bottom aligned text has the top or the bottom of its cells
//! at the reference point. Text drawn in the opaque background mode (the mode a playback starts
//! in) has one rectangle of the background color behind the character cells of each line, as
//! far as its advances reach.
//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around
//! the whole picture clips nothing and is left out.
//!
@@ -541,22 +545,38 @@ impl Mapper {
// one for every character: a NUL's advance goes to the character before it, or moves the
// start when the string begins with one.
let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite());
let (mut s, mut dx, mut lead) = (String::new(), Vec::new(), 0.0f64);
let (mut s, mut dx) = (String::new(), Vec::new());
// How far before and after its start each character's advances (its own and the NULs'
// after it) reach (text units): an advance may be negative. And the advance of the NULs
// that move the start, with how far they reach.
let mut reach = Vec::new();
let mut lead = Lead::default();
for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) {
if c != '\0' {
s.push(c);
dx.push(d);
} else if let Some(last) = dx.last_mut() {
reach.push((d.min(0.0), d.max(0.0)));
} else if let (Some(last), Some(r)) = (dx.last_mut(), reach.last_mut()) {
*last += d;
*r = (r.0.min(*last), r.1.max(*last));
} else {
lead += d;
lead.by += d;
lead.reach = (lead.reach.0.min(lead.by), lead.reach.1.max(lead.by));
}
}
if !advances {
dx.clear();
lead = 0.0;
reach.clear();
lead = Lead::default();
}
if s.trim().is_empty() || t.color[3] == 0 {
// The leading NULs, of the text or of a string of NULs alone.
let first = lead;
// Type that draws nothing still fills its character cells on an opaque background.
let background = t.background.filter(|c| c[3] > 0);
let shows = !s.trim().is_empty() && t.color[3] > 0;
// A string of NULs only fills the cells across its advances.
let nuls = s.is_empty() && first.reach.0 < first.reach.1 && background.is_some();
if (s.is_empty() && !nuls) || !(shows || background.is_some()) {
return;
}
// Text space → document without the move: its vertical scale gives the type size, and what
@@ -613,11 +633,26 @@ impl Mapper {
if !dx.is_empty() {
style.kerning = Some(0.0);
}
// Where the baseline is below the reference point.
// The character cell above and below the baseline (points): the face's OS/2 usWinAscent
// and usWinDescent at the type size (its own ascent and descent when it has no OS/2
// table), as tall as a positive height asks.
let cell = face
.as_ref()
.map(|face| {
let (a, d) = face.win_ascent_descent().unwrap_or_else(|| face.vertical_metrics());
(a / face.units_per_em() * size, d / face.units_per_em() * size)
})
.filter(|(a, d)| a.is_finite() && d.is_finite() && *a >= 0.0 && *d >= 0.0 && a + d > 0.0)
.unwrap_or_else(|| {
let c = if h > 0.0 { size / 0.85 } else { size };
(0.8 * c, 0.2 * c)
});
// Where the baseline is below the reference point: the top or the bottom of the cell is at
// the reference point.
let drop = match t.v_align {
VAlign::Baseline => 0.0,
VAlign::Bottom => -0.2 * size,
VAlign::Top => 0.8 * size,
VAlign::Bottom => -cell.1,
VAlign::Top => cell.0,
};
let origin = self.xf * Point::new(t.transform[4], t.transform[5]);
let base = Affine::translate(origin.to_vec2()) * shape;
@@ -633,19 +668,65 @@ impl Mapper {
};
let whole = point(&s);
let opacity = f32::from(t.color[3]) / 255.0;
let line = Line {
base,
drop,
align: &t.h_align,
decorated: f.underline || f.strike,
shows,
color: t.color,
opacity,
background,
cell,
point: &point,
};
// The backgrounds of every line and piece, and the type added after them so that none of
// them covers it.
let mut out = TextOut::default();
if dx.is_empty() {
let mut text = whole;
let laid = vectorcraft_text::layout(db, &text);
text.xf = base * Affine::translate((0.0, drop));
text.cached_bounds = Some(vectorcraft_text::layout(db, &text).bounds);
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
n.opacity = opacity;
self.push(chain, n);
return;
text.cached_bounds = Some(laid.bounds);
if background.is_some() {
// How far one line's glyphs reach each way, and the sum of their advances, its
// trailing blanks included.
let along = laid.glyphs.iter().fold((f64::INFINITY, f64::NEG_INFINITY, 0.0), |(from, to, width), g| {
let (a, b) = (g.origin.x, g.origin.x + g.advance);
(from.min(a.min(b)), to.max(a.max(b)), width + g.advance)
});
let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite() && along.2.is_finite();
// The cells of one line run as far as its glyphs' advances reach, or for blanks
// alone, which draw no type, where the alignment puts a line that long.
// Those of more than one line run across each line's glyphs. NULs alone span
// their advances, where the alignment puts them.
let cells = if nuls {
let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k;
cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell)
} else if one {
let (x0, x1) = if shows {
(along.0, along.1)
} else {
let x0 = aligned(0.0, along.2, &t.h_align);
(x0, x0 + along.2)
};
cell_rect(x0, x1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell)
} else {
cells(&laid, &s, cell, &t.h_align, shows && line.decorated)
};
out.backs.extend(self.background(&line, cells, text.xf));
}
if shows {
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
n.opacity = opacity;
out.texts.push(n);
}
return self.add_text(&chain, out);
}
// Text units grow by `k` along the baseline in the text object's own space.
let dx: Vec<f64> = dx.iter().map(|d| d * k).collect();
let reach: Vec<(f64, f64)> = reach.iter().map(|(lo, hi)| (lo * k, hi * k)).collect();
let chars: Vec<char> = s.chars().collect();
let line = Line { base, drop, align: &t.h_align, decorated: f.underline || f.strike, color: t.color, opacity, point: &point, chain: &chain };
// Type on more than one line is placed a line at a time, each line aligned by its own
// advances (layout leaves the tracking after a line's last character out of the width it
// aligns, and each line ends with its own) and its underline carried on to its own end.
@@ -655,25 +736,68 @@ impl Mapper {
// a search.
let starts: Vec<usize> = s.char_indices().map(|(at, _)| at).collect();
let count = |to: usize| starts.partition_point(|at| *at < to);
let first = laid.lines.first().map_or(0.0, |l| l.baseline);
let top = laid.lines.first().map_or(0.0, |l| l.baseline);
for (n, l) in laid.lines.iter().enumerate() {
let (from, to) = (count(l.start), count(l.end));
let (Some(cs), Some(dx)) = (chars.get(from..to), dx.get(from..to)) else { continue };
let (Some(cs), Some(dx), Some(reach)) = (chars.get(from..to), dx.get(from..to), reach.get(from..to)) else { continue };
// A leading NUL's advance comes before the first line only.
let lead = if n == 0 { lead * k } else { 0.0 };
let down = l.baseline - first;
self.line(&line, cs, dx, lead, if down.is_finite() { down } else { 0.0 });
let lead = if n == 0 { first.scaled(k) } else { Lead::default() };
let down = l.baseline - top;
self.line(&line, cs, Advances { dx, reach, lead }, if down.is_finite() { down } else { 0.0 }, &mut out);
}
} else {
self.line(&line, &chars, &dx, lead * k, 0.0);
self.line(&line, &chars, Advances { dx: &dx, reach: &reach, lead: first.scaled(k) }, 0.0, &mut out);
}
self.add_text(&chain, out);
}
/// Adds a text record's backgrounds and then its type, leaving out backgrounds when there is
/// no room for both.
fn add_text(&mut self, chain: &[Arc<Clip>], out: TextOut) {
let TextOut { mut backs, texts } = out;
let keep = MAX_NODES.saturating_sub(self.out.len()).saturating_sub(texts.len());
if backs.len() > keep {
backs.truncate(keep);
self.warn(TOO_MANY);
}
for n in backs.into_iter().chain(texts) {
self.push(chain.to_vec(), n);
}
}
/// One line of text with advances `dx` (points along the baseline) for its characters `chars`,
/// `down` below the first line's baseline: in pieces, each a text object of its own, a new
/// piece after each cluster that tracking can't space by its advance.
fn line(&mut self, line: &Line, chars: &[char], dx: &[f64], lead: f64, down: f64) {
if chars.is_empty() || (chars.iter().all(|c| c.is_whitespace()) && !line.decorated) {
/// Character cells `cells`, placed by `xf`, filled with the line's background when it has one.
fn background(&self, line: &Line, mut cells: BezPath, xf: Affine) -> Option<Node> {
let bg = line.background?;
if cells.elements().is_empty() {
return None;
}
cells.apply_affine(xf);
self.path_node(cells, Some(bg), None, false)
}
/// One line of text with advances `adv` (points along the baseline) for its characters
/// `chars`, `down` below the first line's baseline: in pieces, each a text object of its own,
/// a new piece after each cluster that tracking can't space by its advance.
fn line(&mut self, line: &Line, chars: &[char], adv: Advances, down: f64, out: &mut TextOut) {
let Advances { dx, reach, lead } = adv;
// The line's cells, one rectangle behind every piece, run as far each way as its
// advances reach (an advance may be negative), from where the leading NULs' advances
// start, which the alignment puts where it puts a line as long as its advances. A line
// of leading NULs alone fills the cells across their advances.
let start = aligned(lead.by, dx.iter().sum(), line.align);
if line.background.is_some() {
let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64);
for (d, r) in dx.iter().zip(reach) {
(lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1));
pos += d;
}
let xf = line.base * Affine::translate((0.0, line.drop + down));
out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf));
}
let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace());
// A piece's type draws when it shows: blanks only when underlined or struck through.
let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated);
if chars.is_empty() || !draws(chars) {
return;
}
let db = vectorcraft_text::FontDb::global();
@@ -684,13 +808,13 @@ impl Mapper {
// Along the baseline (the text object's own space), where the next piece starts from the
// reference point: the line as long as its advances (a leading NUL's included), where the
// alignment puts it.
let mut at = aligned(lead, dx.iter().sum(), line.align);
let mut at = start;
let last = pieces.len().saturating_sub(1);
for (i, (from, to)) in pieces.into_iter().enumerate() {
let piece: String = chars.get(from..to).unwrap_or_default().iter().collect();
let cs = chars.get(from..to).unwrap_or_default();
let piece: String = cs.iter().collect();
let dx = dx.get(from..to).unwrap_or_default();
// Blanks of their own draw nothing unless they are underlined or struck through.
if piece.trim().is_empty() && !line.decorated {
if !draws(cs) {
at += dx.iter().sum::<f64>();
continue;
}
@@ -715,12 +839,12 @@ impl Mapper {
let gap = if (split && i < last) || (i == last && line.decorated) { gaps(&laid, db, &text, x0 + span) } else { BezPath::new() };
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text.clone())));
n.opacity = line.opacity;
self.push(line.chain.to_vec(), n);
out.texts.push(n);
if !gap.elements().is_empty() {
let mut gap = gap;
gap.apply_affine(text.xf);
if let Some(n) = self.path_node(gap, Some(line.color), None, false) {
self.push(line.chain.to_vec(), n);
out.texts.push(n);
}
}
}
@@ -785,16 +909,95 @@ fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 {
/// What every piece of a text record's lines shares: the text space (`base`, with the baseline
/// `drop` below the reference point), the alignment, whether the type is underlined or struck
/// through, its color and opacity, a point type object of a string in its style, and its clips.
/// through, whether the type shows, its color and opacity, its background and the character cell
/// above and below the baseline (points), and a point type object of a string in its style.
struct Line<'a> {
base: Affine,
drop: f64,
align: &'a HAlign,
decorated: bool,
shows: bool,
color: [u8; 4],
opacity: f32,
background: Option<[u8; 4]>,
cell: (f64, f64),
point: &'a dyn Fn(&str) -> TextObject,
chain: &'a [Arc<Clip>],
}
/// What a text record draws: the backgrounds behind its character cells, and its type (with the
/// bars that carry an underline or strikethrough on), added after them.
#[derive(Default)]
struct TextOut {
backs: Vec<Node>,
texts: Vec<Node>,
}
/// One line's advances (points along the baseline): each character's own, how far before and
/// after its start the advances from it to the next character reach, and the leading NULs'.
struct Advances<'a> {
dx: &'a [f64],
reach: &'a [(f64, f64)],
lead: Lead,
}
/// The NULs that move a line's start: their advance, and how far before and after the line's
/// start they reach.
#[derive(Clone, Copy, Default)]
struct Lead {
by: f64,
reach: (f64, f64),
}
impl Lead {
/// The same NULs with their advances grown by `k`.
fn scaled(self, k: f64) -> Lead {
Lead { by: self.by * k, reach: (self.reach.0 * k, self.reach.1 * k) }
}
}
/// The character cell from `x0` to `x1` along a baseline at `y`, `cell.0` above and `cell.1`
/// below it (points); empty when it has no area.
fn cell_rect(x0: f64, x1: f64, y: f64, cell: (f64, f64)) -> BezPath {
let r = Rect::new(x0, y - cell.0, x1, y + cell.1).abs();
if r.width() > 0.0 && r.height() > 0.0 && r.is_finite() { shapes::rectangle(r).to_bezpath() } else { BezPath::new() }
}
/// The character cells of `laid` (the type `s` laid out on more than one line), `cell.0` above
/// and `cell.1` below each baseline (points), as one rectangle a line: across the line as layout
/// places it and across its glyphs' advances, its trailing blanks included (layout leaves them
/// out of the width it aligns). A line of blanks alone runs across its glyphs' advances when
/// the type draws its underline or strikethrough (`decorated`), and otherwise as wide as their
/// advances, where `align` puts a line that long.
fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign, decorated: bool) -> BezPath {
// Each line's baseline, the sum of its glyphs' advances, how far before and after the
// reference point they reach, and whether they are all blanks. Glyphs come line by line.
type Row = (usize, f64, f64, (f64, f64), bool);
let mut lines: Vec<Row> = Vec::new();
for g in &laid.glyphs {
let blank = s.get(g.byte..).and_then(|r| r.chars().next()).is_none_or(char::is_whitespace);
let (from, to) = (g.origin.x.min(g.origin.x + g.advance), g.origin.x.max(g.origin.x + g.advance));
match lines.last_mut() {
Some((line, _, width, reach, all)) if *line == g.line => {
*width += g.advance;
*reach = (reach.0.min(from), reach.1.max(to));
*all &= blank;
}
_ => lines.push((g.line, g.origin.y, g.advance, (from, to), blank)),
}
}
let mut bp = BezPath::new();
for (line, y, width, reach, blank) in lines {
let (x0, x1) = match laid.lines.get(line) {
Some(l) if !blank => (l.x0.min(reach.0), l.x1.max(reach.1)),
_ if decorated => reach,
_ => {
let x0 = aligned(0.0, width, align);
(x0, x0 + width)
}
};
bp.extend(cell_rect(x0, x1, y, cell));
}
bp
}
/// The most times [`advanced`] lays the type out again to correct its tracking.
+195 -9
View File
@@ -274,7 +274,9 @@ fn hand_built_emf_plays_like_gdi() {
let lines = &children[1];
assert_eq!(lines.appearance.items.len(), 1);
assert!(near(lines.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 5.0 * mm, 5.0 * mm), 0.01));
let NodeKind::Text(t) = &children[2].kind else { panic!("text") };
// The background mode starts opaque: the text's cells are filled white behind it.
assert_eq!(fill_rgb(&children[2]), Some([255, 255, 255]));
let NodeKind::Text(t) = &children[3].kind else { panic!("text") };
assert_eq!(t.plain_text(), "Hi");
let st = &t.runs[0].style;
assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Arial", "Bold"));
@@ -884,6 +886,38 @@ fn wmf_font_width_becomes_horizontal_scale() {
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn wmf_text_fills_its_cells_in_the_opaque_background_mode() {
// CREATEFONTINDIRECT and SELECTOBJECT: a 0.1 inch em; SETBKCOLOR green; SETBKMODE `mode`
// (none when 0); TEXTOUT "Hi" at (720, 360), top aligned.
let backgrounds = |mode: i16| {
let mut font = le16(&[-144, 0, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19)));
let mut text = le16(&[2]);
text.extend(b"Hi");
text.extend(le16(&[360, 720]));
let mut records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0201, 0x0000_ff00u32.to_le_bytes().to_vec())];
if mode != 0 {
records.push((0x0102, le16(&[mode, 0])));
}
records.push((0x0521, text));
paths(&import(&hand_wmf(1440, 1440, &records)).unwrap().document)
};
let mm = 72.0 / 25.4;
// A file that never sets the mode, and one that sets OPAQUE: one green rectangle whose top
// is at the reference point and whose left edge is at the start of the text.
for mode in [0, 2] {
let p = backgrounds(mode);
assert_eq!(p.len(), 1, "{mode}");
assert_eq!(fill_rgb(&p[0]), Some([0, 255, 0]), "{mode}");
let b = p[0].geometric_bounds().unwrap();
assert!((b.x0 - 12.7 * mm).abs() < 0.01 && (b.y0 - 6.35 * mm).abs() < 0.01 && b.x1 > b.x0 && b.y1 > b.y0, "{mode}: {b:?}");
}
// TRANSPARENT: no background.
assert!(backgrounds(1).is_empty());
}
#[test]
fn a_clip_whose_box_holds_the_picture_still_clips() {
// A diamond around the middle of the picture, whose box holds the whole frame but which cuts
@@ -1001,7 +1035,8 @@ fn clipped_text_is_clipped_to_its_rectangle() {
let mut font = le(&[2, -1000, 0, 0, 0, 400]);
font.extend([0, 1, 1, 0, 0, 0, 0, 0]);
font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes));
let mut records = vec![(82, font), (37, le(&[2])), (84, text)];
// SETBKMODE TRANSPARENT: no background behind the text.
let mut records = vec![(18, le(&[1])), (82, font), (37, le(&[2])), (84, text)];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let layer = back.document.layers[0].children().unwrap();
assert_eq!(layer.len(), 1);
@@ -1030,6 +1065,156 @@ fn clipped_text_is_clipped_to_its_rectangle() {
assert!(matches!(children[1].kind, NodeKind::Text(_)));
}
/// The layer of an EMF that sets the background color green, the background mode `mode` (none
/// when 0) and the text alignment `align`, then draws `s` at (`x`, 1500) in `font` with the
/// advances `dx`.
fn on_background(mode: i32, align: i32, x: i32, font: Vec<u8>, s: &str, dx: &[i32]) -> Vec<std::sync::Arc<Node>> {
let mut records = vec![(25, le(&[0x0000_ff00])), (22, le(&[align])), (82, font), (37, le(&[2])), (84, text_out(x, s, dx))];
if mode > 0 {
records.insert(0, (18, le(&[mode])));
}
import(&hand_emf(5000, 3000, &records)).unwrap().document.layers[0].children().unwrap().clone()
}
#[test]
fn opaque_backgrounds_fill_behind_the_character_cells() {
let mm = 72.0 / 25.4;
let aligned = on_background;
// TA_BASELINE: the baseline at (10, 15) mm.
let drawn = |mode: i32, font: Vec<u8>, s: &str, dx: &[i32]| aligned(mode, 24, 1000, font, s, dx);
let opaque = |font: Vec<u8>, s: &str, dx: &[i32]| drawn(2, font, s, dx);
// "Hi" with advances of 20 and 10 mm in a 10 mm em: the cells run across the advances, from
// the face's usWinAscent above the baseline to its usWinDescent below it, behind the type.
let layer = opaque(arial(), "Hi", &[2000, 1000]);
assert_eq!(layer.len(), 2);
assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0]));
let NodeKind::Text(t) = &layer[1].kind else { panic!("text") };
let face = vectorcraft_text::FontDb::global().style_face(&t.runs[0].style).unwrap();
let (a, d) = face.win_ascent_descent().unwrap();
let em = face.units_per_em();
let b = layer[0].geometric_bounds().unwrap();
assert!(near(b, Rect::new(10.0 * mm, (15.0 - 10.0 * a / em) * mm, 40.0 * mm, (15.0 + 10.0 * d / em) * mm), 0.01), "{b:?}");
// TA_TOP and TA_BOTTOM put the top and the bottom of the cell at the reference point: the
// baseline is usWinAscent below it, or usWinDescent above it.
for (align, top) in [(0, 15.0), (8, 15.0 - 10.0 * (a + d) / em)] {
let layer = aligned(2, align, 1000, arial(), "Hi", &[2000, 1000]);
let b = layer[0].geometric_bounds().unwrap();
assert!((b.y0 - top * mm).abs() < 0.01 && (b.height() - 10.0 * (a + d) / em * mm).abs() < 0.01, "{align}: {b:?}");
let NodeKind::Text(t) = &layer[1].kind else { panic!("text") };
let baseline = (t.xf * vectorcraft_geom::Point::ZERO).y;
assert!((baseline - (top + 10.0 * a / em) * mm).abs() < 0.01, "{align}: {baseline}");
}
// A leading NUL's advance is filled too: right aligned at 50 mm, "\0Hi" fills from 10 mm.
let b = aligned(2, 26, 5000, arial(), "\0Hi", &[1000, 2000, 1000])[0].geometric_bounds().unwrap();
assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 50.0 * mm).abs() < 0.01, "{b:?}");
// A positive height is the cell: 10 mm from top to bottom.
let mut font = le(&[2, 1000, 0, 0, 0, 400]);
font.extend([0; 8]);
font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes));
let b = opaque(font, "Hi", &[2000, 1000])[0].geometric_bounds().unwrap();
assert!((b.height() - 10.0 * mm).abs() < 0.01, "{b:?}");
// Without advances the cells run across the glyphs' own advances.
let layer = opaque(arial(), "Hi", &[]);
let NodeKind::Text(t) = &layer[1].kind else { panic!("text") };
let (xs, end) = glyph_xs(t);
let b = layer[0].geometric_bounds().unwrap();
assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}");
// Type split where an advance is further than tracking reaches: one background across the
// whole line's advances comes before both pieces of type.
let layer = opaque(arial(), "Hiy", &[12000, 500, 1000]);
let kinds: Vec<bool> = layer.iter().map(|n| matches!(n.kind, NodeKind::Text(_))).collect();
assert_eq!(kinds, [false, true, true]);
let b = layer[0].geometric_bounds().unwrap();
assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 145.0 * mm).abs() < 0.01, "{b:?}");
}
#[test]
fn opaque_backgrounds_reach_as_far_as_the_advances() {
let mm = 72.0 / 25.4;
let aligned = on_background;
// TA_BASELINE: the baseline at (10, 15) mm.
let drawn = |mode: i32, font: Vec<u8>, s: &str, dx: &[i32]| aligned(mode, 24, 1000, font, s, dx);
let opaque = |font: Vec<u8>, s: &str, dx: &[i32]| drawn(2, font, s, dx);
// Two lines: a rectangle behind each, not one block over the space between them.
let layer = opaque(arial(), "Hi\nHi", &[]);
let NodeKind::Path { path, .. } = &layer[0].kind else { panic!("a path") };
let rects = path.to_bezpath().elements().iter().filter(|e| matches!(e, vectorcraft_geom::PathEl::MoveTo(_))).count();
assert_eq!(rects, 2);
// Without advances, one line's cells run across its glyphs' advances, trailing spaces
// included: right aligned, they run from the "H" to the end of the space after the "i".
let layer = aligned(2, 26, 4000, arial(), "Hi ", &[]);
let NodeKind::Text(t) = &layer[1].kind else { panic!("text") };
let (xs, end) = glyph_xs(t);
let b = layer[0].geometric_bounds().unwrap();
assert!(xs.len() == 3, "{xs:?} {end}");
assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}");
// Layout aligns a line without its trailing spaces: right aligned at 40 mm, the space after
// the "i" runs on past it. On more than one line, the cells also run across the trailing
// spaces, as far as on one line.
assert!(end > 41.0 * mm, "{end}");
let b = aligned(2, 26, 4000, arial(), "Hi \nHi", &[])[0].geometric_bounds().unwrap();
assert!((b.x1 - end).abs() < 0.01, "{b:?} {end}");
// Leading NULs on a line of their own fill their cells across their advances, before the
// next line: from 10 to 30 mm.
let layer = opaque(arial(), "\0\nA", &[2000, 0, 1000]);
let first = layer[0].geometric_bounds().unwrap();
assert!((first.x0 - 10.0 * mm).abs() < 0.01 && (first.x1 - 30.0 * mm).abs() < 0.01, "{first:?}");
assert!(matches!(layer[1].kind, NodeKind::Path { .. }) && matches!(layer[2].kind, NodeKind::Text(_)), "{layer:?}");
// An underlined line of blanks between two others draws its bar across its glyphs, and its
// cells run across the same glyphs.
let layer = opaque(font_of("Arial", true), "A\n \nB", &[]);
let (NodeKind::Path { path, .. }, NodeKind::Text(t)) = (&layer[0].kind, &layer[1].kind) else { panic!("a path and type") };
let mut rects: Vec<(f64, f64, f64)> = Vec::new();
for el in path.to_bezpath().elements() {
let p = match el {
vectorcraft_geom::PathEl::MoveTo(p) => {
rects.push((p.x, p.x, p.y));
*p
}
vectorcraft_geom::PathEl::LineTo(p) => *p,
_ => continue,
};
if let Some(r) = rects.last_mut() {
*r = (r.0.min(p.x), r.1.max(p.x), r.2.min(p.y));
}
}
rects.sort_by(|a, b| a.2.total_cmp(&b.2));
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let spaces: Vec<(f64, f64)> =
laid.glyphs.iter().filter(|g| g.line == 1).map(|g| ((t.xf * g.origin).x, (t.xf * g.origin).x + g.advance)).collect();
let (from, to) = spaces.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (x0, x1)| (a.min(*x0), b.max(*x1)));
assert!(rects.len() == 3 && (rects[1].0 - from).abs() < 0.01 && (rects[1].1 - to).abs() < 0.01, "{rects:?} {spaces:?}");
// NULs whose advances go forward and back again still fill as far as they reach.
let layer = opaque(arial(), "\0\0", &[1000, -1000]);
assert_eq!(layer.len(), 1);
let b = layer[0].geometric_bounds().unwrap();
assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 20.0 * mm).abs() < 0.01, "{b:?}");
let b = opaque(arial(), "H\0i", &[3000, -2000, 1000])[0].geometric_bounds().unwrap();
assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 40.0 * mm).abs() < 0.01, "{b:?}");
// An advance that goes back: the cells reach as far as the advances go, here to 30 mm.
let b = opaque(arial(), "Hi", &[2000, -1000])[0].geometric_bounds().unwrap();
assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 30.0 * mm).abs() < 0.01, "{b:?}");
// NULs alone fill across their advances.
let layer = opaque(arial(), "\0", &[2000]);
assert_eq!(layer.len(), 1);
let b = layer[0].geometric_bounds().unwrap();
assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 30.0 * mm).abs() < 0.01, "{b:?}");
// Blanks on an opaque background still fill their cells, from the reference point on; on a
// transparent one nothing is left.
let layer = opaque(arial(), " \t", &[]);
assert_eq!(layer.len(), 1);
let b = layer[0].geometric_bounds().unwrap();
assert!((b.x0 - 10.0 * mm).abs() < 0.01 && b.x1 > 10.0 * mm, "{b:?}");
assert!(drawn(1, arial(), " \t", &[]).is_empty());
// NULs alone in an underlined font fill their cells and add no type.
let layer = opaque(font_of("Arial", true), "\0", &[2000]);
assert!(layer.len() == 1 && matches!(layer[0].kind, NodeKind::Path { .. }), "{layer:?}");
// A file that never sets the mode draws in the opaque mode a playback starts in.
let layer = drawn(0, arial(), "Hi", &[]);
assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0]));
assert!(drawn(1, arial(), "Hi", &[]).iter().all(|n| matches!(n.kind, NodeKind::Text(_))));
}
/// The first text object of `d`.
fn first_text(d: &Document) -> TextObject {
all(d)
@@ -1195,8 +1380,8 @@ fn multiline_text_with_advances_aligns_each_line() {
}
assert!(drops.iter().all(|d| (d - drops[0]).abs() < 0.01), "{drops:?}");
// Underlined and left aligned, each line's underline ends with its own advances: no bar runs on
// past either line.
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))];
// past either line (on a transparent background, SETBKMODE).
let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. })));
for (align, x, second) in [(6, 2500, [15.0, 30.0]), (2, 4000, [20.0, 35.0])] {
@@ -1254,8 +1439,9 @@ fn wmf_text_is_spaced_by_its_advances() {
fn split_type_keeps_its_underline_and_right_to_left_order() {
let mm = 72.0 / 25.4;
// Underlined "Hiy" with an advance further than tracking reaches after the "H": the bar runs on
// from the end of the "H"'s underline to where "iy" starts, at 130 mm.
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))];
// from the end of the "H"'s underline to where "iy" starts, at 130 mm. The background is
// transparent (SETBKMODE) throughout.
let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
assert_eq!(texts_at(&back.document), vec![("H".to_string(), vec![10.0]), ("iy".to_string(), vec![130.0, 135.0])]);
let bars: Vec<Rect> =
@@ -1265,7 +1451,7 @@ fn split_type_keeps_its_underline_and_right_to_left_order() {
assert!(b.x0 > 10.0 * mm && b.x0 < 130.0 * mm && (b.x1 - 130.0 * mm).abs() < 0.01 && b.height() < 2.0 * mm, "{b:?}");
// The "H" and the "i" before the split are tracked apart and draw a bar each: only the bar that
// ends the piece runs on, from the end of the "i" to 130 mm.
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))];
let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0]), ("y".to_string(), vec![140.0])]);
let gaps: Vec<Node> = all(&back.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect();
@@ -1276,12 +1462,12 @@ fn split_type_keeps_its_underline_and_right_to_left_order() {
let b = gaps[0].geometric_bounds().unwrap();
assert!(b.x0 > 20.0 * mm && (b.x1 - 140.0 * mm).abs() < 0.01, "{b:?}");
// Without an underline, nothing but the type.
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))];
let records = vec![(18, le(&[1])), (82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. })));
// A last advance further than tracking reaches, right aligned at 140 mm: the "H" and the "i"
// start at 10 and 20 mm, and the underline runs on from the "i" to 140 mm.
let records = vec![(22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))];
let records = vec![(18, le(&[1])), (22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0])]);
let bars: Vec<Rect> =
+8 -2
View File
@@ -372,6 +372,12 @@ impl FontFace {
/// `usWinDescent`, at the face's location in a variable font), in font units; `None` when the
/// font has no OS/2 table or the sum isn't positive.
pub fn win_cell_height(&self) -> Option<f64> {
self.win_ascent_descent().map(|(a, d)| a + d)
}
/// The face's character cell on Windows above and below the baseline (the OS/2 table's
/// `usWinAscent` and `usWinDescent`, at the face's location in a variable font), in font
/// units; `None` when the font has no OS/2 table or the sum isn't positive.
pub fn win_ascent_descent(&self) -> Option<(f64, f64)> {
use skrifa::raw::TableProvider;
let f = self.skrifa()?;
let o = f.os2().ok()?;
@@ -380,8 +386,8 @@ impl FontFace {
let varied = |tag: &[u8; 4]| {
f.mvar().ok().and_then(|m| m.metric_delta(skrifa::Tag::new(tag), self.location().coords()).ok()).map_or(0.0, |d| d.to_f64())
};
let h = f64::from(o.us_win_ascent()) + varied(b"hcla") + f64::from(o.us_win_descent()) + varied(b"hcld");
(h > 0.0 && h.is_finite()).then_some(h)
let (a, d) = (f64::from(o.us_win_ascent()) + varied(b"hcla"), f64::from(o.us_win_descent()) + varied(b"hcld"));
(a + d > 0.0 && (a + d).is_finite()).then_some((a, d))
}
/// The average width of the face's characters (the OS/2 table's `xAvgCharWidth`), in font
/// units; `None` when the font has no OS/2 table or gives no positive width.
+6 -1
View File
@@ -875,7 +875,8 @@ fn on_path_align_takes_a_variable_font_instances_em_box() {
}
/// A variable font's instance takes its Windows character cell from the `usWinAscent` and
/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold.
/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold, 120 above the baseline and
/// 80 below it.
#[test]
fn win_cell_height_takes_a_variable_font_instances_mvar() {
use crate::test_fonts::{PATH_ALIGN_VARIABLE_FAMILY, path_align_font};
@@ -885,6 +886,10 @@ fn win_cell_height_takes_a_variable_font_instances_mvar() {
let cell = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_cell_height()).unwrap();
let (regular, bold) = (cell("Regular"), cell("Bold"));
assert!((bold - regular - 200.0).abs() < 1e-6, "Regular {regular}, Bold {bold}");
let split = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_ascent_descent()).unwrap();
let ((ra, rd), (ba, bd)) = (split("Regular"), split("Bold"));
assert!((ba - ra - 120.0).abs() < 1e-6 && (bd - rd - 80.0).abs() < 1e-6, "Regular {ra}/{rd}, Bold {ba}/{bd}");
assert!((ra + rd - regular).abs() < 1e-6);
}
/// In vertical type, Align to Path moves the glyphs half an em, with their horizontal scale and not
+1
View File
@@ -49,6 +49,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[
&[
t("lineSegment", "Line Segment Tool", Some("\\"), "tool-line"),
t("arc", "Arc Tool", None, "tool-arc"),
t(crate::three_point_arc::ID, "Three-Point Arc Tool", None, "tool-three-point-arc"),
t("spiral", "Spiral Tool", None, "tool-spiral"),
t("rectangularGrid", "Rectangular Grid Tool", None, "tool-rect-grid"),
t("polarGrid", "Polar Grid Tool", None, "tool-polar-grid"),
+55 -9
View File
@@ -78,6 +78,8 @@ struct HandleDrag {
offset: Vec2,
space: bool,
independent: bool,
/// The opposite handle mirrors this one ([`DirectSelectionTool::mirrors`]).
symmetric: bool,
translated: bool,
}
@@ -261,9 +263,27 @@ pub struct DirectSelectionTool {
frame_click: Option<(NodeId, AnchorRef)>,
/// Where the pointer last hovered: the type on a path bracket under it draws thicker.
bracket_hover: Option<Point>,
/// The Cmd/Ctrl press that lent this tool for one gesture (`lentByCmd`) is still
/// held: it does not mirror a dragged handle. Once Cmd/Ctrl is let go, pressing it again does.
lent_cmd: bool,
}
impl DirectSelectionTool {
/// Whether a handle drag with `ev`'s modifiers mirrors the opposite handle: Cmd/Ctrl held
/// without Alt, unless it is still the press that lent this tool for one gesture while another
/// tool, such as the Pen, is chosen.
fn mirrors(&self, ev: &PointerEvent) -> bool {
ev.mods.cmd && !ev.mods.alt && !self.lent_cmd
}
/// Forget the lending Cmd/Ctrl once an event comes without it. The session takes Cmd/Ctrl off
/// the press it lends the tool for, while the drags after it still carry it.
fn track_lent_cmd(&mut self, ev: &PointerEvent) {
if ev.kind != PointerKind::Down {
self.lent_cmd &= ev.mods.cmd;
}
}
pub fn new(group: bool) -> Self {
Self {
group,
@@ -291,6 +311,7 @@ impl DirectSelectionTool {
frame_revision: (0, 0),
frame_click: None,
bracket_hover: None,
lent_cmd: false,
}
}
@@ -441,6 +462,21 @@ fn spine_anchor(cx: &ToolContext, (id, ai): (NodeId, usize)) -> Option<vectorcra
spine_path(cx, id)?.subpaths.first()?.anchors.get(ai).copied()
}
/// Preview a drag of the clicked blend-spine direction handle.
/// `symmetric`: the opposite handle mirrors the dragged one ([`DirectSelectionTool::mirrors`]).
fn drag_spine_handle(cx: &ToolContext, ev: &PointerEvent, (id, anchor, out): (NodeId, usize, bool), p: Point, symmetric: bool) -> Vec<Action> {
let q = if symmetric && ev.mods.shift {
spine_anchor(cx, (id, anchor)).map_or(p, |a| a.p + vectorcraft_geom::constrain_angle_from(p - a.p, 45.0, cx.constrain_angle))
} else {
p
};
let mut params = json!({"id": id.0, "anchor": anchor, "handle": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt});
if symmetric {
params["symmetric"] = json!(true);
}
vec![Action::Preview("object.blend.spine.moveAnchor".into(), params)]
}
/// Blend `id`'s spine, built once for callers that look up several of its points.
fn spine_path(cx: &ToolContext, id: NodeId) -> Option<PathData> {
match &cx.doc.node(id)?.kind {
@@ -789,10 +825,15 @@ impl Tool for DirectSelectionTool {
}
/// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group
/// Selection, which selects whole objects, does not.
/// The session sets `lentByCmd` on the tool Cmd/Ctrl lends for one gesture
/// ([`DirectSelectionTool::mirrors`]).
fn set_option(&mut self, key: &str, value: &Value) {
if key == "meshPoints" && !self.group {
self.mesh.set_options(value);
}
if key == "lentByCmd" {
self.lent_cmd = value.as_bool().unwrap_or(false);
}
}
/// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh
/// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved
@@ -851,6 +892,7 @@ impl Tool for DirectSelectionTool {
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
self.bracket_hover = (ev.kind == PointerKind::Move).then_some(ev.pos);
self.track_lent_cmd(ev);
if let Some(out) = self.guide.pointer(cx, ev) {
return out;
}
@@ -908,6 +950,7 @@ impl Tool for DirectSelectionTool {
offset: Vec2::ZERO,
space: false,
independent: false,
symmetric: false,
translated: false,
})
}
@@ -1012,10 +1055,11 @@ impl Tool for DirectSelectionTool {
self.snapped = snapped(q.to_vec2(), p.to_vec2(), ev.mods.shift, &guides);
self.guides = guides;
let cmd = if cx.doc.node(id).is_some_and(is_path_type) { "text.setPathHandle" } else { "path.setHandle" };
vec![Action::Preview(
cmd.into(),
json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}),
)]
let mut params = json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt});
if self.mirrors(ev) {
params["symmetric"] = json!(true);
}
vec![Action::Preview(cmd.into(), params)]
}
(PointerKind::Drag, State::SpinePoint { id, anchor, from, start, began }) => {
let mut out = vec![];
@@ -1053,10 +1097,7 @@ impl Tool for DirectSelectionTool {
));
out
}
(PointerKind::Drag, State::SpineHandle { id, anchor, out }) => vec![Action::Preview(
"object.blend.spine.moveAnchor".into(),
json!({"id": id.0, "anchor": anchor, "handle": if out {"out"} else {"in"}, "x": p.x, "y": p.y, "independent": ev.mods.alt}),
)],
(PointerKind::Drag, State::SpineHandle { id, anchor, out }) => drag_spine_handle(cx, ev, (id, anchor, out), p, self.mirrors(ev)),
(PointerKind::Drag, State::Mesh) => self.mesh.drag_to(p).unwrap_or_default(),
(PointerKind::Up, State::Mesh) => {
self.state = State::Idle;
@@ -1568,15 +1609,20 @@ impl DirectSelectionTool {
self.snapped = snapped(q.to_vec2(), input.to_vec2(), ev.mods.shift, &guides);
self.guides = guides;
drag.handle = q;
drag.independent = ev.mods.alt;
}
}
// Alt and Cmd/Ctrl take effect on every event, while Space is held too.
drag.independent = ev.mods.alt;
drag.symmetric = self.mirrors(ev);
drag.last = p;
drag.space = ev.mods.space;
let mut params = json!({
"id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" },
"x": drag.handle.x, "y": drag.handle.y, "independent": drag.independent,
});
if drag.symmetric {
params["symmetric"] = json!(true);
}
if drag.translated {
params["at"] = json!([drag.at.x, drag.at.y]);
}
+2
View File
@@ -48,6 +48,7 @@ pub mod sidewidget;
pub mod slice;
pub mod symbolism;
pub mod text;
pub mod three_point_arc;
pub mod touchtype;
pub mod trace_split;
pub mod typewidget;
@@ -392,6 +393,7 @@ pub fn create(id: &str) -> Box<dyn Tool> {
quickpen::ID => Box::new(quickpen::QuickPenTool::default()),
// Not in the toolbar: `file.place.queue` loads it.
"place" => Box::new(place::PlaceTool::default()),
three_point_arc::ID => Box::new(three_point_arc::ThreePointArcTool::default()),
other => symbolism::create(other)
.or_else(|| builder::create(other))
.or_else(|| draw2::create(other))
+1
View File
@@ -48,6 +48,7 @@ const ROWS: &[Row] = &[
(&["mirrorCut"], None, &["axis", "keep"]),
(&["puppetWarp"], None, &["showMesh", "expand"]),
(&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]),
(&[crate::three_point_arc::ID], None, &["direction"]),
(&["spiral"], None, &["decay", "segments", "clockwise"]),
// The grids' Tool Options: the dividers and switches the drag uses, the Default Size and
// Reference Point a click's dialog opens with.
+337
View File
@@ -0,0 +1,337 @@
//! The Three-Point Arc tool draws an open circular arc between two ends it is given
//! (`shape.threePointArc`).
//!
//! The ends come first: a drag from one to the other, or a click on each. Shift keeps the second
//! end at 45° steps from the first (from General › Constrain Angle). A third point then shapes the
//! arc, placed by a click or by a press dragged to it: the arc passes through it, or, with the
//! `direction` option on, the arc leaves the first end heading toward it (Alt: the arc arrives at
//! the second end along the line from that end to the point, and Shift keeps the line at 45°
//! steps). `direction` is set in the tool's Tool Options and kept with the preferences; `]` (with
//! or without Shift) switches it while the ends are placed. Every point snaps to Smart Guides.
//! Until the third point is placed, the tool shows the arc as a dashed outline with its ends, its
//! center as a small cross, the direction line in direction mode and, with Measurement Labels on,
//! the radius by the pointer. Where no arc fits (the third point lies on the line through the
//! ends) or the arc would reach past the canvas, the tool shows "Arc too large" by the pointer
//! (nothing while the pointer is on an end) and a click there draws nothing. The arc is one undo
//! step. Escape, a press dropped part way, and an edit, Undo or Redo made outside the tool drop
//! the ends; a second click on the first end (a double-click) places nothing.
use serde_json::{Value, json};
use vectorcraft_doc::MAX_COORD;
use vectorcraft_geom::shapes::CircularArc;
use vectorcraft_geom::{PathData, Point, Vec2};
use crate::guides::{DrawSnap, Leave};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
pub const ID: &str = "threePointArc";
/// How far (screen points) the pointer travels from a press before the press counts as a drag.
const DRAG_PX: f64 = 2.0;
/// Half the length (screen points) of each arm of the cross at the arc's center.
const CROSS_PX: f64 = 4.0;
/// How near (screen points) the first end a second click counts as a click on it.
const REACH_PX: f64 = 3.0;
/// The label the tool shows by the pointer where no arc fits.
pub const TOO_LARGE: &str = "Arc too large";
/// The press in progress.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Press {
/// The first end, placed at `at` by a press at `from` (before snapping): a release after a
/// drag places the second end there. The drag is measured from `from`.
Start { at: Point, from: Point, dragged: bool },
/// The second end, pressed after a click placed the first: the release places it.
End,
/// The third point, pressed once both ends are placed: the release draws the arc.
Third,
}
#[derive(Default)]
pub struct ThreePointArcTool {
snap: DrawSnap,
/// The third point gives the arc's direction at an end instead of a point it passes through.
direction: bool,
start: Option<Point>,
end: Option<Point>,
press: Option<Press>,
/// Where the pointer is, snapped: the point the next press or release places.
pointer: Option<Point>,
/// Alt was held at the last pointer event: in direction mode, the direction is at the second end.
at_end: bool,
/// Where the pointer was at its last event, pressed or hovering, before snapping, and the keys
/// held then.
raw: Option<(Point, Mods)>,
}
/// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through
/// `third`, or with `direction`, heading toward `third` from `start` (or, with `at_end`, arriving
/// at `end` along the line from `end` to `third`). None where no arc fits or the arc would reach
/// past the canvas. With it, the path the command draws.
pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> Option<(CircularArc, PathData)> {
let (arc, path) = match (direction, at_end) {
(false, _) => CircularArc::through(start, end, third).map(|arc| (arc, arc.to_path_via(third))),
(true, false) => CircularArc::leaving(start, third - start, end).map(|arc| (arc, arc.to_path())),
(true, true) => CircularArc::arriving(start, end, end - third).map(|arc| (arc, arc.to_path())),
}?;
// The curve is measured, not its handles, which can reach past the canvas while the curve stays
// inside, as the document's own range check measures a path.
let inside = |x: f64, y: f64| x.abs() <= MAX_COORD && y.abs() <= MAX_COORD;
let on_canvas = path.bounds().is_some_and(|r| inside(r.x0, r.y0) && inside(r.x1, r.y1));
on_canvas.then_some((arc, path))
}
/// The command the tool runs for the arc from `start` to `end` shaped by `third`.
fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> (String, Value) {
let pair = |p: Point| json!([p.x, p.y]);
let params = if direction {
json!({ "start": pair(start), "end": pair(end), "toward": pair(third), "at": if at_end { "end" } else { "start" } })
} else {
json!({ "start": pair(start), "end": pair(end), "through": pair(third) })
};
("shape.threePointArc".into(), params)
}
impl ThreePointArcTool {
fn clear(&mut self) {
self.start = None;
self.end = None;
self.press = None;
self.pointer = None;
self.snap.clear();
}
/// How the point being placed keeps to the points before it: the second end to the first, and
/// in direction mode the third point to the end its direction line starts from.
fn leave(&self, cx: &ToolContext, mods: Mods) -> Option<Leave> {
match (self.start, self.end) {
(Some(a), None) => Some(Leave::segment(cx, a, mods.shift)),
(Some(a), Some(b)) if self.direction => Some(Leave::segment(cx, if mods.alt { b } else { a }, mods.shift)),
_ => None,
}
}
/// The pressed pointer moved to `ev`, or Shift or Alt changed: the point being placed follows
/// it. A change of keys alone does not make the press a drag.
fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) {
let moved = self.raw.is_none_or(|(p, _)| p != ev.pos);
self.raw = Some((ev.pos, ev.mods));
match &mut self.press {
Some(Press::Start { at, from, dragged }) => {
*dragged |= moved && ev.pos.distance(*from) >= cx.tol(DRAG_PX);
let leave = Leave::segment(cx, *at, ev.mods.shift);
self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave)));
}
Some(Press::End | Press::Third) => {
let leave = self.leave(cx, ev.mods);
self.pointer = Some(self.snap.drag(cx, ev.pos, leave.as_ref()));
}
None => {}
}
}
/// The arc as the tool shows it now, and its path: both ends placed and the pointer on a point
/// that fits.
fn arc(&self) -> Option<(CircularArc, PathData)> {
arc_of(self.start?, self.end?, self.pointer?, self.direction, self.at_end)
}
}
impl Tool for ThreePointArcTool {
fn id(&self) -> &'static str {
ID
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
if !ev.pos.is_finite() {
return vec![];
}
if self.end.is_some() {
self.at_end = ev.mods.alt;
}
match ev.kind {
PointerKind::Move => {
self.raw = Some((ev.pos, ev.mods));
let leave = self.leave(cx, ev.mods);
self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref()));
vec![]
}
PointerKind::Down => {
self.raw = Some((ev.pos, ev.mods));
let leave = self.leave(cx, ev.mods);
match (self.start, self.end) {
(None, _) => {
let at = self.snap.press(cx, ev.pos, &[], None);
self.start = Some(at);
self.press = Some(Press::Start { at, from: ev.pos, dragged: false });
self.pointer = Some(at);
}
(Some(a), None) => {
let at = self.snap.press(cx, ev.pos, &[], leave.as_ref());
// The second click of a double-click lands on the first end.
if at.distance(a) <= cx.tol(REACH_PX) {
self.press = None;
return vec![];
}
self.press = Some(Press::End);
self.pointer = Some(at);
}
(Some(_), Some(_)) => {
self.pointer = Some(self.snap.press(cx, ev.pos, &[], leave.as_ref()));
self.press = Some(Press::Third);
}
}
vec![]
}
PointerKind::Drag => {
self.follow(cx, ev);
vec![]
}
PointerKind::Up => {
// A release away from the last drag event places the point where it is let go, and
// a release with Shift or Alt changed places it as those keys keep it.
let same = self.raw.is_some_and(|(p, m)| p == ev.pos && (m.shift, m.alt) == (ev.mods.shift, ev.mods.alt));
if self.press.is_some() && !same {
self.follow(cx, ev);
}
match (self.press.take(), self.start, self.pointer) {
(Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b),
(Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b),
(Some(Press::Third), Some(a), Some(c)) => {
let Some(b) = self.end else { return vec![] };
// Where no arc fits, nothing is drawn and the ends stay for another try.
if self.arc().is_none() {
self.snap.clear();
return vec![];
}
let (name, params) = command(a, b, c, self.direction, self.at_end);
self.clear();
return vec![Action::Exec(name, params)];
}
_ => {}
}
// A placed end: the guides of the press go.
self.snap.clear();
vec![]
}
PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
}
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
match key {
ToolKey::Escape => self.clear(),
ToolKey::BracketRight if self.start.is_some() => {
self.direction = !self.direction;
// A press in progress: the point being placed keeps to the new mode.
// A hovering pointer: the third point it shows keeps to the new mode too.
match (self.press, self.raw) {
(Some(_), Some((p, mods))) => self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)),
(None, Some((p, mods))) if self.end.is_some() && self.pointer.is_some() => {
let leave = self.leave(cx, mods);
self.pointer = Some(self.snap.hover(cx, p, &[], leave.as_ref()));
}
_ => {}
}
}
_ => {}
}
vec![]
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
matches!(key, ToolKey::Escape | ToolKey::BracketRight) && self.start.is_some()
}
/// An end placed: Escape drops it.
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
self.start.is_some()
}
fn busy(&self) -> bool {
self.start.is_some()
}
/// A dropped press (a second finger, a canceled touch) drops the ends placed so far.
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.clear();
vec![]
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.clear();
vec![]
}
fn hover_ended(&mut self, _cx: &ToolContext) {
if self.press.is_none() {
self.pointer = None;
self.snap.clear();
}
}
/// An edit, Undo or Redo made outside the tool, or another document, drops the ends.
fn history_moved(&mut self) {
self.clear();
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut o = self.snap.guides().to_vec();
let color = crate::draw2::FEEDBACK;
match (self.start, self.end, self.pointer) {
// Placing the second end: the chord so far.
(Some(a), None, Some(b)) if b != a => o.push(Overlay::Line { a, b, color, dashed: true }),
(Some(a), Some(b), Some(p)) => {
if self.direction {
o.push(Overlay::Line { a: if self.at_end { b } else { a }, b: p, color, dashed: false });
}
match self.arc() {
Some((arc, path)) => {
o.push(Overlay::Path { path: path.to_bezpath(), color, width: 1.0, dashed: true });
let (c, arm) = (arc.center, cx.tol(CROSS_PX));
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false });
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false });
if cx.measurement_labels {
o.push(Overlay::Measure { p, text: format!("R: {}", cx.len(arc.radius)) });
}
}
// A pointer on an end gives no third point yet, so no label.
None if p.distance(a) <= cx.tol(REACH_PX) || p.distance(b) <= cx.tol(REACH_PX) => {}
None => o.push(Overlay::Label { p, text: TOO_LARGE.into(), color }),
}
}
_ => {}
}
for p in self.start.iter().chain(self.end.iter()) {
o.push(Overlay::Anchor { p: *p, color, filled: true, size: 6.0 });
}
o
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::Crosshair
}
fn options(&self) -> Value {
json!({ "direction": self.direction })
}
fn set_option(&mut self, key: &str, value: &Value) {
if key == "direction"
&& let Some(on) = value.as_bool()
{
self.direction = on;
}
}
fn check_option(&self, key: &str, v: &Value) -> Result<(), String> {
use crate::option_check as c;
match key {
"direction" => c::boolean(key, v),
_ => Err(c::unknown(key)),
}
}
}
#[cfg(test)]
mod tests;
+388
View File
@@ -0,0 +1,388 @@
use super::*;
use crate::testutil::*;
use vectorcraft_doc::Selection;
use vectorcraft_geom::Rect;
fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent {
PointerEvent::new(kind, x, y).with_mods(mods)
}
fn click_with(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64), mods: Mods) -> Vec<Action> {
let mut acts = t.pointer(cx, &ev(PointerKind::Down, p, mods));
acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, mods)));
acts
}
fn click(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64)) -> Vec<Action> {
click_with(t, cx, p, Mods::default())
}
fn hover(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64), mods: Mods) {
assert!(t.pointer(cx, &ev(PointerKind::Move, p, mods)).is_empty());
}
/// A press at `from`, dragged through `path` and let go at its last point.
fn drag(t: &mut ThreePointArcTool, cx: &ToolContext, from: (f64, f64), path: &[(f64, f64)], mods: Mods) -> Vec<Action> {
let mut acts = t.pointer(cx, &ev(PointerKind::Down, from, mods));
for p in path {
acts.extend(t.pointer(cx, &ev(PointerKind::Drag, *p, mods)));
}
let end = path.last().copied().unwrap_or(from);
acts.extend(t.pointer(cx, &ev(PointerKind::Up, end, mods)));
acts
}
fn through(start: (f64, f64), end: (f64, f64), via: (f64, f64)) -> Vec<Action> {
let pair = |(x, y): (f64, f64)| json!([x, y]);
vec![Action::Exec("shape.threePointArc".into(), json!({ "start": pair(start), "end": pair(end), "through": pair(via) }))]
}
fn toward(start: (f64, f64), end: (f64, f64), to: (f64, f64), at: &str) -> Vec<Action> {
let pair = |(x, y): (f64, f64)| json!([x, y]);
vec![Action::Exec("shape.threePointArc".into(), json!({ "start": pair(start), "end": pair(end), "toward": pair(to), "at": at }))]
}
/// The dashed arc the tool shows: its bounding box.
fn preview(o: &[Overlay]) -> Option<Rect> {
o.iter().find_map(|o| match o {
Overlay::Path { path, dashed: true, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)),
_ => None,
})
}
fn too_large(o: &[Overlay]) -> bool {
o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == TOO_LARGE))
}
/// A drag places the two ends; a click on a third point then draws the arc through it. Until
/// then, nothing is drawn.
#[test]
fn a_drag_and_a_click_draw_the_arc_through_the_third_point() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
assert!(drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 300.0), (380.0, 300.0)], Mods::default()).is_empty());
assert!(t.busy() && t.ends_on_escape(&cx));
assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0)));
assert!(!t.busy() && t.overlays(&cx).is_empty(), "the tool starts afresh");
}
/// Two clicks place the ends. Between the second click and the third, the tool shows the arc
/// through the pointer (a half circle here, bulging up the page), its center cross and its
/// radius; the third click draws it.
#[test]
fn three_clicks_draw_the_arc_and_the_tool_shows_it_on_the_way() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
assert!(click(&mut t, &cx, (300.0, 300.0)).is_empty());
hover(&mut t, &cx, (380.0, 300.0), Mods::default());
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Line { dashed: true, .. })), "the chord so far");
assert!(click(&mut t, &cx, (380.0, 300.0)).is_empty());
hover(&mut t, &cx, (340.0, 260.0), Mods::default());
let o = t.overlays(&cx);
let b = preview(&o).expect("the arc");
assert!((b.x0 - 300.0).abs() < 0.1 && (b.x1 - 380.0).abs() < 0.1 && (b.y0 - 260.0).abs() < 0.1 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}");
let radius = format!("R: {}", cx.len(40.0));
assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if *text == radius)), "{o:?}");
// The center cross at (340, 300).
assert!(o.iter().any(|o| matches!(o, Overlay::Line { a, b, dashed: false, .. } if a.midpoint(*b).distance(Point::new(340.0, 300.0)) < 1e-9)));
let quiet = ToolContext { measurement_labels: false, ..cx };
assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. })));
assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0)));
}
/// A third point on the line through the ends, an arc reaching past the canvas, or a third point
/// on an end gives no arc: a click draws nothing and keeps the ends, and a click on a point that
/// fits then draws the arc. The tool shows "Arc too large" by the pointer, except on an end.
#[test]
fn a_third_point_in_line_with_the_ends_draws_nothing() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
// Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt away.
for (bad, label) in [((420.0, 300.0), true), ((250.0, 300.0), true), ((340.0, 300.0), true), ((500.0, 300.001), true), ((380.0, 300.0), false)] {
hover(&mut t, &cx, bad, Mods::default());
let o = t.overlays(&cx);
assert!(too_large(&o) == label && preview(&o).is_none(), "{bad:?}: {o:?}");
assert!(click(&mut t, &cx, bad).is_empty(), "{bad:?}");
assert!(t.busy());
}
assert_eq!(click(&mut t, &cx, (340.0, 340.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 340.0)));
}
/// An arc near the canvas edge fits while its curve stays inside, even where a handle reaches past
/// the edge, and gives no arc once the curve reaches past it.
#[test]
fn an_arc_near_the_canvas_edge_is_measured_by_its_curve() {
// A 60° arc of radius 1000 whose rightmost point is `edge`: the handles at its ends reach about
// 45 pt further right.
let arc = |edge: f64| {
let (r, c) = (1000.0, edge - 1000.0);
let (dx, dy) = (r * 30f64.to_radians().cos(), r * 30f64.to_radians().sin());
let start = Point::new(c + dx, -dy);
let end = Point::new(c + dx, dy);
arc_of(start, end, start + Vec2::new(0.5, 3f64.sqrt() / 2.0) * 100.0, true, false)
};
let Some((_, path)) = arc(MAX_COORD - 1.0) else { panic!("an arc inside the canvas fits") };
assert!(path.control_bounds().is_some_and(|r| r.x1 > MAX_COORD), "a handle reaches past the edge");
assert!(path.bounds().is_some_and(|r| r.x1 <= MAX_COORD && (r.x1 - (MAX_COORD - 1.0)).abs() < 1e-6));
assert!(arc(MAX_COORD + 1.0).is_none(), "an arc reaching past the canvas does not fit");
}
/// In direction mode, Shift keeps the direction line at 45° steps from the end it starts at.
#[test]
fn shift_keeps_the_direction_at_45_degree_steps() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
t.set_option("direction", &json!(true));
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
let shift = Mods { shift: true, ..Mods::default() };
let acts = click_with(&mut t, &cx, (303.0, 250.0), shift);
let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") };
assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9), "{params}");
// With Alt, from the second end.
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
let both = Mods { shift: true, alt: true, ..Mods::default() };
let acts = click_with(&mut t, &cx, (383.0, 250.0), both);
let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") };
assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 380.0).abs() < 1e-9) && params["at"] == "end", "{params}");
}
/// With the `direction` option, the third point gives the direction the arc leaves its first
/// end in, and the tool shows the line from that end to the pointer. Alt moves the direction to
/// the second end. `]` switches the option while the ends are placed, and only then.
#[test]
fn in_direction_mode_the_third_point_sets_the_tangent_at_an_end() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
assert!(!t.claims_key(&cx, ToolKey::BracketRight), "no ends: ] is left to the app");
t.key(&cx, ToolKey::BracketRight, Mods::default());
assert_eq!(t.options(), json!({ "direction": false }));
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
assert!(t.claims_key(&cx, ToolKey::BracketRight));
t.key(&cx, ToolKey::BracketRight, Mods::default());
assert_eq!(t.options(), json!({ "direction": true }));
// Straight up the page from (300, 300): the upper half circle about (340, 300).
hover(&mut t, &cx, (300.0, 250.0), Mods::default());
let o = t.overlays(&cx);
let b = preview(&o).expect("the arc");
assert!((b.y0 - 260.0).abs() < 0.1 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}");
// The direction line: solid, from the end it starts at.
let line = |o: &[Overlay], from: Point| o.iter().any(|o| matches!(o, Overlay::Line { a, dashed: false, .. } if *a == from));
assert!(line(&o, Point::new(300.0, 300.0)), "{o:?}");
assert_eq!(click(&mut t, &cx, (300.0, 250.0)), toward((300.0, 300.0), (380.0, 300.0), (300.0, 250.0), "start"));
// Alt: the direction line starts at the second end.
t.set_option("direction", &json!(true));
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
let alt = Mods { alt: true, ..Mods::default() };
hover(&mut t, &cx, (380.0, 250.0), alt);
assert!(line(&t.overlays(&cx), Point::new(380.0, 300.0)));
assert!(preview(&t.overlays(&cx)).is_some());
assert_eq!(click_with(&mut t, &cx, (380.0, 250.0), alt), toward((300.0, 300.0), (380.0, 300.0), (380.0, 250.0), "end"));
// ] switches back to passing through the third point.
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
t.key(&cx, ToolKey::BracketRight, Mods::default());
assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0)));
}
/// The `direction` option takes a bool; anything else leaves it as it was.
#[test]
fn the_direction_option_takes_a_bool() {
let mut t = ThreePointArcTool::default();
t.set_option("direction", &json!(true));
for v in [json!("false"), json!(0), json!(null)] {
t.set_option("direction", &v);
assert_eq!(t.options(), json!({ "direction": true }), "{v}");
}
t.set_option("direction", &json!(false));
assert_eq!(t.options(), json!({ "direction": false }));
}
/// `]` pressed while the third point is held down places the point as the new mode keeps it: the
/// point Shift kept on the direction line goes back to where the pointer is, and the other way.
#[test]
fn bracket_during_a_press_places_the_third_point_in_the_new_mode() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
let shift = Mods { shift: true, ..Mods::default() };
t.set_option("direction", &json!(true));
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift));
t.key(&cx, ToolKey::BracketRight, Mods::default());
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), shift)), through((300.0, 300.0), (380.0, 300.0), (303.0, 250.0)));
// Through mode first, switched to direction mode during the press: Shift keeps the line upright.
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift));
t.key(&cx, ToolKey::BracketRight, Mods::default());
let acts = t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), shift));
let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") };
assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9) && params["at"] == "start", "{params}");
}
/// `]` pressed while the pointer hovers moves the third point the tool shows to where the new mode
/// keeps it, so the arc shown is the arc a click there draws.
#[test]
fn bracket_while_hovering_shows_the_third_point_in_the_new_mode() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
let shift = Mods { shift: true, ..Mods::default() };
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
hover(&mut t, &cx, (303.0, 250.0), shift);
t.key(&cx, ToolKey::BracketRight, Mods::default());
// The direction line from the first end: Shift keeps it upright.
let start = Point::new(300.0, 300.0);
let line = t.overlays(&cx).into_iter().find_map(|o| match o {
Overlay::Line { a, b, dashed: false, .. } if a == start => Some(b),
_ => None,
});
assert!(line.is_some_and(|b| (b.x - 300.0).abs() < 1e-9), "{line:?}");
let acts = click_with(&mut t, &cx, (303.0, 250.0), shift);
let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") };
assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9), "{params}");
// Back to through mode while hovering: the point goes back to the pointer.
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
hover(&mut t, &cx, (303.0, 250.0), shift);
assert!(t.pointer.is_some_and(|q| (q.x - 300.0).abs() < 1e-9), "{:?}", t.pointer);
t.key(&cx, ToolKey::BracketRight, Mods::default());
assert_eq!(t.pointer, Some(Point::new(303.0, 250.0)));
assert_eq!(click_with(&mut t, &cx, (303.0, 250.0), shift), through((300.0, 300.0), (380.0, 300.0), (303.0, 250.0)));
}
/// With Snap to Point, a first press that snaps to the rectangle's corner, 1.5 pt from the
/// pointer, and moves 1.9 pt before it is let go is a click: the drag is measured from the press,
/// not from the corner, so only the first end is placed.
#[test]
fn a_short_move_from_a_snapped_press_is_not_a_drag() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, snap_to_point: true, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
t.pointer(&cx, &ev(PointerKind::Down, (201.5, 200.0), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, (203.4, 200.0), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Up, (203.4, 200.0), Mods::default()));
assert_eq!((t.start, t.end), (Some(Point::new(200.0, 200.0)), None));
}
/// A release away from the last drag event places the point where the pointer is let go, for
/// the second end and for the third point.
#[test]
fn a_point_is_placed_where_the_press_is_let_go() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
let none = Mods::default();
t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), none));
t.pointer(&cx, &ev(PointerKind::Drag, (340.0, 300.0), none));
t.pointer(&cx, &ev(PointerKind::Up, (380.0, 300.0), none));
assert_eq!(t.end, Some(Point::new(380.0, 300.0)));
t.pointer(&cx, &ev(PointerKind::Down, (340.0, 250.0), none));
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (340.0, 260.0), none)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0)));
// A press that only moves when it is let go still counts as a drag for the ends.
t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), none));
t.pointer(&cx, &ev(PointerKind::Up, (380.0, 300.0), none));
assert_eq!(t.end, Some(Point::new(380.0, 300.0)));
}
/// A release with Shift or Alt changed since the press places the point as the keys at the
/// release keep it, even where the pointer did not move.
#[test]
fn a_release_places_the_point_with_the_keys_held_then() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
let (none, shift) = (Mods::default(), Mods { shift: true, ..Mods::default() });
// The second end: pressed without Shift, let go with it.
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (380.0, 306.0), none));
t.pointer(&cx, &ev(PointerKind::Up, (380.0, 306.0), shift));
assert_eq!(t.end.map(|e| e.y), Some(300.0), "{:?}", t.end);
// The third point in direction mode: pressed with Shift, let go with Shift and Alt, so the
// direction line keeps to 45° steps from the second end.
t.set_option("direction", &json!(true));
let both = Mods { alt: true, ..shift };
t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift));
let acts = t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), both));
let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") };
let at = |key: &str, i: usize| params[key][i].as_f64().unwrap_or(f64::NAN);
let (dx, dy) = (at("toward", 0) - at("end", 0), at("toward", 1) - at("end", 1));
assert!(params["at"] == "end" && (dx.abs() - dy.abs()).abs() < 1e-9, "{params}");
}
/// A first click that snaps to the rectangle's corner, 3 pt from the pointer, and is let go with
/// Shift changed places only the first end: a change of keys alone is not a drag.
#[test]
fn a_click_let_go_with_shift_changed_is_not_a_drag() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let g = Point::new(200.0, 200.0);
let off = (203.0, 201.0);
let mut t = ThreePointArcTool::default();
t.pointer(&cx, &ev(PointerKind::Down, off, Mods::default()));
t.pointer(&cx, &ev(PointerKind::Up, off, Mods { shift: true, ..Mods::default() }));
assert_eq!((t.start, t.end), (Some(g), None));
}
/// Shift keeps the second end at 45° steps from the first.
#[test]
fn shift_keeps_the_second_end_at_45_degree_steps() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
let shift = Mods { shift: true, ..Mods::default() };
drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 303.0), (380.0, 306.0)], shift);
assert_eq!(t.end.map(|e| e.y), Some(300.0), "{:?}", t.end);
}
/// Escape, an edit made outside the tool and a dropped press drop the ends; a second click on
/// the first end (a double-click) places nothing.
#[test]
fn escape_history_and_a_double_click_drop_or_keep_the_ends() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
click(&mut t, &cx, (300.0, 300.0));
assert!(t.claims_key(&cx, ToolKey::Escape));
t.key(&cx, ToolKey::Escape, Mods::default());
assert!(!t.busy() && !t.claims_key(&cx, ToolKey::Escape));
click(&mut t, &cx, (300.0, 300.0));
assert!(click(&mut t, &cx, (300.5, 300.0)).is_empty());
assert_eq!((t.start, t.end), (Some(Point::new(300.0, 300.0)), None), "the double-click's second click places nothing");
click(&mut t, &cx, (380.0, 300.0));
t.history_moved();
assert!(!t.busy());
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
t.drop_press(&cx);
assert!(!t.busy() && t.overlays(&cx).is_empty());
}
/// The catalog lists the tool in the Line Segment tool's group, after the Arc tool, with no
/// default shortcut, and `create` makes it.
#[test]
fn the_tool_is_in_the_line_segment_group_after_the_arc_tool() {
let group = crate::TOOL_GROUPS.iter().find(|g| g.iter().any(|t| t.id == ID)).expect("in a toolbar group");
let ids: Vec<_> = group.iter().map(|t| t.id).collect();
let arc = ids.iter().position(|id| *id == "arc").expect("the Arc tool's group");
assert_eq!(ids.first(), Some(&"lineSegment"));
assert_eq!(ids.get(arc + 1), Some(&ID));
let info = crate::tool_info(ID).expect("catalogued");
assert_eq!((info.label, info.shortcut), ("Three-Point Arc Tool", None));
assert_eq!(crate::create(ID).id(), ID);
}
+2 -1
View File
@@ -72,8 +72,9 @@ pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
pub use selection_marks::SelectionMarks;
use task_bar::task_bar;
pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, is_task_bar_action, read_hidden_task_bar_actions};
#[cfg(test)]
pub(crate) use task_bar::{chip_paints, images_with_other_art};
pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, task_bar_offered};
pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type};
#[cfg(test)]
use tool_overlays::{DIAL_RADIUS, HiddenMarks};
+147 -1
View File
@@ -19,6 +19,14 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool {
task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::<bool>(task_bar_id().with("fonts")).unwrap_or(false))
}
/// The actions and chips the Contextual Task Bar offered where it was last drawn, before Bar
/// Actions left any out, as More Options › Bar Actions lists them: each one's name, its id in
/// [`TASK_BAR_ACTIONS`] or [`TASK_BAR_CHIPS`] (none: Bar Actions cannot turn it off) and whether it
/// shows.
pub(crate) fn task_bar_offered(ctx: &egui::Context) -> Vec<(&'static str, Option<&'static str>, bool)> {
ctx.data(|d| d.get_temp(task_bar_id().with("offered")).unwrap_or_default())
}
/// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour,
/// a gradient's stops or a mesh's points, which Recolor Artwork can change.
pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool {
@@ -182,7 +190,10 @@ pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool {
/// On a blank canvas, a document with no artwork and a selection tool in use, it sits under the
/// active artboard and offers Draw (Pencil) and Place Image.
/// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the
/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]).
/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). More Options › Bar Actions
/// turns each action and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]);
/// the bar leaves out the ones that are off, and Reset Bar Actions shows them all again. With every
/// one of them off, the bar still shows its handle and More Options, where they turn back on.
pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
let t = Tokens::get(ui.ctx());
let on_artboards = app.session.tool_id() == "artboard";
@@ -351,6 +362,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
let paints = chip_paints(app, ui.ctx());
let colored = has_colors(&st.doc, &st.selection.objects);
let doc = st.uid;
// Every action and chip the bar offers here, with its name and its id in TASK_BAR_ACTIONS or
// TASK_BAR_CHIPS (none: Bar Actions cannot turn it off), for More Options › Bar Actions; the
// ones that are off there are left out of the bar.
let hidden = &app.ui.task_bar_hidden_actions;
let mut offered: Vec<(&'static str, Option<&'static str>)> =
items.iter().map(|(label, _, cmd, params)| (*label, action_id(cmd, params))).collect();
items.retain(|(_, _, cmd, params)| action_id(cmd, params).is_none_or(|a| !hidden.contains(a)));
let bounds = xf.rect.shrink(8.0);
// The canvas's width less the frame's margins and stroke.
let room = bounds.width() - BAR_FRAME;
@@ -371,6 +389,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
.into_iter()
.filter_map(|(shown, chip)| shown.then_some(chip))
.collect();
offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), Some(c.id(shape.is_some())))));
let chips: Vec<Chip> = chips.into_iter().filter(|c| !hidden.contains(c.id(shape.is_some()))).collect();
// Bar Actions reads this list through task_bar_offered while its menu is open.
let offered: Vec<(&'static str, Option<&'static str>, bool)> =
offered.into_iter().map(|(label, action)| (label, action, action.is_none_or(|a| !hidden.contains(a)))).collect();
ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("offered"), offered));
let any_hidden = !hidden.is_empty();
let widths: Vec<f32> = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect();
let fidelity = app.session.tool_options()["fidelity"].as_f64();
let font_w = fonts.then(|| {
@@ -498,6 +523,21 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
run = Some((cmd, json!({})));
}
}
// The actions and chips the bar offers for this selection or tool, each
// checked while it shows, which turns it on or off; then Reset Bar
// Actions, which shows every action again.
ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| {
ui.set_min_width(170.0);
for (label, action, shown) in task_bar_offered(ui.ctx()) {
let Some(action) = action else { continue };
if widgets::menu_item_name(ui, bar_action_name(label), true, shown) {
run = Some(("window.taskBar.actions", json!({ "action": action })));
}
}
});
if widgets::menu_item(ui, tl!("Reset Bar Actions"), any_hidden, false) {
run = Some(("window.taskBar.resetActions", json!({})));
}
ui.separator();
if widgets::menu_item(ui, tl!("Show Properties Panel"), true, false) {
run = Some(("window.panel", json!({"panel": "properties"})));
@@ -579,6 +619,112 @@ impl Chip {
Chip::Recolor | Chip::Lock => 30.0,
}
}
/// The chip's id in [`TASK_BAR_CHIPS`]; Lock is `shapeProperties` while it shows a basic
/// `shape`'s properties.
fn id(self, shape: bool) -> &'static str {
match self {
Chip::Fill => "fill",
Chip::Stroke => "stroke",
Chip::Recolor => "recolor",
Chip::Lock if shape => "shapeProperties",
Chip::Lock => "lock",
}
}
/// The chip's name in More Options › Bar Actions, translated.
fn label(self, shape: bool) -> &'static str {
match self {
Chip::Fill => tl!("Fill"),
Chip::Stroke => tl!("Stroke"),
Chip::Recolor => tl!("Recolor Artwork"),
Chip::Lock if shape => tl!("Shape Properties"),
Chip::Lock => tl!("Lock"),
}
}
}
/// The Contextual Task Bar's actions that More Options › Bar Actions turns on or off
/// (`window.taskBar.actions {action, visible?}`): each action's id, the command its button runs and
/// the `tool` that command names, if any. An action that is off stays out of the bar, and More
/// Options does not list it either; turning one off changes only the bar. Every action starts on.
pub(crate) const TASK_BAR_ACTIONS: [(&str, &str, Option<&str>); 37] = [
("imageTrace", TASK_BAR_IMAGE_TRACE, None),
("cropImage", "ui.cropImage", None),
("removeBackground", crate::addons::image::REMOVE_BACKGROUND, None),
("removeAnchorPoints", "path.removeAnchors", None),
("join", "path.join", None),
("cutPath", "path.cutAtAnchors", None),
("convertToCorner", TASK_BAR_TO_CORNER, None),
("convertToSmooth", TASK_BAR_TO_SMOOTH, None),
("group", "object.group", None),
("makeClippingMask", "object.clippingMask.make", None),
("unite", "object.pathfinder.unite", None),
("expand", "imageTrace.expand", None),
("editClippingPath", "object.clippingMask.editMask", None),
("releaseClippingMask", "object.clippingMask.release", None),
("ungroup", "object.ungroup", None),
("isolate", "object.isolate", None),
("editPath", "tool.select", Some("directSelection")),
("releaseCompoundPath", "object.compoundPath.release", None),
("createOutlines", "type.createOutlines", None),
("convertToPointType", "type.convertToPointType", None),
("convertToAreaType", "type.convertToAreaType", None),
("typeOnPathOptions", "type.pathOptions", None),
("centerOnTop", "type.pathCenter.top", None),
("centerOnBottom", "type.pathCenter.bottom", None),
("dynamicText", "type.dynamicText", None),
("offsetPath", "object.path.offsetPath", None),
("simplify", "object.path.simplify", None),
("smooth", "object.path.smooth", None),
("duplicate", "edit.duplicate", None),
("drawPencil", "tool.select", Some("pencil")),
("placeImage", "file.place", None),
("fidelity", TASK_BAR_FIDELITY, None),
("smoothToolOptions", "tool.options", Some("smooth")),
("resizeArtboard", TASK_BAR_ARTBOARD_OPTIONS, None),
("duplicateArtboards", TASK_BAR_DUPLICATE_ARTBOARDS, None),
("rearrangeArtboards", TASK_BAR_REARRANGE_ARTBOARDS, None),
("exportArtboards", "file.exportForScreens", None),
];
/// The ids of the Contextual Task Bar's chips that More Options › Bar Actions turns on or off,
/// as [`TASK_BAR_ACTIONS`] are.
pub(crate) const TASK_BAR_CHIPS: [&str; 5] = ["fill", "stroke", "recolor", "lock", "shapeProperties"];
/// Whether `id` names one of the Contextual Task Bar's actions or chips.
pub(crate) fn is_task_bar_action(id: &str) -> bool {
TASK_BAR_ACTIONS.iter().any(|a| a.0 == id) || TASK_BAR_CHIPS.contains(&id)
}
/// The id in [`TASK_BAR_ACTIONS`] of the bar's item that runs `cmd` with `params`.
fn action_id(cmd: &str, params: &serde_json::Value) -> Option<&'static str> {
let tool = params.get("tool").and_then(serde_json::Value::as_str);
TASK_BAR_ACTIONS.iter().find(|(_, c, t)| *c == cmd && *t == tool).map(|a| a.0)
}
/// The name More Options › Bar Actions lists for the bar's item `label`: without a field's colon
/// (a full-width one too), the space some languages put before it, or a final ellipsis (`…` or
/// `...`), in whichever order they come.
pub(crate) fn bar_action_name(label: &str) -> &str {
let mut name = label.trim_end();
loop {
let rest = name.trim_end_matches([':', ':', '…']);
let rest = rest.strip_suffix("...").unwrap_or(rest).trim_end();
if rest == name {
return name;
}
name = rest;
}
}
/// Reads the Contextual Task Bar's actions and chips that are off, as kept in the preferences. Ids
/// the bar does not have are dropped, and a value that is not a list of strings reads as none off,
/// so the bar shows every action.
pub(crate) fn read_hidden_task_bar_actions<'de, D: serde::Deserializer<'de>>(d: D) -> Result<std::collections::BTreeSet<String>, D::Error> {
let value = <serde_json::Value as serde::Deserialize>::deserialize(d)?;
let ids = value.as_array().into_iter().flatten().filter_map(serde_json::Value::as_str);
Ok(ids.filter(|id| is_task_bar_action(id)).map(str::to_string).collect())
}
/// What a click on one of the bar's [`Chip`]s does: make the Fill (`true`) or the Stroke active and
+2
View File
@@ -150,6 +150,7 @@ mod text_export;
pub mod text_import;
mod three_d_classic;
pub(crate) mod three_d_materials;
pub mod three_point_arc_options;
mod tiff_bmp_tga;
pub mod tile_edge_color;
mod tools;
@@ -471,6 +472,7 @@ registry! {
FreehandOptions: [freehand::KIND] => freehand::SPEC,
ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC,
ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC,
ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC,
FlareOptions: [flare_options::KIND] => flare_options::SPEC,
SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC,
DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC,
+100 -13
View File
@@ -259,11 +259,12 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format
_ => {}
}
}
let labels: Vec<&str> = export_as::formats().iter().map(|f| f.label).collect();
// A built-in format six from the end of the built-in ones: out of view when the list opens at
// its top, and far enough from the end that a plug-in format another test adds after the
// built-in ones does not move the rows shown around it.
// built-in ones does not move the rows shown around it. The window is short enough that the
// list centered on it stops short of its end.
let built_in: Vec<_> = fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect();
let labels: Vec<&str> = built_in.iter().map(|f| f.label).collect();
let chosen = built_in.len().checked_sub(6).and_then(|i| built_in.get(i)).copied().expect("Export As lists formats");
let (mut app, _) = app(1);
app.run("file.exportAs", json!({"format": chosen.id})).unwrap();
@@ -272,31 +273,38 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format
theme::apply(&ctx, Default::default());
// Every scroll area takes the bar at rest from the theme, whatever style the list sets itself.
assert_eq!(ctx.global_style().spacing.scroll, crate::widgets::list_scroll_style());
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 480.0)));
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 280.0)));
let mut time = 0.0;
let popup = std::cell::RefCell::new(vec![]);
// The texts and bars painted on the open list (without the dialog under it), and every text.
let mut run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
time += 0.25;
let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| show(app, ui.ctx()));
let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| {
show(app, ui.ctx());
popup.replace(crate::widgets::top_popup_shapes(ui.ctx()));
});
out.textures_delta.clear();
let (mut texts, mut bars) = (vec![], vec![]);
out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars));
(texts, bars)
let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]);
popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars));
out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![]));
(texts, bars, all)
};
let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0));
run(&mut app, vec![away.clone()]);
let (texts, _) = run(&mut app, vec![]);
let (_, _, texts) = run(&mut app, vec![]);
let field = texts.iter().find(|(s, ..)| s == chosen.label).map(|(_, r, _)| r.center()).expect("the Format field shows the chosen format");
let click_at = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
// Opens the list, moves the pointer away and returns the list's rect, the format names drawn in
// it with their clip rects, and the bars drawn.
type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec<egui::Event>) -> (Vec<(String, egui::Rect, egui::Rect)>, Vec<egui::Rect>) + 'r;
type Texts = Vec<(String, egui::Rect, egui::Rect)>;
type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec<egui::Event>) -> (Texts, Vec<egui::Rect>, Texts) + 'r;
let open = |run: &mut Run<'_>, app: &mut VectorcraftApp| {
run(app, vec![egui::Event::PointerMoved(field), click_at(field, true)]);
run(app, vec![click_at(field, false)]);
run(app, vec![away.clone()]);
let (mut texts, mut bars) = (vec![], vec![]);
for _ in 0..4 {
(texts, bars) = run(app, vec![]);
(texts, bars, _) = run(app, vec![]);
}
let list = ctx
.memory(|m| {
@@ -334,11 +342,13 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format
run(&mut app, vec![wheel]);
let mut scrolled = vec![];
for _ in 0..4 {
(scrolled, _) = run(&mut app, vec![]);
(scrolled, ..) = run(&mut app, vec![]);
}
let scrolled: Vec<_> = scrolled.into_iter().filter(|(s, r, _)| labels.contains(&s.as_str()) && list.contains_rect(*r)).collect();
run(&mut app, vec![egui::Event::PointerMoved(field), click_at(field, true)]);
run(&mut app, vec![click_at(field, false)]);
// Escape closes it: a list taller than the room beside its field covers the field.
let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
run(&mut app, vec![escape(true)]);
run(&mut app, vec![escape(false)]);
let (_, reopened, _) = open(&mut run, &mut app);
if rows.len() < labels.len() {
assert_ne!(tops(&scrolled), tops(&rows), "the wheel scrolled the list");
@@ -347,6 +357,83 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format
assert!(whole(&reopened, chosen.label), "the chosen format shows whole: {:?}", tops(&reopened));
}
/// #5941: the Format list stopped at the room on one side of its field, so a window with room for
/// every format still cut the list short. In windows of 1280×900 and 1000×856 the list shows every
/// built-in format whole, the grayed-out DWG row after them included, inside the window, without a
/// scroll bar. A plug-in format that another test adds or removes meanwhile is not counted.
#[test]
fn the_format_list_shows_every_format_when_the_window_has_room() {
fn walk(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec<(String, egui::Rect, egui::Rect)>, bars: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Text(t) => texts.push((t.galley.text().into(), t.visual_bounding_rect(), clip)),
egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect),
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, texts, bars)),
_ => {}
}
}
let labels: Vec<&str> =
fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).map(|f| f.label).chain(["DWG (use DXF)"]).collect();
for (width, height) in [(1280.0, 900.0), (1000.0, 856.0)] {
let case = format!("{width}×{height}");
let (mut app, _) = app(1);
app.run("file.exportAs", json!({"format": "png"})).unwrap();
let ctx = egui::Context::default();
theme::install_fonts(&ctx);
theme::apply(&ctx, Default::default());
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height));
let mut time = 0.0;
let popup = std::cell::RefCell::new(vec![]);
// The texts and bars painted on the open list (without the dialog under it), and every text.
let mut run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
time += 0.25;
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }, |ui| {
show(app, ui.ctx());
popup.replace(crate::widgets::top_popup_shapes(ui.ctx()));
});
out.textures_delta.clear();
let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]);
popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars));
out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![]));
(texts, bars, all)
};
let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0));
run(&mut app, vec![away.clone()]);
let (_, _, all) = run(&mut app, vec![]);
let field = all.iter().find(|(s, ..)| s == "PNG").map(|(_, r, _)| r.center()).expect("the Format field shows PNG");
let click = |pressed| egui::Event::PointerButton { pos: field, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(&mut app, vec![egui::Event::PointerMoved(field), click(true)]);
run(&mut app, vec![click(false)]);
run(&mut app, vec![away.clone()]);
let list_rect = || {
ctx.memory(|m| {
m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))
})
};
// A plug-in format that another test installs or removes changes the list's height, and the
// list is placed for its new height on the pass after. Read it once it keeps its rect.
let (mut texts, mut bars, mut list) = (vec![], vec![], None);
for _ in 0..12 {
(texts, bars, _) = run(&mut app, vec![]);
let now = list_rect();
if now.is_some() && now == list {
break;
}
list = now;
}
let list = list.expect("the Format list is open");
assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window");
let whole: Vec<&str> = labels
.iter()
.copied()
.filter(|name| {
texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom())
})
.collect();
assert_eq!(whole, labels, "{case}: every format shows whole in {list:?}");
assert!(bars.is_empty(), "{case}: a list that shows every format draws no scroll bar: {bars:?}");
}
}
#[test]
fn svg_continues_in_svg_options() {
let (mut app, written) = app(2);
@@ -0,0 +1,84 @@
//! Three-Point Arc Tool Options (double-click the Three-Point Arc tool, or `tool.options`):
//! Third Point Sets Direction, the tool's `direction` option. With it on, the third point gives the
//! direction the arc leaves an end in; with it off, the arc passes through the third point. OK
//! sets it with `tool.setOption {tool: "threePointArc", values: {direction}}`; it lasts across
//! tool switches and is saved with the preferences. `]` also switches it while an arc is drawn.
use serde_json::{Map, Value, json};
use vectorcraft_tools::three_point_arc::ID as TOOL;
use super::{DialogSpec, run_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
/// The dialog kind of Three-Point Arc Tool Options.
pub const KIND: &str = "threePointArcOptions";
pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 280.0, ..DialogSpec::FORM };
fn heading(_: &Dialog) -> String {
let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label);
crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))])
}
/// Open the tool's options with their current values.
pub fn open(app: &mut VectorcraftApp) -> Value {
let on = app.session.tool_options_of(TOOL).get("direction").and_then(Value::as_bool).unwrap_or(false);
let mut fields = Map::new();
fields.insert("direction".into(), json!(on));
app.ui.dialog = Some(Dialog { kind: KIND.into(), fields });
json!({ "dialog": KIND })
}
fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let on = d.bool("direction");
if widgets::check(ui, tl!("Third Point Sets Direction"), on, true) {
d.fields.insert("direction".into(), json!(!on));
}
false
}
/// OK: set the tool's `direction`.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": { "direction": d.bool("direction") } }))
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_engine::Session;
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app
}
/// The labels the open dialog paints.
fn painted(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
}
#[test]
fn double_clicking_the_tool_opens_its_options_and_ok_sets_the_direction() {
let mut app = app();
assert_eq!(app.session.tool_options_of(TOOL)["direction"], json!(false));
let r = app.run("tool.options", json!({"tool": TOOL})).unwrap();
assert_eq!(r["dialog"], json!(KIND));
let text = painted(&mut app);
for label in ["Three-Point Arc Tool Options", "Third Point Sets Direction", "OK", "Cancel"] {
assert!(text.contains(label), "{label} in {text}");
}
let d = app.ui.dialog.as_mut().unwrap();
assert!(!d.bool("direction"));
d.fields.insert("direction".into(), json!(true));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(app.session.tool_options_of(TOOL)["direction"], json!(true));
// It lasts while another tool is chosen, and the dialog opens on it again.
app.select_tool(TOOL);
app.select_tool("selection");
app.run("tool.options", json!({"tool": TOOL})).unwrap();
assert!(app.ui.dialog.as_ref().unwrap().bool("direction"));
}
}
+27
View File
@@ -224,6 +224,10 @@ font-technology Variable Променливи
Arc Дъга
Arc Lower… Дъга надолу…
Arc Tool Инструмент „Дъга“
Three-Point Arc Tool Инструмент „Дъга през три точки“
Three-Point Arc Дъга през три точки
Arc too large Дъгата е твърде голяма
Third Point Sets Direction Третата точка задава посоката
Arc Upper… Дъга нагоре…
Arch… Извиване…
Arc… Дъга…
@@ -628,6 +632,8 @@ font-technology Variable Променливи
Contextual Task Bar Контекстна лента със задачи
Pin Bar Position Закачане на позицията на лентата
Reset Bar Position Нулиране на позицията на лентата
Bar Actions Действия на лентата
Reset Bar Actions Нулиране на действията на лентата
Resize Преоразмеряване
Contrast Контраст
Control Контрол
@@ -1954,6 +1960,11 @@ font-technology Variable Променливи
Knife Нож
Knockout Group Група с изрязване
Lab Lab
OKLCH Sliders Плъзгачи OKLCH
HSL Sliders Плъзгачи HSL
Chroma Хрома
The largest chroma sRGB holds at this lightness and hue Най-голямата хрома, която sRGB побира при тази светлина и този оттенък
OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство
Lab Spot Colors: Спот цветове по Lab:
Lab Values Стойности по Lab
Landscape Пейзаж
@@ -4749,6 +4760,8 @@ axis Both И двете
@msg `aspect` must be a number (%) `aspect` трябва да бъде число (%)
@msg `at` must be [x, y] `at` трябва да бъде [x, y]
@msg `color` must be a colour `color` трябва да бъде цвят
@msg `sliders` must be none, oklch or hsl `sliders` трябва да бъде none, oklch или hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство
@msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog)
@msg `freeform.points` must be an array `freeform.points` трябва да бъде масив
@msg `freeform.lines` must be an array `freeform.lines` трябва да бъде масив
@@ -7886,6 +7899,20 @@ breakText Glyphs Глифи
Blossom Chain Цветна верига
Pennant Garland Гирлянд от знаменца
Lantern String Низ от фенери
Orbit Lines Орбитални линии
Petal Garland Гирлянд от венчелистчета
Lattice Braid Решетъчна плетка
Facet Sweep Фасетен щрих
Artistic Brushes Художествени четки
Paint Боя
Flat Sweep Плосък замах
Dry Drag Сухо влачене
Loaded Stroke Плътен мазок
Fan Sweep Ветрилообразен замах
@msg `at` must be "start" or "end" `at` трябва да е "start" или "end"
@msg give exactly one of `through` and `toward` посочете точно едно от `through` и `toward`
@msg no arc fits these points: two are the same or all three lie on one line няма дъга през тези точки: две съвпадат или и трите лежат на една права
@msg give `at` only with `toward` задайте `at` само заедно с `toward`
Engraving Гравюра
Fine Hatching Фино щриховане
Dense Hatching Гъсто щриховане
Can't render this file because it is too large.
+27
View File
@@ -797,6 +797,8 @@
Contextual Task Bar Kontekstna traka zadataka
Pin Bar Position Položaj prikvačene trake
Reset Bar Position Vrati položaj trake na početno
Bar Actions Radnje trake
Reset Bar Actions Vrati radnje trake na početno
Resize Promijeni veličinu
Tools Alati
Toolbars Trake s alatima
@@ -1506,6 +1508,10 @@ lighting Light Svjetlo
Add Anchor Point Tool Alat za dodavanje sidrene tačke
Anchor Point Tool Alat sidrena tačka
Arc Tool Alat luk
Three-Point Arc Tool Alat luk kroz tri tačke
Three-Point Arc Luk kroz tri tačke
Arc too large Luk je prevelik
Third Point Sets Direction Treća tačka određuje smjer
Area Graph Tool Alat za površinski grafikon
Area Type Tool Alat za tekst u području
Artboard Tool Alat radna ploča
@@ -4545,6 +4551,11 @@ axis Both Obje
Image Slika
Ink Tinta
Lab Lab
OKLCH Sliders OKLCH klizači
HSL Sliders HSL klizači
Chroma Hroma
The largest chroma sRGB holds at this lightness and hue Najveća hroma koju sRGB obuhvata pri ovoj svjetloći i nijansi
OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor
Medium Srednje
Name Naziv
None Ništa
@@ -5197,6 +5208,8 @@ imageTrace Outline Obris
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` mora biti grayscale, rgb, hsb, cmyk ili websafe
@msg `view` must be wheel or box `view` mora biti wheel ili box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue
@msg `sliders` must be none, oklch or hsl `sliders` mora biti none, oklch ili hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor
@msg `{k}` must be [x, y] `{k}` mora biti [x, y]
@msg `{name}` has no options `{name}` nema opcija
@msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv
@@ -7941,6 +7954,20 @@ shape Open Otvoren
Blossom Chain Cvjetni lanac
Pennant Garland Girlanda zastavica
Lantern String Niz lampiona
Orbit Lines Orbitalne linije
Petal Garland Vijenac od latica
Lattice Braid Rešetkasti preplet
Facet Sweep Fasetni potez
Artistic Brushes Umjetničke četke
Paint Boja
Flat Sweep Ravni potez
Dry Drag Suhi potez
Loaded Stroke Bogati potez
Fan Sweep Lepezasti potez
@msg `at` must be "start" or "end" `at` mora biti "start" ili "end"
@msg give exactly one of `through` and `toward` navedite tačno jedno od `through` i `toward`
@msg no arc fits these points: two are the same or all three lie on one line nijedan luk ne odgovara ovim tačkama: dvije su iste ili sve tri leže na jednoj pravoj
@msg give `at` only with `toward` navedite `at` samo uz `toward`
Engraving Gravura
Fine Hatching Fino šrafiranje
Dense Hatching Gusto šrafiranje
Can't render this file because it contains an unexpected character in line 2 and column 73.
+27
View File
@@ -345,6 +345,10 @@ antiAlias Sharp Nítid
Arc Lower… Arc inferior…
Arc Segment Tool Options Opcions de l’eina de segment d’arc
Arc Tool Eina d’arc
Three-Point Arc Tool Eina d’arc per tres punts
Three-Point Arc Arc per tres punts
Arc too large Arc massa gran
Third Point Sets Direction El tercer punt indica la direcció
Arc Upper… Arc superior…
Arch… Arqueja…
Arc… Arc…
@@ -2495,6 +2499,11 @@ digits Malayalam Malaiàlam
Knife Ganivet
Knockout Group Grup knockout
Lab Lab
OKLCH Sliders Controls lliscants OKLCH
HSL Sliders Controls lliscants HSL
Chroma Croma
The largest chroma sRGB holds at this lightness and hue El croma més gran que sRGB admet amb aquesta lluminositat i aquest to
OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball
Lab Spot Colors Colors directes Lab
Lab Spot Colors: Colors directes Lab:
Lab Values Valors Lab
@@ -3945,6 +3954,8 @@ digits Malayalam Malaiàlam
Reset all Revolve settings to their defaults. Restableix tots els paràmetres de revolució als valors predeterminats.
Reset Automation Restableix Automation
Reset Bar Position Restableix la posició de la barra
Bar Actions Accions de la barra
Reset Bar Actions Restableix les accions de la barra
Reset Bounding Box Restableix el quadre delimitador
Rotate Bounding Box Gira el quadre delimitador
Rotate Bounding Box… Gira el quadre delimitador…
@@ -6140,6 +6151,8 @@ digits Malayalam Malaiàlam
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe
@msg `view` must be wheel or box `view` ha de ser wheel o box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue
@msg `sliders` must be none, oklch or hsl `sliders` ha de ser none, oklch o hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball
@msg `name` is empty `name` és buit
@msg `newName` is empty `newName` és buit
@msg `pathfinder` must be an object `pathfinder` ha de ser un objecte
@@ -6799,6 +6812,10 @@ liquify-list-end {0}, {1} {0} i {1}
@msg a guide has no curvature circle una guia no té cercle de curvatura
@msg the circle that matches the path there would reach past the canvas el cercle que coincideix amb el traçat en aquest punt sortiria del llenç
@msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta
@msg `at` must be "start" or "end" `at` ha de ser "start" o "end"
@msg give exactly one of `through` and `toward` indiqueu exactament un de `through` i `toward`
@msg no arc fits these points: two are the same or all three lie on one line cap arc no s’ajusta a aquests punts: dos són iguals o tots tres són en una mateixa recta
@msg give `at` only with `toward` indiqueu `at` només amb `toward`
@msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers
@msg no artboard no hi ha tauler
@msg no artboard {i} (0-based; the document has {_1}) no hi ha el tauler {i} (basat en 0; el document en té {_1})
@@ -8918,6 +8935,16 @@ breakText Glyphs Glifs
Blossom Chain Cadena de flors
Pennant Garland Garlanda de banderins
Lantern String Filera de fanalets
Orbit Lines Línies orbitals
Petal Garland Garlanda de pètals
Lattice Braid Trena reticular
Facet Sweep Traç facetat
Artistic Brushes Pinzells artístics
Paint Pintura
Flat Sweep Traç pla
Dry Drag Arrossegament sec
Loaded Stroke Traç carregat
Fan Sweep Traç en ventall
Engraving Gravat
Fine Hatching Ratllat fi
Dense Hatching Ratllat dens
Can't render this file because it is too large.
+27
View File
@@ -809,6 +809,8 @@
Contextual Task Bar Kontextový panel úloh
Pin Bar Position Připnout polohu panelu
Reset Bar Position Obnovit polohu panelu
Bar Actions Akce panelu
Reset Bar Actions Obnovit akce panelu
Resize Změnit velikost
Tools Nástroje
Toolbars Panely nástrojů
@@ -1531,6 +1533,10 @@ lighting Light Světlo
Add Anchor Point Tool Nástroj Přidat kotevní bod
Anchor Point Tool Nástroj Kotevní bod
Arc Tool Nástroj Oblouk
Three-Point Arc Tool Nástroj Oblouk třemi body
Three-Point Arc Oblouk třemi body
Arc too large Oblouk je příliš velký
Third Point Sets Direction Třetí bod určuje směr
Area Graph Tool Nástroj Plošný graf
Area Type Tool Nástroj Text v oblasti
Artboard Tool Nástroj Pracovní plocha
@@ -4654,6 +4660,11 @@ axis Both Obě
Image Obraz
Ink Inkoust
Lab Lab
OKLCH Sliders Posuvníky OKLCH
HSL Sliders Posuvníky HSL
Chroma Chroma
The largest chroma sRGB holds at this lightness and hue Největší chroma, kterou sRGB obsáhne při této světlosti a odstínu
OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB
Medium Střední
Name Název
None Žádné
@@ -5492,6 +5503,8 @@ liquify-list-end {0}, {1} {0} a {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musí být grayscale, rgb, hsb, cmyk nebo websafe
@msg `view` must be wheel or box `view` musí být wheel nebo box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue
@msg `sliders` must be none, oklch or hsl `sliders` musí být none, oklch nebo hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB
@msg `{k}` must be [x, y] `{k}` musí být [x, y]
@msg `{name}` has no options `{name}` nemá žádné možnosti
@msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název
@@ -5685,6 +5698,10 @@ liquify-list-end {0}, {1} {0} a {1}
@msg a guide has no curvature circle vodítko nemá kružnici křivosti
@msg the circle that matches the path there would reach past the canvas kružnice odpovídající cestě v tomto místě by přesáhla plátno
@msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce
@msg `at` must be "start" or "end" `at` musí být "start" nebo "end"
@msg give exactly one of `through` and `toward` zadejte právě jeden z parametrů `through` a `toward`
@msg no arc fits these points: two are the same or all three lie on one line těmto bodům neodpovídá žádný oblouk: dva jsou stejné nebo všechny tři leží na jedné přímce
@msg give `at` only with `toward` parametr `at` zadejte jen s `toward`
@msg no app to open files here zde chybí aplikace pro otevírání souborů
@msg no artboard žádná pracovní plocha
@msg no artboard {i} (0-based; the document has {_1}) pracovní plocha {i} neexistuje (číslováno od 0; dokument jich má {_1})
@@ -10742,6 +10759,16 @@ breakText Glyphs Glyfy
Blossom Chain Květinový řetěz
Pennant Garland Girlanda praporků
Lantern String Řetěz luceren
Orbit Lines Orbitální čáry
Petal Garland Okvětní girlanda
Lattice Braid Mřížkový cop
Facet Sweep Fazetový tah
Artistic Brushes Umělecké štětce
Paint Malba
Flat Sweep Plochý tah
Dry Drag Suchý tah
Loaded Stroke Sytý tah
Fan Sweep Vějířový tah
Engraving Rytina
Fine Hatching Jemné šrafování
Dense Hatching Husté šrafování
Can't render this file because it is too large.
+27
View File
@@ -3507,6 +3507,8 @@ liquify-list-end {0}, {1} {0} og {1}
Contextual Task Bar Kontekstuel opgavelinje
Pin Bar Position Fastgør linjens placering
Reset Bar Position Nulstil linjens placering
Bar Actions Linjens handlinger
Reset Bar Actions Nulstil linjens handlinger
Tools Værktøjer
Toolbars Værktøjslinjer
Advanced Avanceret
@@ -4184,6 +4186,10 @@ lighting Light Lys
Add Anchor Point Tool Tilføj ankerpunkt-værktøj
Anchor Point Tool Ankerpunktværktøj
Arc Tool Bueværktøj
Three-Point Arc Tool Værktøj til bue gennem tre punkter
Three-Point Arc Bue gennem tre punkter
Arc too large Buen er for stor
Third Point Sets Direction Tredje punkt angiver retningen
Area Graph Tool Områdediagramværktøj
Area Type Tool Områdetekstværktøj
Artboard Tool Tegnebrætværktøj
@@ -7099,6 +7105,11 @@ axis Both Begge
Image Billede
Ink Blæk
Lab Lab
OKLCH Sliders OKLCH-skydere
HSL Sliders HSL-skydere
Chroma Kroma
The largest chroma sRGB holds at this lightness and hue Den største kroma, sRGB kan rumme ved denne lyshed og farvetone
OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum
Medium Medium
Name Navn
None Ingen
@@ -7881,6 +7892,10 @@ imageTrace Outline Kontur
@msg a guide has no curvature circle en hjælpelinje har ingen krumningscirkel
@msg the circle that matches the path there would reach past the canvas cirklen, der passer til kurven der, ville gå ud over lærredet
@msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje
@msg `at` must be "start" or "end" `at` skal være "start" eller "end"
@msg give exactly one of `through` and `toward` angiv præcis én af `through` og `toward`
@msg no arc fits these points: two are the same or all three lie on one line ingen bue passer til disse punkter: to er ens, eller alle tre ligger på én linje
@msg give `at` only with `toward` angiv kun `at` sammen med `toward`
@msg no app to open files here ingen app til at åbne filer her
@msg no artboard ingen tegneflade
@msg no artboard {i} (0-based; the document has {_1}) ingen tegneflade {i} (0-baseret; dokumentet har {_1})
@@ -9099,6 +9114,8 @@ variable-list-end {0}, {1} {0} og {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` skal være grayscale, rgb, hsb, cmyk eller websafe
@msg `view` must be wheel or box `view` skal være wheel eller box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue
@msg `sliders` must be none, oklch or hsl `sliders` skal være none, oklch eller hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum
@msg the Color Picker is not open farvevælgeren er ikke åben
@msg the screen color sampler is already open skærmfarvesampleren er allerede åben
@msg this system has no screen color sampler dette system har ingen skærmfarvesampler
@@ -10804,6 +10821,16 @@ breakText Glyphs Glyffer
Blossom Chain Blomsterkæde
Pennant Garland Vimpelguirlande
Lantern String Lygtekæde
Orbit Lines Banekurver
Petal Garland Kronbladsguirlande
Lattice Braid Gitterfletning
Facet Sweep Facetteret strøg
Artistic Brushes Kunstneriske pensler
Paint Maling
Flat Sweep Fladt strøg
Dry Drag Tørt træk
Loaded Stroke Fyldigt strøg
Fan Sweep Viftestrøg
Engraving Gravering
Fine Hatching Fin skravering
Dense Hatching Tæt skravering
Can't render this file because it is too large.
+27
View File
@@ -215,6 +215,10 @@ font-technology Variable Variabel
Arc Bogen
Arc Lower… Bogen unten…
Arc Tool Bogen-Werkzeug
Three-Point Arc Tool Dreipunkt-Bogen-Werkzeug
Three-Point Arc Dreipunkt-Bogen
Arc too large Bogen zu groß
Third Point Sets Direction Dritter Punkt gibt die Richtung an
Arc Upper… Bogen oben…
Arch… Torbogen…
Arc… Bogen…
@@ -632,6 +636,8 @@ font-technology Variable Variabel
Contextual Task Bar Kontextbezogene Taskleiste
Pin Bar Position Position der Leiste fixieren
Reset Bar Position Position der Leiste zurücksetzen
Bar Actions Aktionen der Leiste
Reset Bar Actions Aktionen der Leiste zurücksetzen
Resize Größe ändern
Contrast Kontrast
Control Steuerung
@@ -2034,6 +2040,11 @@ file-filter Templates Vorlagen
Knife Messer
Knockout Group Aussparungsgruppe
Lab Lab
OKLCH Sliders OKLCH-Regler
HSL Sliders HSL-Regler
Chroma Chroma
The largest chroma sRGB holds at this lightness and hue Das größte Chroma, das sRGB bei dieser Helligkeit und diesem Farbton enthält
OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum
Lab Spot Colors: Lab-Volltonfarben:
Lab Values Lab-Werte
Landscape Querformat
@@ -5068,6 +5079,8 @@ liquify-list-end {0}, {1} {0} und {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` muss grayscale, rgb, hsb, cmyk oder websafe sein
@msg `view` must be wheel or box `view` muss wheel oder box sein
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein
@msg `sliders` must be none, oklch or hsl `sliders` muss none, oklch oder hsl sein
@msg OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum
@msg `{k}` must be [x, y] `{k}` muss [x, y] sein
@msg `{name}` has no options `{name}` hat keine Optionen
@msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen
@@ -5261,6 +5274,10 @@ liquify-list-end {0}, {1} {0} und {1}
@msg a guide has no curvature circle eine Hilfslinie hat keinen Krümmungskreis
@msg the circle that matches the path there would reach past the canvas der Kreis, der dort zum Pfad passt, würde über die Arbeitsfläche hinausreichen
@msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie
@msg `at` must be "start" or "end" `at` muss „start“ oder „end“ sein
@msg give exactly one of `through` and `toward` geben Sie genau eines von `through` und `toward` an
@msg no arc fits these points: two are the same or all three lie on one line zu diesen Punkten passt kein Bogen: zwei sind gleich oder alle drei liegen auf einer Linie
@msg give `at` only with `toward` geben Sie `at` nur zusammen mit `toward` an
@msg no app to open files here hier gibt es keine App zum Öffnen von Dateien
@msg no artboard keine Zeichenfläche
@msg no artboard {i} (0-based; the document has {_1}) keine Zeichenfläche {i} (Zählung ab 0; das Dokument hat {_1})
@@ -10383,6 +10400,16 @@ breakText Glyphs Glyphen
Blossom Chain Blütenkette
Pennant Garland Wimpelgirlande
Lantern String Laternenkette
Orbit Lines Orbitlinien
Petal Garland Blütengirlande
Lattice Braid Gittergeflecht
Facet Sweep Facettenstrich
Artistic Brushes Künstlerische Pinsel
Paint Farbe
Flat Sweep Flacher Schwung
Dry Drag Trockener Zug
Loaded Stroke Satter Pinselstrich
Fan Sweep Fächerschwung
Engraving Gravur
Fine Hatching Feine Schraffur
Dense Hatching Dichte Schraffur
Can't render this file because it is too large.
+27
View File
@@ -217,6 +217,10 @@ font-technology Variable Μεταβλητές
Arc Τόξο
Arc Lower… Κάτω τόξο…
Arc Tool Τόξο (Arc Tool)
Three-Point Arc Tool Εργαλείο τόξου τριών σημείων
Three-Point Arc Τόξο τριών σημείων
Arc too large Το τόξο είναι πολύ μεγάλο
Third Point Sets Direction Το τρίτο σημείο ορίζει την κατεύθυνση
Arc Upper… Πάνω τόξο…
Arch… Αψίδα…
Arc… Τόξο…
@@ -606,6 +610,8 @@ font-technology Variable Μεταβλητές
Contextual Task Bar Γραμμή εργασιών βάσει περιβάλλοντος
Pin Bar Position Σταθεροποίηση θέσης γραμμής
Reset Bar Position Επαναφορά θέσης γραμμής
Bar Actions Ενέργειες γραμμής
Reset Bar Actions Επαναφορά ενεργειών γραμμής
Resize Αλλαγή μεγέθους
Contrast Αντίθεση
Control Έλεγχος
@@ -1929,6 +1935,11 @@ font-technology Variable Μεταβλητές
Knife Μαχαίρι (Knife)
Knockout Group Ομάδα διάτρησης
Lab Lab
OKLCH Sliders Ρυθμιστικά OKLCH
HSL Sliders Ρυθμιστικά HSL
Chroma Χρωματική ένταση
The largest chroma sRGB holds at this lightness and hue Η μεγαλύτερη χρωματική ένταση που χωρά το sRGB σε αυτή τη φωτεινότητα και απόχρωση
OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB
Lab Spot Colors: Πλακάτα χρώματα Lab:
Lab Values Τιμές Lab
Landscape Οριζόντιος προσανατολισμός
@@ -5322,6 +5333,10 @@ digits Malayalam Μαλαγιάλαμ
@msg a guide has no curvature circle ένας οδηγός δεν έχει κύκλο καμπυλότητας
@msg the circle that matches the path there would reach past the canvas ο κύκλος που ταιριάζει με τη διαδρομή εκεί θα υπερέβαινε τον καμβά
@msg no circle passes through these points: two are the same or all three lie on one line κανένας κύκλος δεν περνά από αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία
@msg `at` must be "start" or "end" το `at` πρέπει να είναι "start" ή "end"
@msg give exactly one of `through` and `toward` δώστε ακριβώς ένα από τα `through` και `toward`
@msg no arc fits these points: two are the same or all three lie on one line κανένα τόξο δεν ταιριάζει σε αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία
@msg give `at` only with `toward` δώστε το `at` μόνο μαζί με το `toward`
@msg no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ
@msg no artboard δεν υπάρχει πίνακας σχεδίασης
@msg no artboard {i} (0-based; the document has {_1}) δεν υπάρχει πίνακας σχεδίασης {i} (αρίθμηση από 0· το έγγραφο περιέχει {_1})
@@ -6975,6 +6990,8 @@ effect Points Σημεία
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe
@msg `view` must be wheel or box το `view` πρέπει να είναι wheel ή box
@msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue
@msg `sliders` must be none, oklch or hsl Το `sliders` πρέπει να είναι none, oklch ή hsl
@msg OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB
@msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1}
@msg choose a destination folder επιλέξτε φάκελο προορισμού
@msg choose a source folder επιλέξτε φάκελο προέλευσης
@@ -8891,6 +8908,16 @@ breakText Glyphs Γλύφοι
Blossom Chain Αλυσίδα λουλουδιών
Pennant Garland Γιρλάντα σημαιών
Lantern String Σειρά φαναριών
Orbit Lines Τροχιακές γραμμές
Petal Garland Γιρλάντα πετάλων
Lattice Braid Πλεξούδα πλέγματος
Facet Sweep Πολυεδρική πινελιά
Artistic Brushes Καλλιτεχνικά πινέλα
Paint Ζωγραφική
Flat Sweep Επίπεδη πινελιά
Dry Drag Στεγνό σύρσιμο
Loaded Stroke Γεμάτη πινελιά
Fan Sweep Βεντάλια
Engraving Χαρακτική
Fine Hatching Λεπτή διαγράμμιση
Dense Hatching Πυκνή διαγράμμιση
Can't render this file because it is too large.
+27
View File
@@ -238,6 +238,10 @@ font-technology Variable Variables
Arc Arco
Arc Lower… Arco inferior…
Arc Tool Herramienta Arco
Three-Point Arc Tool Herramienta Arco por tres puntos
Three-Point Arc Arco por tres puntos
Arc too large Arco demasiado grande
Third Point Sets Direction El tercer punto indica la dirección
Arc Upper… Arco superior…
Arch… Arcada…
Arc… Arco…
@@ -652,6 +656,8 @@ font-technology Variable Variables
Contextual Task Bar Barra de tareas contextual
Pin Bar Position Fijar posición de la barra
Reset Bar Position Restablecer posición de la barra
Bar Actions Acciones de la barra
Reset Bar Actions Restablecer acciones de la barra
Resize Cambiar tamaño
Contrast Contraste
Control Control
@@ -2033,6 +2039,11 @@ font-technology Variable Variables
Knife Cuchilla
Knockout Group Grupo de exclusión
Lab Lab
OKLCH Sliders Controles deslizantes OKLCH
HSL Sliders Controles deslizantes HSL
Chroma Croma
The largest chroma sRGB holds at this lightness and hue El croma más alto que admite sRGB con esta luminosidad y este tono
OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB
Lab Spot Colors: Tintas planas Lab:
Lab Values Valores Lab
Landscape Horizontal
@@ -5180,6 +5191,8 @@ liquify-list-end {0}, {1} {0}, {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` debe ser grayscale, rgb, hsb, cmyk o websafe
@msg `view` must be wheel or box `view` debe ser wheel o box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue
@msg `sliders` must be none, oklch or hsl `sliders` debe ser none, oklch o hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB
@msg `{k}` must be [x, y] `{k}` debe ser [x, y]
@msg `{name}` has no options `{name}` no tiene opciones
@msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre
@@ -5373,6 +5386,10 @@ liquify-list-end {0}, {1} {0}, {1}
@msg a guide has no curvature circle una guía no tiene círculo de curvatura
@msg the circle that matches the path there would reach past the canvas el círculo que coincide con el trazado en ese punto excedería el lienzo
@msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea
@msg `at` must be "start" or "end" `at` debe ser "start" o "end"
@msg give exactly one of `through` and `toward` indique exactamente uno de `through` y `toward`
@msg no arc fits these points: two are the same or all three lie on one line ningún arco se ajusta a estos puntos: dos son iguales o los tres están en una misma línea
@msg give `at` only with `toward` indique `at` solo junto con `toward`
@msg no app to open files here aquí no hay ninguna aplicación para abrir archivos
@msg no artboard no hay mesa de trabajo
@msg no artboard {i} (0-based; the document has {_1}) no existe la mesa de trabajo {i} (contando desde 0; el documento tiene {_1})
@@ -10635,6 +10652,16 @@ breakText Glyphs Glifos
Blossom Chain Cadena de flores
Pennant Garland Guirnalda de banderines
Lantern String Cadena de faroles
Orbit Lines Líneas orbitales
Petal Garland Guirnalda de pétalos
Lattice Braid Trenza reticular
Facet Sweep Trazo facetado
Artistic Brushes Pinceles artísticos
Paint Pintura
Flat Sweep Barrido plano
Dry Drag Arrastre seco
Loaded Stroke Trazo cargado
Fan Sweep Barrido en abanico
Engraving Grabado
Fine Hatching Rayado fino
Dense Hatching Rayado denso
Can't render this file because it is too large.
+27
View File
@@ -795,6 +795,8 @@
Contextual Task Bar Kontekstuaalinen tehtäväpalkki
Pin Bar Position Kiinnitä palkin sijainti
Reset Bar Position Palauta palkin sijainti
Bar Actions Palkin toiminnot
Reset Bar Actions Palauta palkin toiminnot
Resize Muuta kokoa
Tools Työkalut
Toolbars Työkalurivit
@@ -1502,6 +1504,10 @@ lighting Light Valo
Add Anchor Point Tool Lisää ankkuripiste -työkalu
Anchor Point Tool Ankkuripistetyökalu
Arc Tool Kaarityökalu
Three-Point Arc Tool Kolmen pisteen kaaren työkalu
Three-Point Arc Kolmen pisteen kaari
Arc too large Kaari on liian suuri
Third Point Sets Direction Kolmas piste määrää suunnan
Area Graph Tool Aluekaaviotyökalu
Area Type Tool Aluetekstityökalu
Artboard Tool Piirtoalustatyökalu
@@ -4564,6 +4570,11 @@ axis Both Molemmat
Image Kuva
Ink Muste
Lab Lab
OKLCH Sliders OKLCH-liukusäätimet
HSL Sliders HSL-liukusäätimet
Chroma Kroma
The largest chroma sRGB holds at this lightness and hue Suurin kroma, jonka sRGB sisältää tällä vaaleudella ja sävyllä
OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi
Medium Keskitaso
Name Nimi
None Ei mitään
@@ -5606,6 +5617,10 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg a guide has no curvature circle apuviivalla ei ole kaarevuusympyrää
@msg the circle that matches the path there would reach past the canvas ympyrä, joka vastaa polkua siinä kohdassa, ylittäisi kankaan
@msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla
@msg `at` must be "start" or "end" `at` on oltava "start" tai "end"
@msg give exactly one of `through` and `toward` anna täsmälleen yksi parametreista `through` ja `toward`
@msg no arc fits these points: two are the same or all three lie on one line näihin pisteisiin ei sovi kaarta: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla
@msg give `at` only with `toward` anna `at` vain yhdessä parametrin `toward` kanssa
@msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen
@msg no artboard ei piirtoalustaa
@msg no artboard {i} (0-based; the document has {_1}) ei piirtoalustaa {i} (0-pohjainen; asiakirjassa on {_1})
@@ -6980,6 +6995,8 @@ mark-style Japanese Japanilainen
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe
@msg `view` must be wheel or box `view`-arvon on oltava wheel tai box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue
@msg `sliders` must be none, oklch or hsl `sliders` on oltava none, oklch tai hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi
@msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1}
@msg choose a destination folder valitse kohdekansio
@msg choose a source folder valitse lähdekansio
@@ -8974,6 +8991,16 @@ breakText Glyphs Merkit
Blossom Chain Kukkaketju
Pennant Garland Viiririvistö
Lantern String Lyhtyketju
Orbit Lines Kiertoradan viivat
Petal Garland Terälehtiköynnös
Lattice Braid Ristikkopunos
Facet Sweep Särmikäs veto
Artistic Brushes Taidesiveltimet
Paint Maalaus
Flat Sweep Tasainen veto
Dry Drag Kuiva veto
Loaded Stroke Runsas siveltimenveto
Fan Sweep Viuhkaveto
Engraving Kaiverrus
Fine Hatching Hieno viivoitus
Dense Hatching Tiheä viivoitus
Can't render this file because it is too large.
+27
View File
@@ -239,6 +239,10 @@ font-technology Variable Variables
Arc Arc
Arc Lower… Arc inférieur…
Arc Tool Outil Arc
Three-Point Arc Tool Outil Arc par trois points
Three-Point Arc Arc par trois points
Arc too large Arc trop grand
Third Point Sets Direction Le troisième point indique la direction
Arc Upper… Arc supérieur…
Arch… Arche…
Arc… Arc…
@@ -653,6 +657,8 @@ font-technology Variable Variables
Contextual Task Bar Barre des tâches contextuelle
Pin Bar Position Épingler la position de la barre
Reset Bar Position Réinitialiser la position de la barre
Bar Actions Actions de la barre
Reset Bar Actions Réinitialiser les actions de la barre
Resize Redimensionner
Contrast Contraste
Control Contrôle
@@ -2023,6 +2029,11 @@ font-technology Variable Variables
Knife Cutter
Knockout Group Groupe perçant
Lab Lab
OKLCH Sliders Curseurs OKLCH
HSL Sliders Curseurs HSL
Chroma Chroma
The largest chroma sRGB holds at this lightness and hue Le plus grand chroma que sRGB contient à cette luminosité et cette teinte
OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB
Lab Spot Colors: Tons directs Lab :
Lab Values Valeurs Lab
Landscape Paysage
@@ -5139,6 +5150,8 @@ liquify-list-end {0}, {1} {0} et {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` doit valoir grayscale, rgb, hsb, cmyk ou websafe
@msg `view` must be wheel or box `view` doit valoir wheel ou box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue
@msg `sliders` must be none, oklch or hsl `sliders` doit valoir none, oklch ou hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB
@msg `{k}` must be [x, y] `{k}` doit être [x, y]
@msg `{name}` has no options `{name}` n’a pas d’options
@msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom
@@ -5332,6 +5345,10 @@ liquify-list-end {0}, {1} {0} et {1}
@msg a guide has no curvature circle un repère n’a pas de cercle de courbure
@msg the circle that matches the path there would reach past the canvas le cercle qui correspond au tracé à cet endroit dépasserait la zone de travail
@msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés
@msg `at` must be "start" or "end" `at` doit valoir "start" ou "end"
@msg give exactly one of `through` and `toward` indiquez exactement un seul de `through` et `toward`
@msg no arc fits these points: two are the same or all three lie on one line aucun arc ne correspond à ces points : deux sont identiques ou les trois sont alignés
@msg give `at` only with `toward` indiquez `at` uniquement avec `toward`
@msg no app to open files here aucune application pour ouvrir des fichiers ici
@msg no artboard aucun plan de travail
@msg no artboard {i} (0-based; the document has {_1}) aucun plan de travail {i} (numérotation à partir de 0 ; le document en a {_1})
@@ -10705,6 +10722,16 @@ breakText Glyphs Glyphes
Blossom Chain Chaîne de fleurs
Pennant Garland Guirlande de fanions
Lantern String Guirlande de lanternes
Orbit Lines Lignes orbitales
Petal Garland Guirlande de pétales
Lattice Braid Tresse en treillis
Facet Sweep Trait à facettes
Artistic Brushes Pinceaux artistiques
Paint Peinture
Flat Sweep Balayage plat
Dry Drag Traînée sèche
Loaded Stroke Trait chargé
Fan Sweep Balayage en éventail
Engraving Gravure
Fine Hatching Hachures fines
Dense Hatching Hachures denses
Can't render this file because it is too large.
+26
View File
@@ -283,6 +283,10 @@
Arc Lower… નીચે આર્ક…
Arc Segment Tool Options આર્ક સેગમેન્ટ ટૂલ વિકલ્પો
Arc Tool આર્ક ટૂલ
Three-Point Arc Tool ત્રણ-પૉઇન્ટ આર્ક ટૂલ
Three-Point Arc ત્રણ-પૉઇન્ટ આર્ક
Arc too large આર્ક ખૂબ મોટો છે
Third Point Sets Direction ત્રીજો પૉઇન્ટ દિશા નક્કી કરે છે
Arc Upper… ઉપર આર્ક…
Arch… કમાન…
Arc… આર્ક…
@@ -2036,6 +2040,12 @@
Knife નાઇફ
Knockout Group નૉકઆઉટ ગ્રૂપ
LZW Compression LZW કમ્પ્રેશન
OKLCH Sliders OKLCH સ્લાઇડર્સ
HSL Sliders HSL સ્લાઇડર્સ
Chroma ક્રોમા
The largest chroma sRGB holds at this lightness and hue આ લાઇટનેસ અને હ્યૂ પર sRGB સમાવી શકે તે સૌથી વધુ ક્રોમા
OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે
Lightness લાઇટનેસ
Lab Spot Colors: Lab સ્પોટ રંગો:
Landscape લેન્ડસ્કેપ
Language ભાષા
@@ -3280,6 +3290,8 @@ arrowhead Feather પીંછું
Reselect ફરી પસંદ કરો
Reset રીસેટ કરો
Reset Bar Position બાર સ્થિતિ રીસેટ કરો
Bar Actions બાર ક્રિયાઓ
Reset Bar Actions બાર ક્રિયાઓ રીસેટ કરો
Reset Bounding Box બાઉન્ડિંગ બોક્સ રીસેટ કરો
Rotate Bounding Box બાઉન્ડિંગ બોક્સ ફેરવો
Rotate Bounding Box… બાઉન્ડિંગ બોક્સ ફેરવો…
@@ -5634,6 +5646,20 @@ swatch [Registration] [રજિસ્ટ્રેશન]
Blossom Chain ફૂલોની સાંકળ
Pennant Garland ધ્વજપટ્ટીની માળા
Lantern String ફાનસની હાર
Orbit Lines ભ્રમણકક્ષાની રેખાઓ
Petal Garland પાંખડીઓની માળા
Lattice Braid જાળી વેણી
Facet Sweep પાસાદાર રેખા
Artistic Brushes કલાત્મક બ્રશ
Paint રંગકામ
Flat Sweep સપાટ લસરકો
Dry Drag સૂકો ઘસારો
Loaded Stroke ઘાટો પીંછીનો ઘસારો
Fan Sweep પંખા જેવો લસરકો
@msg `at` must be "start" or "end" `at` "start" અથવા "end" હોવું જોઈએ
@msg give exactly one of `through` and `toward` `through` અને `toward` માંથી બરાબર એક આપો
@msg no arc fits these points: two are the same or all three lie on one line આ પૉઇન્ટ્સમાં કોઈ આર્ક બેસતો નથી: બે એકસરખા છે અથવા ત્રણેય એક જ રેખા પર છે
@msg give `at` only with `toward` `at` ફક્ત `toward` સાથે જ આપો
Engraving કોતરણી
Fine Hatching ઝીણી રેખાઓ
Dense Hatching ગાઢ રેખાઓ
Can't render this file because it contains an unexpected character in line 72 and column 5.
+27
View File
@@ -398,6 +398,10 @@ antiAlias Sharp शार्प
Arc Lower… निचला आर्क…
Arc Segment Tool Options आर्क सेगमेंट टूल ऑप्शन्स
Arc Tool आर्क टूल
Three-Point Arc Tool थ्री-पॉइंट आर्क टूल
Three-Point Arc थ्री-पॉइंट आर्क
Arc too large आर्क बहुत बड़ा है
Third Point Sets Direction तीसरा पॉइंट दिशा तय करता है
Arc Upper… ऊपरी आर्क…
Arc… आर्क…
Arch… मेहराब…
@@ -2997,6 +3001,11 @@ arrowhead Feather पंख
Knife चाकू
Knockout Group नॉकआउट समूह
Lab Lab
OKLCH Sliders OKLCH स्लाइडर्स
HSL Sliders HSL स्लाइडर्स
Chroma क्रोमा
The largest chroma sRGB holds at this lightness and hue इस लाइटनेस और ह्यू पर sRGB में आने वाला सबसे अधिक क्रोमा
OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए
Lab Spot Colors लैब स्पॉट रंग
Lab Spot Colors: लैब स्पॉट रंग:
Lab Values लैब मूल्य
@@ -4571,6 +4580,8 @@ arrowhead Feather पंख
Reset all Revolve settings to their defaults. सभी रिवॉल्व सेटिंग्स डिफ़ॉल्ट पर रीसेट करें।
Reset Automation स्वचालन रीसेट करें
Reset Bar Position बार स्थिति रीसेट करें
Bar Actions बार क्रियाएँ
Reset Bar Actions बार क्रियाएँ रीसेट करें
Reset Bounding Box बाउंडिंग बॉक्स रीसेट करें
Rotate Bounding Box बाउंडिंग बॉक्स घुमाएँ
Rotate Bounding Box… बाउंडिंग बॉक्स घुमाएँ…
@@ -7060,6 +7071,8 @@ arrowhead Feather पंख
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए
@msg `view` must be wheel or box `view` को wheel या box होना चाहिए
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए
@msg `sliders` must be none, oklch or hsl `sliders` none, oklch या hsl होना चाहिए
@msg OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए
@msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए
@msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए।
@msg `name` is empty `name` खाली है
@@ -8302,6 +8315,10 @@ liquify-list-end {0}, {1} {0} और {1}
@msg a guide has no curvature circle गाइड का कोई वक्रता वृत्त नहीं होता
@msg the circle that matches the path there would reach past the canvas वहाँ पाथ से मेल खाने वाला वृत्त कैनवास से बाहर चला जाएगा
@msg no circle passes through these points: two are the same or all three lie on one line इन पॉइंट्स से होकर कोई वृत्त नहीं गुज़रता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं
@msg `at` must be "start" or "end" `at` को "start" या "end" होना चाहिए।
@msg give exactly one of `through` and `toward` `through` और `toward` में से ठीक एक दें
@msg no arc fits these points: two are the same or all three lie on one line इन पॉइंट्स पर कोई आर्क फ़िट नहीं होता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं
@msg give `at` only with `toward` `at` केवल `toward` के साथ दें
@msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है
@msg no appearance item {index} कोई उपस्थिति आइटम {index}
@msg no artboard कोई आर्टबोर्ड नहीं
@@ -10348,6 +10365,16 @@ theme Appearance अपीयरेंस
Blossom Chain फूलों की शृंखला
Pennant Garland झंडियों की माला
Lantern String लालटेन की शृंखला
Orbit Lines कक्षीय रेखाएँ
Petal Garland पंखुड़ी माला
Lattice Braid जाली चोटी
Facet Sweep पहलूदार स्ट्रोक
Artistic Brushes कलात्मक ब्रश
Paint चित्रकारी
Flat Sweep सपाट फेरा
Dry Drag सूखा घिसाव
Loaded Stroke गाढ़ा ब्रश स्ट्रोक
Fan Sweep पंखे जैसा फेरा
Engraving नक्काशी
Fine Hatching बारीक रेखांकन
Dense Hatching घना रेखांकन
Can't render this file because it is too large.
+27
View File
@@ -322,6 +322,10 @@ font-technology Variable Változó
Arc Ív
Arc Lower… Alsó ív…
Arc Tool Ív
Three-Point Arc Tool Hárompontos ív eszköz
Three-Point Arc Hárompontos ív
Arc too large Az ív túl nagy
Third Point Sets Direction A harmadik pont adja meg az irányt
Arc Upper… Felső ív…
Arch… Boltív…
Arc… Ív…
@@ -2517,6 +2521,11 @@ file-filter Templates Sablonok
Knife Kés
Knockout Group Kiütő csoport
Lab Lab
OKLCH Sliders OKLCH csúszkák
HSL Sliders HSL csúszkák
Chroma Króma
The largest chroma sRGB holds at this lightness and hue A legnagyobb króma, amelyet az sRGB ezen a világosságon és színárnyalaton tartalmaz
OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges
Lab Spot Colors Lab-direktszínek
Lab Spot Colors: Lab-direktszínek:
Lab Values Lab-értékek
@@ -3784,6 +3793,8 @@ mark-style Japanese Japán
Reset all Revolve settings to their defaults. A tengely körüli forgatás minden beállítását visszaállítja az alapértékre.
Reset Automation Automation visszaállítása
Reset Bar Position Sáv helyének visszaállítása
Bar Actions Sáv műveletei
Reset Bar Actions Sáv műveleteinek visszaállítása
Reset Bounding Box Befoglaló keret visszaállítása
Rotate Bounding Box Befoglaló keret elforgatása
Rotate Bounding Box… Befoglaló keret elforgatása…
@@ -5519,6 +5530,8 @@ imageTrace Outline Körvonal
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`: grayscale, rgb, hsb, cmyk vagy websafe kell
@msg `view` must be wheel or box `view`: wheel vagy box kell
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell
@msg `sliders` must be none, oklch or hsl A `sliders` értéke none, oklch vagy hsl lehet
@msg OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges
@msg `{k}` must be [x, y] `{k}`: [x, y] kell
@msg `{name}` has no options ennek nincsenek beállításai: `{name}`
@msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet
@@ -6060,6 +6073,10 @@ liquify-list-end {0}, {1} {0} és {1}
@msg a guide has no curvature circle a segédvonalnak nincs görbületi köre
@msg the circle that matches the path there would reach past the canvas az útvonalhoz ott illeszkedő kör túlnyúlna a vásznon
@msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van
@msg `at` must be "start" or "end" `at`: "start" vagy "end" kell
@msg give exactly one of `through` and `toward` pontosan egyet adjon meg a `through` és a `toward` közül
@msg no arc fits these points: two are the same or all three lie on one line ezekre a pontokra nem illeszkedik ív: kettő egybeesik, vagy mindhárom egy egyenesen van
@msg give `at` only with `toward` az `at` csak a `toward` mellett adható meg
@msg no app to open files here itt nincs fájlmegnyitó alkalmazás
@msg no artboard nincs rajztábla
@msg no artboard {i} (0-based; the document has {_1}) nincs ilyen sorszámú rajztábla: {i} (0-tól számozva; a dokumentumban ennyi van: {_1})
@@ -10731,6 +10748,16 @@ breakText Glyphs Glifák
Blossom Chain Virágfüzér
Pennant Garland Zászlófüzér
Lantern String Lámpásfüzér
Orbit Lines Pályavonalak
Petal Garland Sziromfüzér
Lattice Braid Rácsfonat
Facet Sweep Fazettás vonás
Artistic Brushes Művészi ecsetek
Paint Festék
Flat Sweep Lapos húzás
Dry Drag Száraz húzás
Loaded Stroke Telített ecsetvonás
Fan Sweep Legyezővonás
Engraving Metszet
Fine Hatching Finom vonalkázás
Dense Hatching Sűrű vonalkázás
Can't render this file because it is too large.
+27
View File
@@ -1384,6 +1384,8 @@
Contextual Task Bar Bilah tugas kontekstual
Pin Bar Position Sematkan posisi bilah
Reset Bar Position Atur ulang posisi bilah
Bar Actions Tindakan bilah
Reset Bar Actions Atur ulang tindakan bilah
Tools Alat
Toolbars Bilah alat
Advanced Lanjutan
@@ -2061,6 +2063,10 @@ lighting Light Cahaya
Add Anchor Point Tool Alat tambah titik jangkar
Anchor Point Tool Alat titik jangkar
Arc Tool Alat busur
Three-Point Arc Tool Alat busur tiga titik
Three-Point Arc Busur tiga titik
Arc too large Busur terlalu besar
Third Point Sets Direction Titik ketiga menentukan arah
Area Graph Tool Alat grafik area
Area Type Tool Alat teks area
Artboard Tool Alat artboard
@@ -4965,6 +4971,11 @@ axis Both Keduanya
Image Gambar
Ink Tinta
Lab Lab
OKLCH Sliders Penggeser OKLCH
HSL Sliders Penggeser HSL
Chroma Kroma
The largest chroma sRGB holds at this lightness and hue Kroma terbesar yang dapat dimuat sRGB pada kecerahan dan rona ini
OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja
Medium Sedang
Name Nama
None Nihil
@@ -6893,6 +6904,8 @@ mark-style Japanese Jepang
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` harus grayscale, rgb, hsb, cmyk atau websafe
@msg `view` must be wheel or box `view` harus wheel atau box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue
@msg `sliders` must be none, oklch or hsl `sliders` harus none, oklch, atau hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja
@msg the Color Picker is not open Pemilih Warna tidak terbuka
@msg the screen color sampler is already open pengambil warna layar sudah terbuka
@msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar
@@ -8584,6 +8597,20 @@ breakText Glyphs Glif
Blossom Chain Rangkaian Bunga
Pennant Garland Untaian Panji
Lantern String Rangkaian Lentera
Orbit Lines Garis Orbit
Petal Garland Rangkaian Kelopak
Lattice Braid Anyaman Kisi
Facet Sweep Sapuan Berfaset
Artistic Brushes Kuas Artistik
Paint Cat
Flat Sweep Sapuan Datar
Dry Drag Tarikan Kering
Loaded Stroke Sapuan Tebal
Fan Sweep Sapuan Kipas
@msg `at` must be "start" or "end" `at` harus "start" atau "end"
@msg give exactly one of `through` and `toward` berikan tepat satu dari `through` dan `toward`
@msg no arc fits these points: two are the same or all three lie on one line tidak ada busur yang cocok dengan titik-titik ini: dua titik sama atau ketiganya segaris
@msg give `at` only with `toward` berikan `at` hanya bersama `toward`
Engraving Ukiran
Fine Hatching Arsiran halus
Dense Hatching Arsiran rapat
Can't render this file because it is too large.
+27
View File
@@ -240,6 +240,10 @@ font-technology Variable Variabili
Arc Arco
Arc Lower… Arco inferiore…
Arc Tool Strumento Arco
Three-Point Arc Tool Strumento Arco per tre punti
Three-Point Arc Arco per tre punti
Arc too large Arco troppo grande
Third Point Sets Direction Il terzo punto indica la direzione
Arc Upper… Arco superiore…
Arch… Arcata…
Arc… Arco…
@@ -654,6 +658,8 @@ font-technology Variable Variabili
Contextual Task Bar Barra attività contestuale
Pin Bar Position Fissa posizione barra
Reset Bar Position Ripristina posizione barra
Bar Actions Azioni barra
Reset Bar Actions Ripristina azioni barra
Resize Ridimensiona
Contrast Contrasto
Control Controllo
@@ -2074,6 +2080,11 @@ file-filter Templates Modelli
Knife Coltello
Knockout Group Gruppo con foratura
Lab Lab
OKLCH Sliders Cursori OKLCH
HSL Sliders Cursori HSL
Chroma Croma
The largest chroma sRGB holds at this lightness and hue Il croma più alto che sRGB contiene con questa luminosità e tonalità
OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB
Lab Spot Colors: Colori spot Lab:
Lab Values Valori Lab
Landscape Orizzontale
@@ -5206,6 +5217,8 @@ liquify-list-end {0}, {1} {0} e {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve essere grayscale, rgb, hsb, cmyk o websafe
@msg `view` must be wheel or box `view` deve essere wheel o box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue
@msg `sliders` must be none, oklch or hsl `sliders` deve essere none, oklch o hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB
@msg `{k}` must be [x, y] `{k}` deve essere [x, y]
@msg `{name}` has no options `{name}` non ha opzioni
@msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome
@@ -5399,6 +5412,10 @@ liquify-list-end {0}, {1} {0} e {1}
@msg a guide has no curvature circle una guida non ha un cerchio di curvatura
@msg the circle that matches the path there would reach past the canvas il cerchio che corrisponde al tracciato in quel punto supererebbe l'area di lavoro
@msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati
@msg `at` must be "start" or "end" `at` deve essere "start" o "end"
@msg give exactly one of `through` and `toward` indicare esattamente uno tra `through` e `toward`
@msg no arc fits these points: two are the same or all three lie on one line nessun arco si adatta a questi punti: due coincidono oppure tutti e tre sono allineati
@msg give `at` only with `toward` indicare `at` solo insieme a `toward`
@msg no app to open files here nessuna app per aprire file qui
@msg no artboard nessuna tavola da disegno
@msg no artboard {i} (0-based; the document has {_1}) nessuna tavola da disegno {i} (a partire da 0; il documento ne ha {_1})
@@ -10417,6 +10434,16 @@ breakText Glyphs Glifi
Blossom Chain Catena di fiori
Pennant Garland Ghirlanda di bandierine
Lantern String Fila di lanterne
Orbit Lines Linee orbitali
Petal Garland Ghirlanda di petali
Lattice Braid Intreccio a reticolo
Facet Sweep Tratto sfaccettato
Artistic Brushes Pennelli artistici
Paint Pittura
Flat Sweep Passata piatta
Dry Drag Trascinamento secco
Loaded Stroke Tratto carico
Fan Sweep Passata a ventaglio
Engraving Incisione
Fine Hatching Tratteggio fine
Dense Hatching Tratteggio fitto
Can't render this file because it is too large.
+27
View File
@@ -846,6 +846,8 @@ digits Malayalam マラヤーラム数字
Contextual Task Bar コンテキストタスクバー
Pin Bar Position バーの位置を固定
Reset Bar Position バーの位置をリセット
Bar Actions バーのアクション
Reset Bar Actions バーのアクションをリセット
Resize サイズを変更
Tools ツール
Toolbars ツールバー
@@ -1236,6 +1238,10 @@ antiAlias Sharp シャープ
@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) すべてに適用 (ほかに {n} 個が見つかりません)
Arc 円弧
Arc Tool 円弧ツール
Three-Point Arc Tool 3 点円弧ツール
Three-Point Arc 3 点円弧
Arc too large 円弧が大きすぎます
Third Point Sets Direction 3 点目で方向を指定
Area / Path Type エリア内文字/パス上文字
Area Graph Tool 面グラフツール
Area Type Tool エリア内文字ツール
@@ -4412,6 +4418,11 @@ file-filter Templates テンプレート
Keep the pasted color as a new swatch with a numbered name. ペーストしたカラーを、番号付きの名前で新規スウォッチとして残します。
Keep: 保持:
Lab Lab
OKLCH Sliders OKLCH スライダー
HSL Sliders HSL スライダー
Chroma クロマ
The largest chroma sRGB holds at this lightness and hue この明度と色相で sRGB に収まる最大のクロマ
OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です
Lab Values Lab 値
Large List View 大きいリスト表示
Large Thumbnail View 大きいサムネール表示
@@ -5164,6 +5175,10 @@ variable-list-end {0}, {1} {0}、{1}
@msg a guide has no curvature circle ガイドには曲率円がありません
@msg the circle that matches the path there would reach past the canvas その位置でパスに合う円はキャンバスからはみ出します
@msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります
@msg `at` must be "start" or "end" `at` には "start" または "end" を指定してください
@msg give exactly one of `through` and `toward` `through` と `toward` のどちらか一方だけを指定してください
@msg no arc fits these points: two are the same or all three lie on one line これらの点に合う円弧はありません: 2 つの点が同じか、3 点すべてが一直線上にあります
@msg give `at` only with `toward` `at` は `toward` と一緒にだけ指定してください
@msg select at least two objects オブジェクトを 2 つ以上選択してください
@msg exit isolation mode first 先に分離モードを終了してください
@msg no saved presets 保存したプリセットはありません
@@ -5632,6 +5647,8 @@ variable-list-end {0}, {1} {0}、{1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` には grayscale、rgb、hsb、cmyk、websafe のいずれかを指定してください
@msg `view` must be wheel or box `view` には wheel、box のいずれかを指定してください
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください
@msg `sliders` must be none, oklch or hsl `sliders` には none、oklch、hsl のいずれかを指定してください
@msg OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です
@msg `{key}` must be true or false `{key}` には true または false を指定してください
@msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません
@msg `select` must be true or false `select` には true または false を指定してください
@@ -10480,6 +10497,16 @@ breakText Glyphs 字形
Blossom Chain 花の連なり
Pennant Garland 三角旗のガーランド
Lantern String ランタンの連なり
Orbit Lines 軌道線
Petal Garland 花びらのガーランド
Lattice Braid 格子編み
Facet Sweep 多面体のストローク
Artistic Brushes アートブラシ
Paint ペイント
Flat Sweep 平筆の一掃き
Dry Drag ドライドラッグ
Loaded Stroke 厚塗りストローク
Fan Sweep 扇形の一掃き
Engraving 彫刻
Fine Hatching 細いハッチング
Dense Hatching 密なハッチング
Can't render this file because it is too large.
+27
View File
@@ -2920,6 +2920,8 @@
Contextual Task Bar კონტექსტური ამოცანების ზოლი
Pin Bar Position ზოლის პოზიციის ჩამაგრება
Reset Bar Position ზოლის პოზიციის ჩამოყრა
Bar Actions ზოლის მოქმედებები
Reset Bar Actions ზოლის მოქმედებების ჩამოყრა
Tools ხელსაწყოები
Toolbars ხელსაწყოთა ზოლები
Advanced დამატებითი
@@ -3585,6 +3587,10 @@ lighting Light სინათლე
Add Anchor Point Tool საყრდენი წერტილის დამატების ხელსაწყო
Anchor Point Tool საყრდენი წერტილის ხელსაწყო
Arc Tool რკალის ხელსაწყო
Three-Point Arc Tool სამწერტილიანი რკალის ხელსაწყო
Three-Point Arc სამწერტილიანი რკალი
Arc too large რკალი ზედმეტად დიდია
Third Point Sets Direction მესამე წერტილი მიმართულებას განსაზღვრავს
Area Graph Tool ფართობითი დიაგრამის ხელსაწყო
Area Type Tool არის ტექსტის ხელსაწყო
Artboard Tool სამუშაო დაფის ხელსაწყო
@@ -6359,6 +6365,11 @@ axis Both ორივე
Image გამოსახულება
Ink მელანი
Lab Lab
OKLCH Sliders OKLCH სლაიდერები
HSL Sliders HSL სლაიდერები
Chroma ქრომა
The largest chroma sRGB holds at this lightness and hue უდიდესი ქრომა, რომელსაც sRGB იტევს ამ სიღიავესა და ფერის ტონზე
OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება
Medium საშუალო
Name სახელი
None არცერთი
@@ -7140,6 +7151,10 @@ font-technology Variable ცვლადი
@msg a guide has no curvature circle დამხმარე ხაზს სიმრუდის წრე არ აქვს
@msg the circle that matches the path there would reach past the canvas წრეწირი, რომელიც იქ ტრაექტორიას შეესაბამება, ტილოს გასცდებოდა
@msg no circle passes through these points: two are the same or all three lie on one line ამ წერტილებზე წრეწირი არ გადის: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს
@msg `at` must be "start" or "end" `at` უნდა იყოს "start" ან "end"
@msg give exactly one of `through` and `toward` მიუთითეთ ზუსტად ერთი: `through` ან `toward`
@msg no arc fits these points: two are the same or all three lie on one line ამ წერტილებს რკალი არ ერგება: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს
@msg give `at` only with `toward` `at` მიუთითეთ მხოლოდ `toward`-თან ერთად
@msg no app to open files here აქ ფაილების გასახსნელი აპი არ არის
@msg no artboard სამუშაო დაფა არ არის
@msg no artboard {i} (0-based; the document has {_1}) სამუშაო დაფა {i} არ არსებობს (0-დან ითვლება; დოკუმენტს აქვს {_1})
@@ -8766,6 +8781,8 @@ liquify-list-end {0}, {1} {0} და {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` უნდა იყოს grayscale, rgb, hsb, cmyk ან websafe
@msg `view` must be wheel or box `view` უნდა იყოს wheel ან box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue
@msg `sliders` must be none, oklch or hsl `sliders` უნდა იყოს none, oklch ან hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება
@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს
# Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch.
Intertwine გადახლართვა
@@ -11028,6 +11045,16 @@ font-script Japanese იაპონური
Blossom Chain ყვავილების ჯაჭვი
Pennant Garland ალმების გირლანდა
Lantern String ფარნების ჯაჭვი
Orbit Lines ორბიტული ხაზები
Petal Garland ფურცლების გირლანდა
Lattice Braid ბადის ნაწნავი
Facet Sweep წახნაგოვანი მონასმი
Artistic Brushes მხატვრული ფუნჯები
Paint საღებავი
Flat Sweep ბრტყელი მოსმა
Dry Drag მშრალი მოსმა
Loaded Stroke სქელი მონასმი
Fan Sweep მარაოსებრი მოსმა
Engraving გრავიურა
Fine Hatching წვრილი შტრიხები
Dense Hatching მჭიდრო შტრიხები
Can't render this file because it is too large.
+27
View File
@@ -839,6 +839,8 @@ digits Malayalam 말라얄람어
Contextual Task Bar 상황별 작업 표시줄
Pin Bar Position 표시줄 위치 고정
Reset Bar Position 표시줄 위치 재설정
Bar Actions 표시줄 동작
Reset Bar Actions 표시줄 동작 재설정
Resize 크기 조절
Tools 도구
Toolbars 도구 모음
@@ -1226,6 +1228,10 @@ antiAlias Sharp 날카롭게
@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 모두에 적용(누락 {n}개 더 있음)
Arc 호
Arc Tool 호 도구
Three-Point Arc Tool 3점 호 도구
Three-Point Arc 3점 호
Arc too large 호가 너무 큽니다
Third Point Sets Direction 세 번째 점으로 방향 지정
Area / Path Type 영역/패스 문자
Area Graph Tool 영역 그래프 도구
Area Type Tool 영역 문자 도구
@@ -4402,6 +4408,11 @@ file-filter Templates 템플릿
Keep the pasted color as a new swatch with a numbered name. 붙여넣은 색상을 번호가 붙은 이름의 새 견본으로 보관합니다.
Keep: 유지:
Lab Lab
OKLCH Sliders OKLCH 슬라이더
HSL Sliders HSL 슬라이더
Chroma 크로마
The largest chroma sRGB holds at this lightness and hue 이 명도와 색조에서 sRGB가 담을 수 있는 최대 크로마
OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다
Lab Values Lab 값
Large List View 큰 목록 보기
Large Thumbnail View 큰 축소판 보기
@@ -5093,6 +5104,10 @@ variable-list-end {0}, {1} {0} 및 {1}
@msg a guide has no curvature circle 안내선에는 곡률원이 없습니다
@msg the circle that matches the path there would reach past the canvas 그 위치에서 패스에 맞는 원이 캔버스를 벗어납니다
@msg no circle passes through these points: two are the same or all three lie on one line 이 점들을 지나는 원이 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다
@msg `at` must be "start" or "end" `at`은(는) "start" 또는 "end"여야 합니다
@msg give exactly one of `through` and `toward` `through`와 `toward` 중 정확히 하나만 지정하세요
@msg no arc fits these points: two are the same or all three lie on one line 이 점들에 맞는 호가 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다
@msg give `at` only with `toward` `at`은(는) `toward`와 함께만 지정하세요
@msg select at least two objects 개체를 두 개 이상 선택하세요
@msg exit isolation mode first 먼저 격리 모드를 종료하세요
@msg no saved presets 저장된 프리셋이 없습니다
@@ -5561,6 +5576,8 @@ variable-list-end {0}, {1} {0} 및 {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`은(는) grayscale, rgb, hsb, cmyk, websafe 중 하나여야 합니다
@msg `view` must be wheel or box `view`은(는) wheel, box 중 하나여야 합니다
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다
@msg `sliders` must be none, oklch or hsl `sliders`는 none, oklch 또는 hsl이어야 합니다
@msg OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다
@msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다
@msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다
@msg `select` must be true or false `select`은(는) true 또는 false여야 합니다
@@ -10380,6 +10397,16 @@ breakText Glyphs 글리프
Blossom Chain 꽃사슬
Pennant Garland 깃발 장식
Lantern String 등불 줄
Orbit Lines 궤도 선
Petal Garland 꽃잎 화환
Lattice Braid 격자 땋기
Facet Sweep 면 분할 붓질
Artistic Brushes 예술 브러시
Paint 페인트
Flat Sweep 평평한 붓질
Dry Drag 마른 붓질
Loaded Stroke 두터운 붓질
Fan Sweep 부채꼴 붓질
Engraving 판화
Fine Hatching 가는 해칭
Dense Hatching 촘촘한 해칭
Can't render this file because it is too large.
+27
View File
@@ -1376,6 +1376,8 @@ liquify-list-end {0}, {1} {0} en {1}
Contextual Task Bar Contextuele taakbalk
Pin Bar Position Balkpositie vastzetten
Reset Bar Position Balkpositie herstellen
Bar Actions Balkacties
Reset Bar Actions Balkacties herstellen
Tools Gereedschappen
Toolbars Werkbalken
Advanced Geavanceerd
@@ -2053,6 +2055,10 @@ lighting Light Licht
Add Anchor Point Tool Ankerpunt toevoegen
Anchor Point Tool Ankerpunt-gereedschap
Arc Tool Boog-gereedschap
Three-Point Arc Tool Driepuntsboog-gereedschap
Three-Point Arc Driepuntsboog
Arc too large Boog te groot
Third Point Sets Direction Derde punt geeft de richting aan
Area Graph Tool Vlakdiagram-gereedschap
Area Type Tool Vlaktype-gereedschap
Artboard Tool Tekengebied-gereedschap
@@ -4970,6 +4976,11 @@ axis Both Beide
Image Afbeelding
Ink Inkt
Lab Lab
OKLCH Sliders OKLCH-schuifregelaars
HSL Sliders HSL-schuifregelaars
Chroma Chroma
The largest chroma sRGB holds at this lightness and hue De grootste chroma die sRGB bij deze helderheid en tint bevat
OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte
Medium Gemiddeld
Name Naam
None Geen
@@ -5757,6 +5768,10 @@ imageTrace Outline Contour
@msg a guide has no curvature circle een hulplijn heeft geen krommingscirkel
@msg the circle that matches the path there would reach past the canvas de cirkel die daar bij het pad past, zou voorbij het canvas reiken
@msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn
@msg `at` must be "start" or "end" `at` moet "start" of "end" zijn
@msg give exactly one of `through` and `toward` geef precies één van `through` en `toward`
@msg no arc fits these points: two are the same or all three lie on one line er past geen boog bij deze punten: twee zijn gelijk of alle drie liggen op één lijn
@msg give `at` only with `toward` geef `at` alleen samen met `toward`
@msg no app to open files here hier is geen app om bestanden mee te openen
@msg no artboard geen tekengebied
@msg no artboard {i} (0-based; the document has {_1}) geen tekengebied {i} (vanaf 0; het document heeft er {_1})
@@ -8882,6 +8897,8 @@ mark-style Japanese Japans
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` moet grayscale, rgb, hsb, cmyk of websafe zijn
@msg `view` must be wheel or box `view` moet wheel of box zijn
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn
@msg `sliders` must be none, oklch or hsl `sliders` moet none, oklch of hsl zijn
@msg OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte
@msg the Color Picker is not open de kleurenkiezer is niet open
@msg the screen color sampler is already open de schermkleurkiezer is al open
@msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer
@@ -10781,6 +10798,16 @@ breakText Glyphs Glyphs
Blossom Chain Bloemenketting
Pennant Garland Vlaggetjesslinger
Lantern String Lantaarnslinger
Orbit Lines Baanlijnen
Petal Garland Bloemblaadjesslinger
Lattice Braid Rastervlecht
Facet Sweep Gefacetteerde streek
Artistic Brushes Artistieke penselen
Paint Verf
Flat Sweep Vlakke streek
Dry Drag Droge sleep
Loaded Stroke Dikke verfstreek
Fan Sweep Waaierstreek
Engraving Gravure
Fine Hatching Fijne arcering
Dense Hatching Dichte arcering
Can't render this file because it is too large.
+27
View File
@@ -758,6 +758,8 @@
Contextual Task Bar Kontekstowy pasek zadań
Pin Bar Position Przypnij położenie paska
Reset Bar Position Resetuj położenie paska
Bar Actions Akcje paska
Reset Bar Actions Resetuj akcje paska
Resize Zmień rozmiar
Tools Narzędzia
Toolbars Paski narzędzi
@@ -1457,6 +1459,10 @@ lighting Light Światło
Add Anchor Point Tool Narzędzie Dodaj punkt kontrolny
Anchor Point Tool Narzędzie Punkt kontrolny
Arc Tool Narzędzie Łuk
Three-Point Arc Tool Narzędzie Łuk przez trzy punkty
Three-Point Arc Łuk przez trzy punkty
Arc too large Łuk jest za duży
Third Point Sets Direction Trzeci punkt wyznacza kierunek
Area Graph Tool Narzędzie Wykres warstwowy
Area Type Tool Narzędzie Tekst akapitowy
Artboard Tool Narzędzie Obszar kompozycji
@@ -4497,6 +4503,11 @@ axis Both Obie
Image Obraz
Ink Farba
Lab Lab
OKLCH Sliders Suwaki OKLCH
HSL Sliders Suwaki HSL
Chroma Chroma
The largest chroma sRGB holds at this lightness and hue Największa chroma, jaką sRGB mieści przy tej jasności i barwie
OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB
Medium Średni
Name Nazwa
None Brak
@@ -5309,6 +5320,8 @@ liquify-list-end {0}, {1} {0} i {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musi mieć wartość grayscale, rgb, hsb, cmyk lub websafe
@msg `view` must be wheel or box `view` musi mieć wartość wheel lub box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue
@msg `sliders` must be none, oklch or hsl `sliders` musi mieć wartość none, oklch lub hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB
@msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y]
@msg `{name}` has no options `{name}` nie ma opcji
@msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę
@@ -5502,6 +5515,10 @@ liquify-list-end {0}, {1} {0} i {1}
@msg a guide has no curvature circle linia pomocnicza nie ma okręgu krzywizny
@msg the circle that matches the path there would reach past the canvas okrąg pasujący w tym miejscu do ścieżki wykroczyłby poza płótno
@msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej
@msg `at` must be "start" or "end" `at` musi mieć wartość "start" lub "end"
@msg give exactly one of `through` and `toward` podaj dokładnie jeden z parametrów `through` i `toward`
@msg no arc fits these points: two are the same or all three lie on one line żaden łuk nie pasuje do tych punktów: dwa są takie same albo wszystkie trzy leżą na jednej prostej
@msg give `at` only with `toward` podaj `at` tylko razem z `toward`
@msg no app to open files here brak aplikacji do otwierania plików
@msg no artboard brak obszaru kompozycji
@msg no artboard {i} (0-based; the document has {_1}) brak obszaru kompozycji {i} (numeracja od 0; dokument ma {_1})
@@ -10605,6 +10622,16 @@ breakText Glyphs Glify
Blossom Chain Łańcuch kwiatów
Pennant Garland Girlanda proporczyków
Lantern String Łańcuch lampionów
Orbit Lines Linie orbitalne
Petal Garland Girlanda płatków
Lattice Braid Plecionka kratowa
Facet Sweep Fasetowane pociągnięcie
Artistic Brushes Pędzle artystyczne
Paint Farba
Flat Sweep Płaskie pociągnięcie
Dry Drag Suche przeciągnięcie
Loaded Stroke Grube pociągnięcie
Fan Sweep Wachlarzowy ślad
Engraving Grawerowanie
Fine Hatching Drobne kreskowanie
Dense Hatching Gęste kreskowanie
Can't render this file because it is too large.
+27
View File
@@ -233,6 +233,10 @@ antiAlias Sharp Nítido
Arc Arco
Arc Lower… Arco Inferior…
Arc Tool Ferramenta Arco
Three-Point Arc Tool Ferramenta Arco por três pontos
Three-Point Arc Arco por três pontos
Arc too large Arco grande demais
Third Point Sets Direction O terceiro ponto indica a direção
Arc Upper… Arco Superior…
Arch… Abóbada…
Arc… Arco…
@@ -597,6 +601,8 @@ antiAlias Sharp Nítido
Contextual Task Bar Barra de Tarefas Contextual
Pin Bar Position Fixar Posição da Barra
Reset Bar Position Redefinir Posição da Barra
Bar Actions Ações da Barra
Reset Bar Actions Redefinir Ações da Barra
Resize Redimensionar
Control Controle
Convert Converter
@@ -4647,6 +4653,10 @@ axis Both Ambos
@msg a guide has no curvature circle uma guia não tem círculo de curvatura
@msg the circle that matches the path there would reach past the canvas o círculo que corresponde ao caminho nesse ponto ultrapassaria a tela
@msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta
@msg `at` must be "start" or "end" `at` deve ser "start" ou "end"
@msg give exactly one of `through` and `toward` informe exatamente um entre `through` e `toward`
@msg no arc fits these points: two are the same or all three lie on one line nenhum arco se ajusta a esses pontos: dois são iguais ou os três estão na mesma reta
@msg give `at` only with `toward` informe `at` somente com `toward`
@msg no app to open files here nenhum aplicativo para abrir arquivos aqui
@msg no artboard nenhuma prancheta
@msg no artboard {i} (0-based; the document has {_1}) nenhuma prancheta {i} (base 0; o documento tem {_1})
@@ -5710,6 +5720,11 @@ variable-list-end {0}, {1} {0} e {1}
@plural agrees with {n} default shortcut|agrees with {n} default shortcuts coincide com {n} atalho padrão|coincide com {n} atalhos padrão
@plural {n} part of the file wasn't read|{n} parts of the file weren't read {n} parte do arquivo não foi lida|{n} partes do arquivo não foram lidas
Lab Lab
OKLCH Sliders Controles Deslizantes OKLCH
HSL Sliders Controles Deslizantes HSL
Chroma Croma
The largest chroma sRGB holds at this lightness and hue O maior croma que o sRGB comporta nesta luminosidade e neste tom
OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB
Lab Values Valores Lab
Large List View Exibição em Lista Grande
Large Thumbnail View Exibição em Miniaturas Grandes
@@ -6921,6 +6936,8 @@ mark-style Japanese Japonesas
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe
@msg `view` must be wheel or box `view` deve ser wheel ou box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue
@msg `sliders` must be none, oklch or hsl `sliders` deve ser none, oklch ou hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB
@msg the image can't be read as a texture a imagem não pode ser lida como textura
# User Interface › Accent Color
@@ -10814,6 +10831,16 @@ swatch Yellow Green Verde-amarelado
Blossom Chain Corrente de flores
Pennant Garland Guirlanda de bandeirolas
Lantern String Cordão de lanternas
Orbit Lines Linhas orbitais
Petal Garland Guirlanda de pétalas
Lattice Braid Trança em grade
Facet Sweep Traço facetado
Artistic Brushes Pincéis artísticos
Paint Pintura
Flat Sweep Pincelada plana
Dry Drag Arrasto seco
Loaded Stroke Traço carregado
Fan Sweep Pincelada em leque
Engraving Gravura
Fine Hatching Hachuras finas
Dense Hatching Hachuras densas
Can't render this file because it is too large.
+27
View File
@@ -236,6 +236,10 @@ font-technology Variable Вариативные
Arc Дуга
Arc Lower… Дуга снизу…
Arc Tool Инструмент «Дуга»
Three-Point Arc Tool Инструмент «Дуга по трём точкам»
Three-Point Arc Дуга по трём точкам
Arc too large Дуга слишком велика
Third Point Sets Direction Третья точка задаёт направление
Arc Upper… Дуга сверху…
Arch… Арка…
Arc… Дуга…
@@ -650,6 +654,8 @@ font-technology Variable Вариативные
Contextual Task Bar Контекстная панель задач
Pin Bar Position Закрепить положение панели
Reset Bar Position Сбросить положение панели
Bar Actions Действия панели
Reset Bar Actions Сбросить действия панели
Resize Изменить размер
Contrast Контраст
Control Control
@@ -2060,6 +2066,11 @@ file-filter Templates Шаблоны
Knife Нож
Knockout Group Группа с вырезанием
Lab Lab
OKLCH Sliders Ползунки OKLCH
HSL Sliders Ползунки HSL
Chroma Хрома
The largest chroma sRGB holds at this lightness and hue Наибольшая хрома, которую вмещает sRGB при этой светлоте и оттенке
OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB
Lab Spot Colors: Плашечные цвета Lab:
Lab Values Значения Lab
Landscape Альбомная
@@ -5202,6 +5213,8 @@ liquify-list-end {0}, {1} {0} и {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` должно быть grayscale, rgb, hsb, cmyk или websafe
@msg `view` must be wheel or box `view` должно быть wheel или box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue
@msg `sliders` must be none, oklch or hsl `sliders` должен быть none, oklch или hsl
@msg OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB
@msg `{k}` must be [x, y] `{k}` должно быть [x, y]
@msg `{name}` has no options `{name}` не имеет параметров
@msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя
@@ -5395,6 +5408,10 @@ liquify-list-end {0}, {1} {0} и {1}
@msg a guide has no curvature circle у направляющей нет круга кривизны
@msg the circle that matches the path there would reach past the canvas окружность, соответствующая контуру в этом месте, вышла бы за пределы холста
@msg no circle passes through these points: two are the same or all three lie on one line через эти точки не проходит ни одна окружность: две точки совпадают или все три лежат на одной прямой
@msg `at` must be "start" or "end" `at` должно быть "start" или "end"
@msg give exactly one of `through` and `toward` укажите ровно один из параметров `through` и `toward`
@msg no arc fits these points: two are the same or all three lie on one line ни одна дуга не подходит к этим точкам: две точки совпадают или все три лежат на одной прямой
@msg give `at` only with `toward` указывайте `at` только вместе с `toward`
@msg no app to open files here здесь нет приложения для открытия файлов
@msg no artboard нет монтажной области
@msg no artboard {i} (0-based; the document has {_1}) нет монтажной области {i} (счёт с 0; в документе {_1})
@@ -10798,6 +10815,16 @@ shape Open Открытый
Blossom Chain Цветочная цепочка
Pennant Garland Гирлянда флажков
Lantern String Цепочка фонариков
Orbit Lines Орбитальные линии
Petal Garland Гирлянда лепестков
Lattice Braid Решётчатое плетение
Facet Sweep Гранёный мазок
Artistic Brushes Художественные кисти
Paint Краска
Flat Sweep Плоский мазок
Dry Drag Сухой протяг
Loaded Stroke Густой мазок
Fan Sweep Веерный мазок
Engraving Гравировка
Fine Hatching Тонкая штриховка
Dense Hatching Плотная штриховка
Can't render this file because it is too large.
+27
View File
@@ -227,6 +227,10 @@ font-technology Variable Variabla
Arc Båge
Arc Lower… Nedre båge…
Arc Tool Bågverktyg
Three-Point Arc Tool Verktyg för trepunktsbåge
Three-Point Arc Trepunktsbåge
Arc too large Bågen är för stor
Third Point Sets Direction Tredje punkten anger riktningen
Arc Upper… Övre båge…
Arch… Valv…
Arc… Båge…
@@ -635,6 +639,8 @@ font-technology Variable Variabla
Contextual Task Bar Kontextuellt aktivitetsfält
Pin Bar Position Fäst fältets position
Reset Bar Position Återställ fältets position
Bar Actions Fältets åtgärder
Reset Bar Actions Återställ fältets åtgärder
Resize Ändra storlek
Contrast Kontrast
Control Kontroll
@@ -1976,6 +1982,11 @@ font-technology Variable Variabla
Knife Kniv
Knockout Group Utsparningsgrupp
Lab Lab
OKLCH Sliders OKLCH-reglage
HSL Sliders HSL-reglage
Chroma Kroma
The largest chroma sRGB holds at this lightness and hue Den största kroma som sRGB rymmer vid denna ljushet och nyans
OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd
Lab Spot Colors: Lab-dekorfärger:
Lab Values Lab-värden
Landscape Liggande
@@ -5260,6 +5271,10 @@ liquify-list-end {0}, {1} {0} och {1}
@msg a guide has no curvature circle en stödlinje har ingen krökningscirkel
@msg the circle that matches the path there would reach past the canvas cirkeln som matchar banan där skulle nå utanför arbetsytan
@msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje
@msg `at` must be "start" or "end" `at` måste vara "start" eller "end"
@msg give exactly one of `through` and `toward` ange exakt en av `through` och `toward`
@msg no arc fits these points: two are the same or all three lie on one line ingen båge passar de här punkterna: två är samma punkt eller så ligger alla tre på en linje
@msg give `at` only with `toward` ange `at` endast tillsammans med `toward`
@msg no app to open files here det finns ingen app för att öppna filer här
@msg no artboard ingen rityta
@msg no artboard {i} (0-based; the document has {_1}) ingen rityta {i} (räknat från 0; dokumentet har {_1})
@@ -6961,6 +6976,8 @@ theme Appearance Utseende
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe
@msg `view` must be wheel or box `view` måste vara wheel eller box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue
@msg `sliders` must be none, oklch or hsl `sliders` måste vara none, oklch eller hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd
@msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1}
@msg choose a destination folder välj en målmapp
@msg choose a source folder välj en källmapp
@@ -10835,6 +10852,16 @@ digits Hindi Hindi
Blossom Chain Blomkedja
Pennant Garland Vimpelgirlang
Lantern String Lyktgirlang
Orbit Lines Banlinjer
Petal Garland Kronbladsgirlang
Lattice Braid Gallerfläta
Facet Sweep Fasetterat drag
Artistic Brushes Konstnärliga penslar
Paint Färg
Flat Sweep Platt penseldrag
Dry Drag Torrt drag
Loaded Stroke Fylligt penseldrag
Fan Sweep Solfjädersdrag
Engraving Gravyr
Fine Hatching Fin skraffering
Dense Hatching Tät skraffering
Can't render this file because it is too large.
+27
View File
@@ -223,6 +223,10 @@ font-technology Variable Değişken
Arc Yay
Arc Lower… Ark Alt…
Arc Tool Yay Aracı
Three-Point Arc Tool Üç Noktalı Yay Aracı
Three-Point Arc Üç Noktalı Yay
Arc too large Yay çok büyük
Third Point Sets Direction Üçüncü Nokta Yönü Belirler
Arc Upper… Ark Üst…
Arch… Kemer…
Arc… Yay…
@@ -632,6 +636,8 @@ font-technology Variable Değişken
Contextual Task Bar Bağlamsal Görev Çubuğu
Pin Bar Position Pim Çubuğu Konumu
Reset Bar Position Çubuk Konumunu Sıfırla
Bar Actions Çubuk Eylemleri
Reset Bar Actions Çubuk Eylemlerini Sıfırla
Contrast Kontrast
Control Kontrol
Convert Dönüştür
@@ -1855,6 +1861,11 @@ font-technology Variable Değişken
Knife Bıçak
Knockout Group Nakavt Grubu
Lab Laboratuvar
OKLCH Sliders OKLCH Kaydırıcıları
HSL Sliders HSL Kaydırıcıları
Chroma Kroma
The largest chroma sRGB holds at this lightness and hue sRGB'nin bu açıklık ve renk tonunda alabileceği en yüksek kroma
OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir
Lab Spot Colors: Laboratuvar Spot Renkleri:
Lab Values Laboratuvar Değerleri
Landscape Manzara
@@ -4907,6 +4918,8 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` grayscale, rgb, hsb, cmyk veya websafe olmalıdır
@msg `view` must be wheel or box `view` wheel veya box olmalıdır
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır
@msg `sliders` must be none, oklch or hsl `sliders` none, oklch veya hsl olmalıdır
@msg OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir
@msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır
@msg `{name}` has no options `{name}`nin seçeneği yok
@msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç
@@ -5085,6 +5098,10 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg a guide has no curvature circle bir kılavuzun eğrilik çemberi yoktur
@msg the circle that matches the path there would reach past the canvas yolla orada eşleşen çember tuvalin dışına taşardı
@msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde
@msg `at` must be "start" or "end" `at` "start" veya "end" olmalıdır
@msg give exactly one of `through` and `toward` `through` ve `toward` değerlerinden tam olarak birini verin
@msg no arc fits these points: two are the same or all three lie on one line bu noktalara uyan bir yay yok: ikisi aynı ya da üçü de aynı doğru üzerinde
@msg give `at` only with `toward` `at` değerini yalnızca `toward` ile birlikte verin
@msg no app to open files here burada dosyaları açacak uygulama yok
@msg no artboard çalışma yüzeyi yok
@msg no artboard {i} (0-based; the document has {_1}) çalışma yüzeyi yok {i} (0 tabanlı; belgede {_1} var)
@@ -10700,6 +10717,16 @@ breakText Glyphs Glifler
Blossom Chain Çiçek zinciri
Pennant Garland Bayrak süsü
Lantern String Fener dizisi
Orbit Lines Yörünge Çizgileri
Petal Garland Taç Yaprağı Çelengi
Lattice Braid Kafes Örgü
Facet Sweep Fasetli Darbe
Artistic Brushes Sanatsal Fırçalar
Paint Boya
Flat Sweep Düz fırça izi
Dry Drag Kuru sürükleme
Loaded Stroke Yoğun fırça izi
Fan Sweep Yelpaze izi
Engraving Gravür
Fine Hatching İnce tarama
Dense Hatching Yoğun tarama
Can't render this file because it is too large.
+27
View File
@@ -234,6 +234,10 @@ font-technology Variable Варіативні
Arc Дуга
Arc Lower… Дуга знизу…
Arc Tool Інструмент «Дуга»
Three-Point Arc Tool Інструмент «Дуга за трьома точками»
Three-Point Arc Дуга за трьома точками
Arc too large Дуга завелика
Third Point Sets Direction Третя точка задає напрямок
Arc Upper… Дуга зверху…
Arch… Арка…
Arc… Дуга…
@@ -648,6 +652,8 @@ font-technology Variable Варіативні
Contextual Task Bar Контекстна панель завдань
Pin Bar Position Закріпити положення панелі
Reset Bar Position Скинути положення панелі
Bar Actions Дії панелі
Reset Bar Actions Скинути дії панелі
Resize Змінити розмір
Contrast Контраст
Control Панель керування
@@ -2068,6 +2074,11 @@ file-filter Templates Шаблони
Knife Ніж
Knockout Group Група з вирізуванням
Lab Lab
OKLCH Sliders Повзунки OKLCH
HSL Sliders Повзунки HSL
Chroma Хрома
The largest chroma sRGB holds at this lightness and hue Найбільша хрома, яку вміщує sRGB за цієї світлоти й відтінку
OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB
Lab Spot Colors: Плашкові кольори Lab:
Lab Values Значення Lab
Landscape Альбомна
@@ -5190,6 +5201,8 @@ liquify-list-end {0}, {1} {0} і {1}
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` має бути grayscale, rgb, hsb, cmyk або websafe
@msg `view` must be wheel or box `view` має бути wheel або box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue
@msg `sliders` must be none, oklch or hsl `sliders` має бути none, oklch або hsl
@msg OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB
@msg `{k}` must be [x, y] `{k}` має бути [x, y]
@msg `{name}` has no options `{name}` не має параметрів
@msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я
@@ -5383,6 +5396,10 @@ liquify-list-end {0}, {1} {0} і {1}
@msg a guide has no curvature circle напрямна не має кола кривини
@msg the circle that matches the path there would reach past the canvas коло, що відповідає контуру в цьому місці, вийшло б за межі полотна
@msg no circle passes through these points: two are the same or all three lie on one line через ці точки не проходить жодне коло: дві точки збігаються або всі три лежать на одній прямій
@msg `at` must be "start" or "end" `at` має бути "start" або "end"
@msg give exactly one of `through` and `toward` вкажіть рівно один із параметрів `through` і `toward`
@msg no arc fits these points: two are the same or all three lie on one line жодна дуга не підходить до цих точок: дві точки збігаються або всі три лежать на одній прямій
@msg give `at` only with `toward` вказуйте `at` лише разом із `toward`
@msg no app to open files here тут немає програми для відкриття файлів
@msg no artboard немає монтажної області
@msg no artboard {i} (0-based; the document has {_1}) немає монтажної області {i} (рахунок з 0; у документі {_1})
@@ -10393,6 +10410,16 @@ breakText Glyphs Гліфи
Blossom Chain Квітковий ланцюжок
Pennant Garland Гірлянда прапорців
Lantern String Ланцюжок ліхтариків
Orbit Lines Орбітальні лінії
Petal Garland Гірлянда пелюсток
Lattice Braid Ґратчасте плетіння
Facet Sweep Гранований мазок
Artistic Brushes Художні пензлі
Paint Фарба
Flat Sweep Плоский мазок
Dry Drag Сухий протяг
Loaded Stroke Густий мазок
Fan Sweep Віяловий мазок
Engraving Гравіювання
Fine Hatching Тонке штрихування
Dense Hatching Щільне штрихування
Can't render this file because it is too large.
+27
View File
@@ -259,6 +259,10 @@ font-technology Variable Biến thiên
Arc Cung
Arc Lower… Cung dưới…
Arc Tool Công cụ Cung
Three-Point Arc Tool Công cụ Cung ba điểm
Three-Point Arc Cung ba điểm
Arc too large Cung quá lớn
Third Point Sets Direction Điểm thứ ba chỉ hướng
Arc Upper… Cung trên…
Arch… Vòm…
Arc… Cung…
@@ -2368,6 +2372,11 @@ digits Hindi Hindi
Knife Dao
Knockout Group Nhóm Knockout
Lab Lab
OKLCH Sliders Thanh trượt OKLCH
HSL Sliders Thanh trượt HSL
Chroma Độ tươi màu
The largest chroma sRGB holds at this lightness and hue Độ tươi màu lớn nhất mà sRGB chứa được ở độ sáng và sắc độ này
OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc
Lab Spot Colors: Màu đặc Lab:
Lab Values Giá trị Lab
Landscape Ngang
@@ -3562,6 +3571,8 @@ mark-style Japanese Kiểu Nhật
Reset all 3D settings to their defaults. Đặt lại tất cả cài đặt 3D về mặc định.
Reset all Revolve settings to their defaults. Đặt lại tất cả cài đặt Revolve về mặc định.
Reset Bar Position Đặt lại vị trí thanh
Bar Actions Thao tác của thanh
Reset Bar Actions Đặt lại thao tác của thanh
Reset Bounding Box Đặt lại hộp bao
Rotate Bounding Box Xoay hộp bao
Rotate Bounding Box… Xoay hộp bao…
@@ -5188,6 +5199,8 @@ theme Appearance Giao diện
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` phải là grayscale, rgb, hsb, cmyk hoặc websafe
@msg `view` must be wheel or box `view` phải là wheel hoặc box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue
@msg `sliders` must be none, oklch or hsl `sliders` phải là none, oklch hoặc hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc
@msg `{k}` must be [x, y] `{k}` phải là [x, y]
@msg `{name}` has no options `{name}` không có tùy chọn
@msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác
@@ -5753,6 +5766,10 @@ liquify-list-end {0}, {1} {0} và {1}
@msg a guide has no curvature circle đường căn không có đường tròn độ cong
@msg the circle that matches the path there would reach past the canvas đường tròn khớp với đường dẫn tại đó sẽ vượt quá giới hạn vùng vẽ
@msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng
@msg `at` must be "start" or "end" `at` phải là "start" hoặc "end"
@msg give exactly one of `through` and `toward` hãy cho đúng một trong hai `through` và `toward`
@msg no arc fits these points: two are the same or all three lie on one line không có cung nào khớp với các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng
@msg give `at` only with `toward` chỉ cho `at` cùng với `toward`
@msg no app to open files here không có ứng dụng để mở tệp ở đây
@msg no artboard không có bảng vẽ
@msg no artboard {i} (0-based; the document has {_1}) không có bảng vẽ {i} (bắt đầu từ 0; tài liệu có {_1})
@@ -8590,6 +8607,16 @@ breakText Glyphs Glyph
Blossom Chain Chuỗi hoa
Pennant Garland Dây cờ tam giác
Lantern String Dây đèn lồng
Orbit Lines Đường quỹ đạo
Petal Garland Vòng hoa cánh
Lattice Braid Bện lưới
Facet Sweep Nét đa diện
Artistic Brushes Cọ nghệ thuật
Paint Sơn
Flat Sweep Nét quét phẳng
Dry Drag Nét kéo khô
Loaded Stroke Nét cọ đậm
Fan Sweep Nét quét hình quạt
Engraving Khắc nét
Fine Hatching Nét gạch mảnh
Dense Hatching Nét gạch dày
Can't render this file because it is too large.
+27
View File
@@ -184,6 +184,10 @@ antiAlias Sharp 锐利
Arc 弧形
Arc Lower… 下弧形…
Arc Tool 弧形工具
Three-Point Arc Tool 三点弧形工具
Three-Point Arc 三点弧形
Arc too large 弧形过大
Third Point Sets Direction 第三点指示方向
Arc Upper… 上弧形…
Arch… 拱形…
Arc… 弧形…
@@ -599,6 +603,8 @@ antiAlias Sharp 锐利
Contextual Task Bar 上下文任务栏
Pin Bar Position 固定任务栏位置
Reset Bar Position 重置任务栏位置
Bar Actions 任务栏操作
Reset Bar Actions 重置任务栏操作
Resize 调整大小
Contrast 对比
Control 控制栏
@@ -1950,6 +1956,11 @@ file-filter Templates 模板
Knife 刻刀
Knockout Group 挖空组
Lab Lab
OKLCH Sliders OKLCH 滑块
HSL Sliders HSL 滑块
Chroma 色度
The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容纳的最大色度
OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间
Lab Spot Colors: Lab 专色:
Lab Values Lab 值
Landscape 横向
@@ -4850,6 +4861,10 @@ imageTrace Outline 轮廓
@msg a guide has no curvature circle 参考线没有曲率圆
@msg the circle that matches the path there would reach past the canvas 在该处与路径曲率相符的圆会超出画布
@msg no circle passes through these points: two are the same or all three lie on one line 没有圆经过这些点:有两点相同,或三点共线
@msg `at` must be "start" or "end" `at` 必须是 "start" 或 "end"
@msg give exactly one of `through` and `toward` `through` 和 `toward` 必须且只能指定一个
@msg no arc fits these points: two are the same or all three lie on one line 没有弧形符合这些点:有两点相同,或三点共线
@msg give `at` only with `toward` `at` 只能与 `toward` 一起指定
@msg select at least two objects 请至少选择两个对象
@msg exit isolation mode first 请先退出隔离模式
@msg no saved presets 没有已保存的预设
@@ -5301,6 +5316,8 @@ imageTrace Outline 轮廓
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必须是 grayscale、rgb、hsb、cmyk 或 websafe
@msg `view` must be wheel or box `view` 必须是 wheel 或 box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue
@msg `sliders` must be none, oklch or hsl `sliders` 必须是 none、oklch 或 hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间
@msg `{key}` must be true or false `{key}` 必须是 true 或 false
@msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true
@msg `select` must be true or false `select` 必须是 true 或 false
@@ -10585,6 +10602,16 @@ breakText Glyphs 字形
Blossom Chain 花链
Pennant Garland 旗帜花环
Lantern String 灯笼串
Orbit Lines 轨道线
Petal Garland 花瓣花环
Lattice Braid 格纹编织
Facet Sweep 切面笔触
Artistic Brushes 艺术画笔
Paint 绘画
Flat Sweep 平刷
Dry Drag 干拖
Loaded Stroke 厚涂笔触
Fan Sweep 扇形笔触
Engraving 雕刻
Fine Hatching 细线排线
Dense Hatching 密集排线
Can't render this file because it is too large.
+27
View File
@@ -198,6 +198,10 @@ font-technology Variable 可變
Arc 弧形
Arc Lower… 下弧形…
Arc Tool 弧形工具
Three-Point Arc Tool 三點弧形工具
Three-Point Arc 三點弧形
Arc too large 弧形過大
Third Point Sets Direction 第三點指示方向
Arc Upper… 上弧形…
Arch… 拱形…
Arc… 弧形…
@@ -616,6 +620,8 @@ font-technology Variable 可變
Contextual Task Bar 快捷工作列
Pin Bar Position 釘選工作列位置
Reset Bar Position 重設工作列位置
Bar Actions 工作列動作
Reset Bar Actions 重設工作列動作
Resize 調整大小
Contrast 對比
Control 控制
@@ -2221,6 +2227,10 @@ file-filter Templates 範本
@msg a guide has no curvature circle 參考線沒有曲率圓
@msg the circle that matches the path there would reach past the canvas 在該處與路徑曲率相符的圓會超出畫布
@msg no circle passes through these points: two are the same or all three lie on one line 沒有圓通過這些點:有兩點相同,或三點共線
@msg `at` must be "start" or "end" `at` 必須是 "start" 或 "end"
@msg give exactly one of `through` and `toward` `through` 與 `toward` 必須且只能指定一個
@msg no arc fits these points: two are the same or all three lie on one line 沒有弧形符合這些點:有兩點相同,或三點共線
@msg give `at` only with `toward` `at` 只能與 `toward` 一起指定
@msg select at least two objects 請選取至少兩個物件
@msg exit isolation mode first 請先結束隔離模式
@msg no saved presets 沒有已儲存的預設集
@@ -2675,6 +2685,8 @@ file-filter Templates 範本
@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必須是 grayscale、rgb、hsb、cmyk 或 websafe
@msg `view` must be wheel or box `view` 必須是 wheel 或 box
@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue
@msg `sliders` must be none, oklch or hsl `sliders` 必須是 none、oklch 或 hsl
@msg OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間
@msg `{key}` must be true or false `{key}` 必須是 true 或 false
@msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true
@msg `select` must be true or false `select` 必須是 true 或 false
@@ -3331,6 +3343,11 @@ liquify-list-end {0}, {1} {0}和{1}
Knife 美工刀
Knockout Group 去底群組
Lab Lab
OKLCH Sliders OKLCH 滑桿
HSL Sliders HSL 滑桿
Chroma 色度
The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容納的最大色度
OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間
Lab Spot Colors: Lab 特別色:
Lab Values Lab 值
Landscape 橫向
@@ -10400,6 +10417,16 @@ breakText Glyphs 字符
Blossom Chain 花鏈
Pennant Garland 旗幟花環
Lantern String 燈籠串
Orbit Lines 軌道線
Petal Garland 花瓣花環
Lattice Braid 格紋編織
Facet Sweep 切面筆觸
Artistic Brushes 藝術筆刷
Paint 繪畫
Flat Sweep 平刷
Dry Drag 乾拖
Loaded Stroke 厚塗筆觸
Fan Sweep 扇形筆觸
Engraving 雕刻
Fine Hatching 細線排線
Dense Hatching 密集排線
Can't render this file because it is too large.
+1
View File
@@ -45,6 +45,7 @@ pub static ICONS: &[(&str, &[u8])] = &[
("dc-anchor-smooth", include_bytes!("../../../assets/icons/dc-anchor-smooth.svg")),
("dc-appearance", include_bytes!("../../../assets/icons/dc-appearance.svg")),
("dc-arc", include_bytes!("../../../assets/icons/dc-arc.svg")),
("dc-arc-three-point", include_bytes!("../../../assets/icons/dc-arc-three-point.svg")),
("dc-arrow-down", include_bytes!("../../../assets/icons/dc-arrow-down.svg")),
("dc-arrow-extend", include_bytes!("../../../assets/icons/dc-arrow-extend.svg")),
("dc-arrow-tip", include_bytes!("../../../assets/icons/dc-arrow-tip.svg")),
+1
View File
@@ -39,6 +39,7 @@ pub fn tool_icon(name: &str) -> &'static str {
"tool-touch-type" => "dc-touch-type",
"tool-line" => "dc-line",
"tool-arc" => "dc-arc",
"tool-three-point-arc" => "dc-arc-three-point",
"tool-spiral" => "tornado",
"tool-rect-grid" => "dc-rect-grid",
"tool-polar-grid" => "dc-polar-grid",
+20
View File
@@ -652,6 +652,26 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
app.ui.task_bar_place = Default::default();
Ok(Value::Null)
}
// More Options › Bar Actions: one of the bar's actions or chips on or off.
"window.taskBar.actions" => match (s("action").filter(|a| crate::canvas::is_task_bar_action(a)), opt_bool(p, "visible")) {
(None, _) => {
let ids = crate::canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(crate::canvas::TASK_BAR_CHIPS);
Err(format!("`action` must be one of {}", ids.collect::<Vec<_>>().join(", ")))
}
(_, Err(e)) => Err(e),
(Some(action), Ok(visible)) => {
let hidden = &mut app.ui.task_bar_hidden_actions;
let visible = visible.unwrap_or_else(|| hidden.contains(&action));
if visible {
hidden.remove(&action);
} else {
hidden.insert(action.clone());
}
Ok(json!({ "action": action, "visible": visible }))
}
},
// More Options › Reset Bar Actions: every action and chip shows again.
"window.taskBar.resetActions" => Ok(json!(std::mem::take(&mut app.ui.task_bar_hidden_actions))),
"window.dock" => {
let ui = &mut app.ui;
// The bars the last Tab hid show again, unless the toolbar or the Control bar was shown
+4
View File
@@ -95,6 +95,10 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option<bool> {
"window.taskBar" => app.ui.task_bar,
"window.pathfinder.compoundShapes" => app.ui.shape_modes_compound,
"window.taskBar.pin" => app.ui.task_bar_place.pinned,
"window.taskBar.actions" => p
.get("action")
.and_then(Value::as_str)
.is_some_and(|a| crate::canvas::is_task_bar_action(a) && !app.ui.task_bar_hidden_actions.contains(a)),
"window.learn" => crate::panels::learn::visible(&app.ui),
"window.panel" => {
let panel = p.get("panel").and_then(Value::as_str).unwrap_or("");
+13 -1
View File
@@ -688,6 +688,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state",
),
("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"),
(
"window.taskBar.actions",
"Bar Actions",
"",
"{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}",
),
(
"window.taskBar.resetActions",
"Reset Bar Actions",
"",
"{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again",
),
(
"window.dock",
"Panels",
@@ -1562,7 +1574,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, harmony, harmonyRule, vision}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, harmony, harmonyRule, vision}",
),
(
"ui.savePdfDialog",
+411 -19
View File
@@ -22,15 +22,25 @@
//! Setup uses, and for achromatopsia as the gray with the color's CIE L*. The chips only show the
//! simulation.
//!
//! The view, the channel, Show Harmony, Harmony Rule and Show Color Vision Preview are kept with
//! the preferences (`ui.colorWheel`).
//! Panel menu › OKLCH Sliders shows L, C and H rows under the wheel or the box that edit the color
//! by OKLCH lightness, chroma and hue (CSS Color 4:
//! <https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch>), while the active document's RGB
//! space ([`cms::active`]: the profile assigned to the document, else the working RGB space of the
//! color settings) is sRGB. Panel menu › HSL Sliders shows H, S and L rows in their place that edit the color by the
//! hue, saturation and lightness of CSS Color 4's HSL
//! (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>). The choice is kept with the
//! preferences too.
//!
//! The view, the channel, the slider rows, Show Harmony, Harmony Rule and Show Color Vision
//! Preview are kept with the preferences (`ui.colorWheel`).
use egui::{Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, vec2};
use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::cms::{self, Cms, ProofSetup, ProofTarget};
use vectorcraft_color::harmony::Harmony;
use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb};
use vectorcraft_color::oklab::{self, CHROMA_FULL};
use vectorcraft_color::{Color, Paint, hsb_to_rgb, hsl_to_rgb, rgb_to_hsb, rgb_to_hsl};
use vectorcraft_doc::{ColorMode, NodeId};
use super::color::{Target, apply, wheel_target};
@@ -82,6 +92,8 @@ pub struct Settings {
pub view: View,
#[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")]
pub channel: Channel,
#[serde(deserialize_with = "deserialize_sliders")]
pub sliders: Sliders,
/// Show Harmony: markers on the ring for the other colors of `harmony_rule`.
#[serde(deserialize_with = "deserialize_flag")]
pub harmony: bool,
@@ -94,9 +106,50 @@ pub struct Settings {
pub vision: bool,
}
/// The slider rows under the wheel or the box (panel menu, `ui.colorWheel {sliders}`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Sliders {
#[default]
None,
/// OKLCH Sliders: lightness, chroma and hue.
Oklch,
/// HSL Sliders: hue, saturation and lightness.
Hsl,
}
impl Sliders {
pub const ALL: [Sliders; 3] = [Sliders::None, Sliders::Oklch, Sliders::Hsl];
/// The id `ui.colorWheel` and the preferences use.
pub fn id(self) -> &'static str {
match self {
Sliders::None => "none",
Sliders::Oklch => "oklch",
Sliders::Hsl => "hsl",
}
}
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|v| v.id() == s)
}
}
fn deserialize_sliders<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Sliders, D::Error> {
let v = <Value as Deserialize>::deserialize(d)?;
Ok(v.as_str().and_then(Sliders::parse).unwrap_or_default())
}
impl Default for Settings {
fn default() -> Self {
Self { view: View::default(), channel: Channel::default(), harmony: false, harmony_rule: Harmony::Complementary, vision: false }
Self {
view: View::default(),
channel: Channel::default(),
sliders: Sliders::default(),
harmony: false,
harmony_rule: Harmony::Complementary,
vision: false,
}
}
}
@@ -146,12 +199,22 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Se
Ok(serde_json::from_value(v).unwrap_or_default())
}
/// `ui.colorWheel {view?, channel?, harmony?, harmonyRule?, vision?}`: show the wheel or the box,
/// pick the box's channel, show the colors of a harmony rule on the wheel, and show or hide the
/// color vision row. Keys left out or null keep their values; params that are not an object,
/// another key or a value off the list are an error and change nothing. → the settings.
/// `ui.colorWheel {view?, channel?, sliders?, harmony?, harmonyRule?, vision?}`: show the wheel or
/// the box, pick the box's channel, show OKLCH Sliders, HSL Sliders or neither, show the colors of
/// a harmony rule on the wheel, and show or hide the color vision row. Keys left out or null keep
/// their values; params that are not an object, another key or a value off the list are an error
/// and change nothing.
/// `sliders: "oklch"` is an error while the active document's RGB space (its assigned profile,
/// else the working RGB space) is not sRGB. → the settings.
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
const KEYS: [&str; 5] = ["view", "channel", "harmony", "harmonyRule", "vision"];
set(&mut app.ui.color_wheel, p, &cms::active())?;
Ok(json!(app.ui.color_wheel))
}
/// Set the keys of `ui.colorWheel` params `p` in `settings`, with the color settings `cms`; on an
/// error `settings` stay as they were.
pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), String> {
const KEYS: [&str; 6] = ["view", "channel", "sliders", "harmony", "harmonyRule", "vision"];
match p {
Value::Null => {}
Value::Object(o) => {
@@ -161,7 +224,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri
}
got => return Err(format!("the params must be an object, not {got}")),
}
let mut set = app.ui.color_wheel.clone();
let mut set = settings.clone();
match p.get("view") {
None | Some(Value::Null) => {}
Some(v) => set.view = v.as_str().and_then(View::parse).ok_or("`view` must be wheel or box")?,
@@ -170,6 +233,16 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri
None | Some(Value::Null) => {}
Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?,
}
match p.get("sliders") {
None | Some(Value::Null) => {}
Some(v) => {
let sliders = v.as_str().and_then(Sliders::parse).ok_or("`sliders` must be none, oklch or hsl")?;
if sliders == Sliders::Oklch && !cms.rgb_is_srgb() {
return Err(OKLCH_NEEDS_SRGB.to_string());
}
set.sliders = sliders;
}
}
let key = "harmony";
match p.get(key) {
None | Some(Value::Null) => {}
@@ -188,12 +261,13 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri
if let Some(on) = crate::menus::opt_bool(p, "vision")? {
set.vision = on;
}
app.ui.color_wheel = set;
Ok(json!(app.ui.color_wheel))
*settings = set;
Ok(())
}
/// The panel menu: Wheel View and Box View, and Box Channel while the box shows; Show Harmony
/// and Harmony Rule while the wheel shows; and Show Color Vision Preview.
/// The panel menu: Wheel View and Box View, and Box Channel while the box shows; HSL Sliders and
/// OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; and Show Color Vision
/// Preview.
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let set = app.ui.color_wheel.clone();
for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] {
@@ -211,6 +285,22 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
});
});
ui.separator();
let on = set.sliders == Sliders::Hsl;
if menu_item(ui, tl!("HSL Sliders"), true, on) {
let sliders = if on { Sliders::None } else { Sliders::Hsl };
if let Err(e) = app.run("ui.colorWheel", json!({ "sliders": sliders.id() })) {
app.status(e);
}
}
let on = set.sliders == Sliders::Oklch;
// While the rows show, the item stays enabled so that they can be hidden.
let enabled = on || cms::active().rgb_is_srgb();
if widgets::menu_item_hint(ui, tl!("OKLCH Sliders"), enabled, on, tl!("OKLCH needs sRGB as the working RGB space")) {
let sliders = if on { Sliders::None } else { Sliders::Oklch };
if let Err(e) = app.run("ui.colorWheel", json!({ "sliders": sliders.id() })) {
app.status(e);
}
}
if menu_item(ui, tl!("Show Harmony"), set.view == View::Wheel, set.harmony) {
command(app, &json!({ "harmony": !set.harmony })).ok();
}
@@ -299,6 +389,16 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) ->
/// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored.
const MEMORY: &str = "color-wheel-hsb";
/// Panel state: the OKLCH the slider rows asked for last, the [`Owner`] of the color they stored
/// and its display sRGB.
const OKLCH_MEMORY: &str = "color-wheel-oklch";
/// Panel state: the slider rows whose drag previews on an open interaction, until it is released.
const ROWS_LIVE: &str = "color-wheel-rows-live";
/// The message for OKLCH Sliders while the active document's RGB space is not sRGB.
const OKLCH_NEEDS_SRGB: &str = "OKLCH needs sRGB as the working RGB space";
/// Panel state: the HSL the slider rows asked for last, the [`Owner`] of the color they stored and
/// its display sRGB.
const HSL_MEMORY: &str = "color-wheel-hsl";
/// The height of the color vision chips and the space between them.
const VISION_CHIP: f32 = 16.0;
const VISION_GAP: f32 = 3.0;
@@ -399,6 +499,28 @@ impl Owner {
}
}
/// The components remembered under `key` for the target's `color`: the display sRGB the color had
/// when they were stored, and the components. A record whose owner or display color differs from
/// what the panel shows now is dropped, so that it does not come back when the same color returns
/// later.
fn recall<T: Clone + Send + Sync + 'static>(
app: &VectorcraftApp,
ui: &Ui,
key: &str,
tgt: &Target,
color: Option<Color>,
cms: &Cms,
) -> Option<([f32; 3], T)> {
let (owner, shown, v) = pstate::<Option<(Owner, [f32; 3], T)>>(ui.ctx(), key)?;
match color {
Some(c) if owner == Owner::of(app, tgt, c) && cms.display_rgb(&c) == shown => Some((shown, v)),
_ => {
set_pstate(ui.ctx(), key, None::<(Owner, [f32; 3], T)>);
None
}
}
}
/// The HSB a color shows on the wheel: that of its display sRGB through `cms`.
pub(crate) fn display_hsb(cms: &Cms, c: &Color) -> [f32; 3] {
rgb_to_hsb(cms.display_rgb(c))
@@ -416,7 +538,12 @@ pub(crate) fn remembered_hsb(cms: &Cms, c: &Color, shown: [f32; 3], hsb: [f32; 3
/// model with the color settings. Anything else (no color, a Gray color, a tint of a global swatch)
/// becomes a process color in the document's color mode: managed CMYK when `cmyk_doc`, else RGB.
pub(crate) fn stored(cms: &Cms, hsb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color {
let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(hsb));
stored_srgb(cms, hsb_to_rgb(hsb), was, cmyk_doc)
}
/// [`stored`] for a pick of display sRGB `srgb`.
pub(crate) fn stored_srgb(cms: &Cms, srgb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color {
let [r, g, b] = cms.srgb_to_rgb(srgb);
let rgb = Color::rgb(r, g, b);
let cmyk = || {
let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
@@ -450,14 +577,215 @@ fn replaced(app: &VectorcraftApp, tgt: &Target, behind: bool) -> Option<Color> {
}
}
/// The OKLCH `[l, c, h°]` the rows show for `c` through `cms` when `lch` was asked for last and `c`
/// then displayed as the sRGB `shown`: `lch` while `c` still displays as `shown` (a chroma past the
/// gamut and the hue of a gray stay), else `c`'s own.
pub(crate) fn remembered_oklch(cms: &Cms, c: &Color, shown: [f32; 3], lch: [f64; 3]) -> [f64; 3] {
if cms.display_rgb(c) == shown { lch } else { oklab::to_oklch(clipped_rgb(cms, c)) }
}
/// The display sRGB of `c` through `cms` clipped to sRGB: the color the slider rows show and edit
/// for a color outside sRGB.
fn clipped_rgb(cms: &Cms, c: &Color) -> [f32; 3] {
cms.display_rgb(c).map(|v| v.clamp(0.0, 1.0))
}
/// The color a track shows at OKLCH `lch`: the color itself inside sRGB, and outside it dimmed.
/// A color outside sRGB shows at the largest chroma that fits at its L and H, the color a pick
/// there stores. With `max_chroma` (the C track, whose L and H stay fixed) that chroma is given
/// for the colors past it; without it, or in a gap below it where the ray leaves sRGB and comes
/// back, it is found for each color.
pub(crate) fn oklch_track(lch: [f64; 3], max_chroma: Option<f64>) -> Color32 {
let exact = oklab::oklch_to_srgb(lch[0], lch[1], lch[2]);
let (rgb, outside) = match max_chroma {
Some(m) if lch[1] > m => (oklab::oklch_to_srgb(lch[0], m, lch[2]), true),
Some(_) if oklab::in_srgb(exact) => (exact, false),
_ => {
let (rgb, lowered) = oklab::from_oklch(lch[0], lch[1], lch[2]);
(rgb.map(f64::from), lowered)
}
};
let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
let c = Color32::from_rgb(r, g, b);
if outside { c.gamma_multiply(0.3) } else { c }
}
/// Where the C track's tick sits, from 0 at its left to 1 at its right: at the largest chroma
/// `max_chroma`, of the track's 0 to 0.4.
pub(crate) fn chroma_tick(max_chroma: f64) -> f32 {
(max_chroma / CHROMA_FULL).clamp(0.0, 1.0) as f32
}
/// The L, C and H rows of OKLCH Sliders for the target's `color` through `cms`: lightness from 0 to
/// 100 %, chroma from 0 to 100 % of 0.4 (as CSS reads a chroma percentage) and hue from 0 to 360°.
/// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the
/// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no
/// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow
/// key, a screen reader or a field asks for, and its phase.
pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option<Color>, cms: &Cms) -> Option<([f64; 3], Live)> {
let t = Tokens::get(ui.ctx());
let enabled = color.is_some() && cms.rgb_is_srgb();
let lch = match (color, recall::<[f64; 3]>(app, ui, OKLCH_MEMORY, tgt, color, cms)) {
(Some(c), Some((shown, lch))) => remembered_oklch(cms, &c, shown, lch),
(Some(c), _) => oklab::to_oklch(clipped_rgb(cms, &c)),
(None, _) => [0.0; 3],
};
// Each row: its letter, its screen-reader name, the end of its range and the field's suffix.
let rows = [("L", tl!("Lightness"), 100.0, "%"), ("C", tl!("Chroma"), 100.0, "%"), ("H", tl!("Hue"), 360.0, "°")];
let shown = [lch[0] * 100.0, lch[1] / CHROMA_FULL * 100.0, lch[2]];
// The OKLCH with row `i` set to `v` in the row's units.
let with = |i: usize, v: f64| {
let mut out = lch;
match i {
0 => out[0] = (v / 100.0).clamp(0.0, 1.0),
1 => out[1] = (v / 100.0 * CHROMA_FULL).clamp(0.0, CHROMA_FULL),
_ => out[2] = v.clamp(0.0, 360.0),
}
out
};
let mut out = None;
// The L and H tracks search the gamut for each color outside sRGB, so their colors are kept
// until the other two components change.
let mut tracks = pstate::<[Option<([u64; 3], Vec<Color32>)>; 3]>(ui.ctx(), OKLCH_TRACKS);
ui.add_enabled_ui(enabled, |ui| {
let field_w = 48.0;
let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0);
// The C track's L and H stay fixed, so its largest chroma is found once per frame.
let max_c = if enabled { oklab::max_chroma(lch[0], lch[2]) } else { 0.0 };
for (i, (letter, name, max, suffix)) in rows.into_iter().enumerate() {
ui.horizontal(|ui| {
ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text)));
let v = shown[i].clamp(0.0, max);
let at = |x: f32| with(i, f64::from(x) * max);
let mut key = lch.map(f64::to_bits);
key[i] = 0;
let colors = match &tracks[i] {
Some((k, colors)) if i != 1 && enabled && *k == key => colors.clone(),
_ if i != 1 && enabled => {
let last = (TRACK_SAMPLES - 1) as f32;
let colors: Vec<Color32> = (0..TRACK_SAMPLES).map(|s| oklch_track(at(s as f32 / last), None)).collect();
tracks[i] = Some((key, colors.clone()));
colors
}
_ => Vec::new(),
};
let track = |x: f32| match colors.get((x.clamp(0.0, 1.0) * (TRACK_SAMPLES - 1) as f32).round() as usize) {
Some(c) => *c,
None if enabled => oklch_track(at(x), (i == 1).then_some(max_c)),
None => t.input,
};
let value = SliderValue::field(v, 0.0..=max, suffix, 0);
let (dragged, phase, keyed) =
widgets::color_slider_stepped(ui, ("color-wheel-oklch", i), name, Some(value), (v / max) as f32, slider_w, &track);
// The tick goes on the bar of the rail as the row laid it out.
let rail = (i == 1 && enabled).then(|| ui.ctx().read_response(widgets::id_with(ui.scope_id(), ("color-wheel-oklch", i)))).flatten();
if let Some(rail) = rail {
let bar = widgets::color_rail_bar(rail.rect);
let x = bar.left() + chroma_tick(max_c) * bar.width();
ui.painter().line_segment([pos2(x, bar.top() - 3.0), pos2(x, bar.bottom())], Stroke::new(1.5, t.text));
let tip = Rect::from_x_y_ranges(x - 3.0..=x + 3.0, bar.top() - 3.0..=bar.bottom());
ui.interact(tip, ui.scope_id().with("color-wheel-oklch-tick"), egui::Sense::hover())
.on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue"));
}
if let Some(x) = dragged {
out = Some((at(x), phase));
}
if let Some(k) = keyed {
out = Some((with(i, k), Live::Released));
}
if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) {
out = Some((with(i, f), Live::Released));
}
});
}
});
set_pstate(ui.ctx(), OKLCH_TRACKS, tracks);
out.filter(|_| enabled)
}
/// Panel state: the colors of the L and H tracks of OKLCH Sliders, each with the OKLCH (its own
/// component left out) they were drawn for.
const OKLCH_TRACKS: &str = "color-wheel-oklch-tracks";
/// How many colors along a cached track.
const TRACK_SAMPLES: usize = 128;
/// The HSL `[h°, s, l]` the rows show for `c` through `cms` when `hsl` was asked for last and `c`
/// then displayed as the sRGB `shown`: `hsl` while `c` still displays as `shown` (the hue of a gray
/// and the saturation of black and white stay), else `c`'s own.
pub(crate) fn remembered_hsl(cms: &Cms, c: &Color, shown: [f32; 3], hsl: [f32; 3]) -> [f32; 3] {
if cms.display_rgb(c) == shown { hsl } else { rgb_to_hsl(clipped_rgb(cms, c)) }
}
/// The color a track shows at HSL `hsl`.
fn hsl32(hsl: [f32; 3]) -> Color32 {
let [r, g, b] = hsl_to_rgb(hsl).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
Color32::from_rgb(r, g, b)
}
/// The H, S and L rows of HSL Sliders for the target's `color` through `cms`: hue from 0 to 360°,
/// saturation and lightness from 0 to 100 %, CSS Color 4's HSL of the display sRGB. Each track
/// shows the colors its slider reaches. The rows are gray with no color to edit. Returns the HSL a
/// drag, an arrow key, a screen reader or a field asks for, and its phase.
pub(crate) fn hsl_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option<Color>, cms: &Cms) -> Option<([f32; 3], Live)> {
let t = Tokens::get(ui.ctx());
let enabled = color.is_some();
let hsl = match (color, recall::<[f32; 3]>(app, ui, HSL_MEMORY, tgt, color, cms)) {
(Some(c), Some((shown, hsl))) => remembered_hsl(cms, &c, shown, hsl),
(Some(c), _) => rgb_to_hsl(clipped_rgb(cms, &c)),
(None, _) => [0.0; 3],
};
// Each row: its letter, its screen-reader name, the end of its range and the field's suffix. The
// names start with "HSL" so that they differ from the box strip's HSB Hue and Saturation.
let hsl_name = |name: &str| format!("HSL {name}");
let rows =
[("H", hsl_name(tl!("Hue")), 360.0, "°"), ("S", hsl_name(tl!("Saturation")), 100.0, "%"), ("L", hsl_name(tl!("Lightness")), 100.0, "%")];
let shown = [f64::from(hsl[0]), f64::from(hsl[1]) * 100.0, f64::from(hsl[2]) * 100.0];
// The HSL with row `i` set to `v` in the row's units.
let with = |i: usize, v: f64| {
let mut out = hsl;
match i {
0 => out[0] = v.clamp(0.0, 360.0) as f32,
1 => out[1] = (v / 100.0).clamp(0.0, 1.0) as f32,
_ => out[2] = (v / 100.0).clamp(0.0, 1.0) as f32,
}
out
};
let mut out = None;
ui.add_enabled_ui(enabled, |ui| {
let field_w = 48.0;
let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0);
for (i, (letter, name, max, suffix)) in rows.into_iter().enumerate() {
ui.horizontal(|ui| {
ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text)));
let v = shown[i].clamp(0.0, max);
let at = |x: f32| with(i, f64::from(x) * max);
let track = |x: f32| if enabled { hsl32(at(x)) } else { t.input };
let value = SliderValue::field(v, 0.0..=max, suffix, 0);
let (dragged, phase, keyed) =
widgets::color_slider_stepped(ui, ("color-wheel-hsl", i), &name, Some(value), (v / max) as f32, slider_w, &track);
if let Some(x) = dragged {
out = Some((at(x), phase));
}
if let Some(k) = keyed {
out = Some((with(i, k), Live::Released));
}
if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-hsl-field", i), Some(&name), v, suffix, 0, field_w) {
out = Some((with(i, f), Live::Released));
}
});
}
});
out.filter(|_| enabled)
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let tgt = wheel_target(app, ui);
let color = tgt.color();
let cms = cms::active();
// With None, a pattern or a "?" proxy the wheel shows the last solid color without markers,
// and a click, an arrow key or a screen reader's action applies the picked color.
let hsb = match (color, pstate::<Option<(Owner, [f32; 3], [f32; 3])>>(ui.ctx(), MEMORY)) {
(Some(c), Some((owner, shown, hsb))) if owner == Owner::of(app, &tgt, c) => remembered_hsb(&cms, &c, shown, hsb),
let hsb = match (color, recall::<[f32; 3]>(app, ui, MEMORY, &tgt, color, &cms)) {
(Some(c), Some((shown, hsb))) => remembered_hsb(&cms, &c, shown, hsb),
(c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)),
};
let marked = color.is_some();
@@ -512,16 +840,80 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
pick = Some(([hsb[0], x, 1.0 - y], field_phase));
}
});
let (mut picked_lch, mut picked_hsl) = (None, None);
match app.ui.color_wheel.sliders {
Sliders::None => {}
Sliders::Oklch => {
ui.add_space(4.0);
picked_lch = oklch_rows(app, ui, &tgt, color, &cms);
}
Sliders::Hsl => {
ui.add_space(4.0);
picked_hsl = hsl_rows(app, ui, &tgt, color, &cms);
}
}
// A row drag whose rows were hidden or replaced (`ui.colorWheel {sliders}`), or turned gray
// (OKLCH rows after the working RGB space stops being sRGB), reports no release: its preview is
// kept as one undo step and the interaction ends.
let live = pstate::<Option<Sliders>>(ui.ctx(), ROWS_LIVE);
if live.is_some_and(|rows| rows != app.ui.color_wheel.sliders || (rows == Sliders::Oklch && !cms.rgb_is_srgb())) {
if app.session.in_interaction()
&& let Err(e) = app.session.commit_interaction()
{
app.status(e.to_string());
}
app.sync_views();
set_pstate(ui.ctx(), ROWS_LIVE, None::<Sliders>);
}
if app.ui.color_wheel.vision {
ui.add_space(4.0);
vision_row(ui, &cms, color.as_ref());
}
let Some((hsb, phase)) = pick else { return };
let behind = super::alt_held(ui);
let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk);
let rows = match (picked_hsl, picked_lch) {
(Some((hsl, phase)), _) => Some((hsl_to_rgb(hsl), phase, HSL_MEMORY, Remembered::Hsl(hsl))),
(_, Some((lch, phase))) => Some((oklab::from_oklch(lch[0], lch[1], lch[2]).0, phase, OKLCH_MEMORY, Remembered::Oklch(lch))),
_ => None,
};
if let Some((srgb, phase, key, asked)) = rows {
// A hue on a gray, or a saturation on black or white, leaves the displayed color as it is:
// the rows keep what they were given, and the paint (a Gray color too) stays unchanged.
let current = color.filter(|c| {
let d = cms.display_rgb(c);
!behind && live.is_none() && (0..3).all(|i| (d[i] - srgb[i]).abs() <= 1e-5)
});
if let Some(c) = current {
asked.remember(ui, key, Owner::of(app, &tgt, c), cms.display_rgb(&c));
return;
}
let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc);
apply(app, &tgt, c, phase, behind);
set_pstate(ui.ctx(), ROWS_LIVE, (phase == Live::Dragging).then_some(app.ui.color_wheel.sliders));
if !behind {
asked.remember(ui, key, Owner::of(app, &tgt, c), cms.display_rgb(&c));
}
return;
}
let Some((hsb, phase)) = pick else { return };
let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc);
apply(app, &tgt, c, phase, behind);
if !behind {
set_pstate(ui.ctx(), MEMORY, Some((Owner::of(app, &tgt, c), cms.display_rgb(&c), hsb)));
}
}
/// What a slider row asked for, kept under its memory key.
enum Remembered {
Hsl([f32; 3]),
Oklch([f64; 3]),
}
impl Remembered {
fn remember(self, ui: &Ui, key: &str, owner: Owner, shown: [f32; 3]) {
match self {
Remembered::Hsl(v) => set_pstate(ui.ctx(), key, Some((owner, shown, v))),
Remembered::Oklch(v) => set_pstate(ui.ctx(), key, Some((owner, shown, v))),
}
}
}
+375 -19
View File
@@ -474,7 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
});
let zone = ui.interact(list_rect, ui.scope_id().with("symbols-drop"), Sense::hover());
if !over_symbol && let Some(ids) = widgets::art_drop(ui, &zone) {
// Shift held at the release keeps the dropped art as ordinary art.
// Shift held at the release that ends the drag keeps the dropped art as ordinary art.
let mut p = json!({ "ids": ids, "type": "dynamic" });
if modifiers_at_release(ui).shift {
p["keepArt"] = json!(true);
@@ -529,8 +529,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
} else if new.clicked() {
// Alt skips Symbol Options: the symbol is made under the default name, dynamic as the
// dialog's default. Shift keeps the selected art as ordinary art, with or without Alt.
// Both are read as the primary button went up, when it did in this frame.
let m = modifiers_at_release(ui);
// Both are read as the button went up on it.
let m = modifiers_released_in(ui, new.interact_rect, new.clicked_by(egui::PointerButton::Primary));
let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) };
if m.shift {
p["keepArt"] = json!(true);
@@ -545,7 +545,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let picked = if marked.contains(&name) { &marked[..] } else { &[] };
delete(app, picked, Some(&name), alt_at_release(ui));
} else if trash.clicked() {
delete(app, &marked, sel.as_deref(), alt_at_release(ui));
let pointer = trash.clicked_by(egui::PointerButton::Primary);
delete(app, &marked, sel.as_deref(), modifiers_released_in(ui, trash.interact_rect, pointer).alt);
}
});
}
@@ -558,18 +559,21 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty());
let inst = has_instances_selected(app);
let name = json!({"name": sel});
// Shift keeps the selected art as ordinary art instead of making it an instance. It is read as
// the primary button went up, when it did in this frame.
let shift = modifiers_at_release(ui).shift;
let redefine = if shift { json!({"name": sel, "keepArt": true}) } else { name.clone() };
let new = if shift { json!({"keepArt": true}) } else { json!({}) };
let items: [(&str, bool, &str, Value); 3] = [
(tl!("New Symbol…"), has_sel, "ui.symbolOptions", new),
(tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", redefine),
(tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()),
// Shift, held as the button went up on New Symbol… or Redefine Symbol, keeps the selected art
// as ordinary art instead of making it an instance.
let items: [(&str, bool, &str, Value, bool); 3] = [
(tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({}), true),
(tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", name.clone(), true),
(tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone(), false),
];
for (label, enabled, cmd, params) in items {
if menu_item(ui, label, enabled, false) {
for (label, enabled, cmd, mut params, keeps_art) in items {
let top = ui.cursor().min.y;
let item = widgets::menu_item_response(ui, label, enabled, false);
if item.clicked() {
let row = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=ui.cursor().min.y);
if keeps_art && modifiers_released_in(ui, row, item.clicked_by(egui::PointerButton::Primary)).shift {
params["keepArt"] = json!(true);
}
app.run(cmd, params).ok();
}
}
@@ -668,14 +672,71 @@ fn art_redefine_drop(ui: &Ui, item: &egui::Response, doc: &Document, uid: Option
item.dnd_release_payload::<PanelDrag>().map(|_| ids.iter().map(|id| id.0).collect())
}
/// Whether Alt (Option) is held for a drop or a click: when the primary button went up in this frame, as it
/// went up, else now.
/// Whether Alt (Option) is held for a drop: as [`modifiers_at_release`] gives it.
fn alt_at_release(ui: &Ui) -> bool {
modifiers_at_release(ui).alt
}
/// The modifiers held for a drop or a click: when the primary button went up in this frame, as it went up,
/// else now.
/// The modifiers held for a click on the widget whose interact rectangle is `rect`: when the
/// primary button last went up in this frame as a click (the pointer stayed within egui's click
/// distance of where the button went down) after going down over `rect` or within egui's interact
/// radius of it (egui gives a press that close to the widget), as it went up (egui reports the
/// click of the last such release in the frame); else, when no such click happened in this frame,
/// as the first release of the frame went up, which ends a press of an earlier frame that egui
/// counted as the click; else now. A release that ends a drag is not a click and is skipped.
/// `pointer` is whether egui reports the widget clicked by the primary button; when it is false,
/// the click came from the keyboard or a screen reader and the modifiers held now are used.
fn modifiers_released_in(ui: &Ui, rect: egui::Rect, pointer: bool) -> egui::Modifiers {
if !pointer {
return ui.input(|i| i.modifiers);
}
let radius = ui.ctx().global_style().interaction.interact_radius;
let max_click_dist = ui.ctx().options(|o| o.input_options.max_click_dist);
ui.input(|i| {
// Where the button went down in this frame, and whether the pointer has since moved too far
// for a click.
let mut origin: Option<egui::Pos2> = None;
let mut moved = false;
// Whether a button went down earlier in this frame; until one does, a release ends a press
// of an earlier frame.
let mut pressed_here = false;
// The modifiers of the release that ends a press of an earlier frame.
let mut early = None;
let mut found = None;
for e in &i.events {
match e {
egui::Event::PointerMoved(pos) => {
moved |= origin.is_some_and(|o| o.distance(*pos) > max_click_dist);
}
egui::Event::PointerButton { pos, pressed: true, .. } => {
origin = Some(*pos);
moved = false;
pressed_here = true;
}
egui::Event::PointerButton { pos, button, pressed: false, modifiers } => {
moved |= origin.is_some_and(|o| o.distance(*pos) > max_click_dist);
let over = origin.is_some_and(|o| rect.distance_sq_to_pos(o) <= radius * radius);
if *button == egui::PointerButton::Primary {
if !pressed_here {
early = early.or(Some(*modifiers));
} else if !moved && over {
found = Some(*modifiers);
}
}
origin = None;
moved = false;
}
_ => {}
}
}
// egui tracks a press of an earlier frame. A widget it reports clicked by the pointer, with
// no click on it after a press of this frame, was clicked by the early release.
found.or(early).unwrap_or(i.modifiers)
})
}
/// The modifiers held for a drop: when the primary button went up in this frame, as it first went
/// up, which is the release that ends a drag under way when the frame starts; else now.
fn modifiers_at_release(ui: &Ui) -> egui::Modifiers {
ui.input(|i| {
i.events
@@ -1110,6 +1171,21 @@ mod tests {
assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance");
}
/// A Shift-click on New Symbol… in the panel menu that goes down in one frame and up in the next
/// keeps the art as ordinary art, though a plain click elsewhere follows in the same frame.
#[test]
fn a_shift_click_on_new_symbol_in_the_menu_counts_though_a_click_elsewhere_follows() {
let (mut app, _) = leaf_dot_and_rect();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let off = pos2(-10.0, -10.0);
let after = vec![egui::Event::PointerMoved(off), button(off, true), button(off, false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)];
click_menu_held_then(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT, after);
assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND));
crate::dialogs::confirm(&mut app).unwrap();
assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art");
}
/// Clicks the panel's New Symbol button with `modifiers` held.
fn click_new(app: &mut VectorcraftApp, modifiers: egui::Modifiers) {
click_button_then(app, "New Symbol", modifiers, vec![]);
@@ -1267,6 +1343,181 @@ mod tests {
assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance");
}
/// A drop on the panel reads Shift from the release that ends the drag: a click on the list
/// without Shift later in the same frame keeps a Shift drop's art as ordinary art, and a click
/// with Shift does not keep a plain drop's art.
#[test]
fn a_drop_on_the_panel_reads_shift_from_the_release_that_ends_the_drag() {
let (mut app, rect) = leaf_dot_and_rect();
let ctx = egui::Context::default();
let at = pos2(180.0, 60.0);
let release = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers };
let press = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers };
widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]);
frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::SHIFT);
let plain = egui::Modifiers::NONE;
let events = vec![release(egui::Modifiers::SHIFT), egui::Event::ModifiersChanged(plain), press(plain), release(plain)];
frame_held(&ctx, &mut app, events, egui::Modifiers::SHIFT);
assert_eq!(art(&app, "New Symbol"), (0, 1), "the Shift drop keeps the rectangle as ordinary art");
widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]);
frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], plain);
let shift = egui::Modifiers::SHIFT;
let events = vec![release(plain), egui::Event::ModifiersChanged(shift), press(shift), release(shift)];
frame_held(&ctx, &mut app, events, plain);
assert_eq!(art(&app, "New Symbol 2"), (1, 0), "the plain drop makes the rectangle an instance");
}
/// A click of the primary button off the panel with no modifiers held, the pointer then back
/// at `at`.
fn stray_click(at: Pos2) -> [egui::Event; 4] {
let off = pos2(-10.0, -10.0);
let button =
|pressed| egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
[egui::Event::PointerMoved(off), button(true), button(false), egui::Event::PointerMoved(at)]
}
/// Clicks the panel button labeled `label` with `modifiers` held as the primary button goes up,
/// between two clicks off the panel without them, and lets them go later in the same frame.
fn click_button_let_go(app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) {
let ctx = egui::Context::default();
ctx.enable_accesskit();
let out = frame_held(&ctx, app, vec![], modifiers);
let at = clickable(&out).into_iter().find(|(l, _)| l == label).unwrap_or_else(|| panic!("a {label} button")).1;
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers };
let let_go = egui::Event::ModifiersChanged(egui::Modifiers::NONE);
let mut events = stray_click(at).to_vec();
events.extend([press(true), press(false), let_go]);
events.extend(stray_click(at));
frame_held(&ctx, app, events, modifiers);
}
/// Clicks the menu item labeled `label` with `modifiers` held as the primary button goes up,
/// between two clicks off the menu without them, and lets them go later in the same frame.
fn click_menu_let_go(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) {
let held = egui::Event::ModifiersChanged(modifiers);
let labels = menu_frame(ctx, app, vec![held.clone()]);
let item = labels.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} in the menu"));
let press = |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers };
let mut events = vec![held];
events.extend(stray_click(item));
events.extend([press(true), press(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
events.extend(stray_click(item));
menu_frame(ctx, app, events);
}
/// The New Symbol and Delete Symbol buttons and the menu's New Symbol… and Redefine Symbol read
/// Shift and Alt as the primary button goes up on them, though clicks elsewhere without them
/// come before and after and they are let go later in the same frame.
#[test]
fn symbol_clicks_read_the_modifiers_as_the_button_goes_up() {
let (mut app, rect) = leaf_dot_and_rect();
click_button_let_go(&mut app, "New Symbol", egui::Modifiers::SHIFT | egui::Modifiers::ALT);
assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options");
assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]);
assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art");
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
click_menu_let_go(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT);
crate::dialogs::confirm(&mut app).unwrap();
assert_eq!(art(&app, "New Symbol 2"), (0, 1), "the menu's Shift keeps the rectangle as ordinary art");
app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap();
click_menu_let_go(&ctx, &mut app, "Redefine Symbol", egui::Modifiers::SHIFT);
assert_eq!(art(&app, "Dot"), (0, 1), "Redefine Symbol with Shift keeps the rectangle as ordinary art");
assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]);
// Dot holds the rectangle now and nothing places it, so Alt deletes it without asking.
click_button_let_go(&mut app, "Delete Symbol", egui::Modifiers::ALT);
assert_eq!(dialog_kind(&app), None, "Alt deletes an unused symbol without asking");
assert_eq!(symbols(&mut app), ["Leaf", "New Symbol", "New Symbol 2"]);
}
/// A click just outside New Symbol, which egui still counts as a click on it, reads Shift and
/// Alt as the primary button goes up there, though they are let go later in the same frame.
#[test]
fn a_click_just_outside_new_symbol_reads_the_modifiers_as_the_button_goes_up() {
let (mut app, _) = leaf_dot_and_rect();
let ctx = egui::Context::default();
ctx.enable_accesskit();
let modifiers = egui::Modifiers::SHIFT | egui::Modifiers::ALT;
let out = frame_held(&ctx, &mut app, vec![], modifiers);
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
let b = nodes
.iter()
.find(|(_, n)| n.label().is_some_and(|l| l.trim() == "New Symbol"))
.and_then(|(_, n)| n.bounds())
.expect("a New Symbol button");
let at = pos2(b.x0 as f32 - 2.0, ((b.y0 + b.y1) / 2.0) as f32);
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers };
let events = vec![egui::Event::PointerMoved(at), press(true), press(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)];
frame_held(&ctx, &mut app, events, modifiers);
assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options");
assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]);
assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art");
}
/// A click that goes down on the edge of New Symbol and, in the next frame, up past egui's
/// interact radius but within its click distance counts as a click on it and reads Shift and Alt
/// as the button goes up, though they are let go later in the same frame.
#[test]
fn a_click_released_past_the_interact_radius_reads_the_modifiers_as_the_button_goes_up() {
let (mut app, _) = leaf_dot_and_rect();
let ctx = egui::Context::default();
ctx.enable_accesskit();
let modifiers = egui::Modifiers::SHIFT | egui::Modifiers::ALT;
let out = frame_held(&ctx, &mut app, vec![], modifiers);
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
let b = nodes
.iter()
.find(|(_, n)| n.label().is_some_and(|l| l.trim() == "New Symbol"))
.and_then(|(_, n)| n.bounds())
.expect("a New Symbol button");
let y = ((b.y0 + b.y1) / 2.0) as f32;
let (down, up) = (pos2(b.x0 as f32 + 0.5, y), pos2(b.x0 as f32 - 5.4, y));
let radius = ctx.global_style().interaction.interact_radius;
let max_click_dist = ctx.options(|o| o.input_options.max_click_dist);
assert!(down.distance(up) <= max_click_dist && b.x0 as f32 - up.x > radius, "the release is a click outside the radius");
let button = |at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers };
frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(down), button(down, true)], modifiers);
let events = vec![egui::Event::PointerMoved(up), button(up, false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)];
frame_held(&ctx, &mut app, events, modifiers);
assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options");
assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]);
assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art");
}
/// An Alt-click on Delete Symbol followed in the same frame by a drag that ends just outside
/// it without Alt reads Alt from the click: the release that ends the drag is not a click.
#[test]
fn a_drag_ending_near_delete_symbol_after_an_alt_click_keeps_the_click_modifiers() {
let mut app = leaf_and_dot();
let ctx = egui::Context::default();
ctx.enable_accesskit();
let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE);
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
let b = nodes
.iter()
.find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol"))
.and_then(|(_, n)| n.bounds())
.expect("a Delete Symbol button");
let center = pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32);
let near = pos2(b.x0 as f32 - 1.0, center.y);
let from = pos2(near.x, near.y - 12.0);
let button = |pos, pressed, modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers };
let (alt, none) = (egui::Modifiers::ALT, egui::Modifiers::NONE);
let events = vec![
egui::Event::PointerMoved(center),
button(center, true, alt),
button(center, false, alt),
egui::Event::ModifiersChanged(none),
egui::Event::PointerMoved(from),
button(from, true, none),
egui::Event::PointerMoved(near),
button(near, false, none),
];
frame_held(&ctx, &mut app, events, alt);
assert_eq!(dialog_kind(&app), None, "Alt deletes the unused symbol without asking");
assert_eq!(symbols(&mut app), ["Leaf"]);
}
/// `ui.symbolOptions` takes `keepArt` only as true or false, and only for a new symbol.
#[test]
fn symbol_options_checks_keep_art() {
@@ -2962,6 +3213,111 @@ mod tests {
assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is unchanged");
}
/// A plain art drop on a symbol followed in the same frame by an Alt-click on that symbol makes
/// a new symbol and leaves the symbol as it was: the release that ends the drag decides.
#[test]
fn an_alt_click_after_a_plain_art_drop_in_the_same_frame_does_not_redefine() {
let mut app = leaf_and_dot();
let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
let leaf = symbol_art(&app, "Leaf");
let ctx = egui::Context::default();
let at = item_at(&ctx, &mut app, "Leaf");
widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]);
frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE);
let alt_press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT };
let events = vec![button(at, false), egui::Event::ModifiersChanged(egui::Modifiers::ALT), alt_press, alt_release(at)];
frame_held(&ctx, &mut app, events, egui::Modifiers::NONE);
assert_eq!(symbols(&mut app).len(), 3, "a new symbol");
assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is unchanged");
}
/// A plain drop of an unused symbol on Delete Symbol followed in the same frame by an Alt-click
/// on the button still asks first: the release that ends the drag decides.
#[test]
fn an_alt_click_after_a_plain_drop_on_delete_in_the_same_frame_still_asks() {
let mut app = leaf_and_dot();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let trash = button_rect(&ctx, &mut app, "Delete Symbol").center();
let dot = item_at(&ctx, &mut app, "Dot");
frame(&ctx, &mut app, vec![]);
frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot), button(dot, true)]);
frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot + vec2(40.0, 40.0))]);
frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot + vec2(80.0, 80.0))]);
frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash)], egui::Modifiers::NONE);
let alt_press =
egui::Event::PointerButton { pos: trash, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT };
let events = vec![button(trash, false), egui::Event::ModifiersChanged(egui::Modifiers::ALT), alt_press, alt_release(trash)];
frame_held(&ctx, &mut app, events, egui::Modifiers::NONE);
assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the plain drop asks first");
assert_eq!(symbols(&mut app), ["Leaf", "Dot"]);
}
/// A screen reader's Click on Delete Symbol asks first for an unused symbol, though an Alt-click
/// elsewhere comes before it in the same frame and Alt is let go after.
#[test]
fn a_screen_reader_click_on_delete_does_not_take_alt_from_another_click() {
use egui::accesskit::{Action, ActionRequest, TreeId};
let mut app = leaf_and_dot();
let ctx = egui::Context::default();
ctx.enable_accesskit();
let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE);
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
let node =
nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol")).map(|(id, _)| *id).expect("a Delete Symbol node");
let off = pos2(-10.0, -10.0);
let alt = |pressed| egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT };
let click =
egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node: node, target_tree: TreeId::ROOT, data: None });
let events = vec![egui::Event::PointerMoved(off), alt(true), alt(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE), click];
frame_held(&ctx, &mut app, events, egui::Modifiers::ALT);
assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the screen reader's Click asks first");
assert_eq!(symbols(&mut app), ["Leaf", "Dot"]);
}
/// A screen reader's Click on Delete Symbol asks first for an unused symbol, though in the same
/// frame an Alt release over the button ends a drag that began in an earlier frame and Alt is
/// let go after.
#[test]
fn a_screen_reader_click_on_delete_does_not_take_alt_from_a_drag_begun_earlier() {
use egui::accesskit::{Action, ActionRequest, TreeId};
let mut app = leaf_and_dot();
let ctx = egui::Context::default();
ctx.enable_accesskit();
let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE);
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
let node =
nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol")).map(|(id, _)| *id).expect("a Delete Symbol node");
let trash = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1;
let off = pos2(-10.0, -10.0);
let press = egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT };
frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(off), press], egui::Modifiers::ALT);
frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash - vec2(0.0, 80.0))], egui::Modifiers::ALT);
let click =
egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node: node, target_tree: TreeId::ROOT, data: None });
let events = vec![egui::Event::PointerMoved(trash), alt_release(trash), egui::Event::ModifiersChanged(egui::Modifiers::NONE), click];
frame_held(&ctx, &mut app, events, egui::Modifiers::ALT);
assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the screen reader's Click asks first");
assert_eq!(symbols(&mut app), ["Leaf", "Dot"]);
}
/// A click on Delete Symbol that goes down in one frame and up with Alt held in the next deletes
/// an unused symbol without asking, though a plain click elsewhere follows in the same frame.
#[test]
fn an_alt_click_on_delete_across_frames_counts_though_a_click_elsewhere_follows() {
let mut app = leaf_and_dot();
let ctx = egui::Context::default();
ctx.enable_accesskit();
let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE);
let trash = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1;
frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash), button(trash, true)], egui::Modifiers::ALT);
let off = pos2(-10.0, -10.0);
let events = vec![alt_release(trash), egui::Event::PointerMoved(off), button(off, true), button(off, false)];
frame_held(&ctx, &mut app, events, egui::Modifiers::ALT);
assert_eq!(dialog_kind(&app), None, "Alt deletes an unused symbol without asking");
assert_eq!(symbols(&mut app), ["Leaf"]);
}
/// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new
/// symbol and adds no undo step: art of another document, objects the document no longer has,
/// no objects, and a release away from the panel are not outlined, and art holding an instance
@@ -197,6 +197,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
json!("calligraphic-nibs"),
json!("pressure-sensitive"),
json!("bristle-brushes"),
json!("paint"),
json!("pattern-borders"),
json!("decorative"),
json!("scatter-shapes"),
@@ -207,7 +208,8 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
json!("tech-circuit"),
json!("engraving"),
json!("arrows"),
json!("image-brush")
json!("image-brush"),
json!("artistic")
]
);
let dry = entries.iter().find(|e| under(e) && e.params["library"] == "dry-media").map(|e| e.label.as_str());
@@ -238,11 +240,32 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0);
assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines"));
assert_eq!(undo_len(&app), undo + 1);
let r = app.run("window.brushLibrary", json!({"library": "Artistic Brushes"})).unwrap();
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("artistic"), Some(4)));
let previous = crate::i18n::current();
crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap());
assert_eq!(crate::menus::display_label(&app, "window.brushLibrary", "Artistic Brushes"), "Künstlerische Pinsel");
crate::i18n::set_current(previous);
let undo = undo_len(&app);
click(&mut app, &ctx, "Orbit Lines", Modifiers::NONE, 3.0);
assert!(has(&app, "Orbit Lines") && !has(&app, "Facet Sweep"));
assert_eq!(undo_len(&app), undo + 1);
// Without brushes there is nothing to save.
let all: Vec<String> = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect();
app.run("brush.delete", json!({ "names": all })).unwrap();
let entries = crate::menus::menu_entries(&app);
assert!(entries.iter().any(|e| under(e) && e.command.as_deref() == Some("ui.saveBrushLibrary") && !e.enabled));
}
#[test]
fn pressure_decorative_paint_and_image_libraries_add_a_brush_in_one_step() {
let mut app = app();
let ctx = context();
let r = app.run("window.brushLibrary", json!({"library": "Pressure Sensitive"})).unwrap();
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("pressure-sensitive"), Some(4)));
let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap();
let undo = undo_len(&app);
click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 3.0);
click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 4.0);
assert!(has(&app, "Flex Ribbon") && !has(&app, "Pulse Stroke"));
assert_eq!(undo_len(&app), undo + 1);
assert_eq!(
@@ -253,24 +276,30 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("decorative"), Some(4)));
let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap();
let undo = undo_len(&app);
click(&mut app, &ctx, "Leaf Vine", Modifiers::NONE, 4.0);
click(&mut app, &ctx, "Leaf Vine", Modifiers::NONE, 5.0);
assert!(has(&app, "Leaf Vine") && !has(&app, "Lantern String"));
assert_eq!(undo_len(&app), undo + 1);
assert_eq!(
app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(),
Some("Leaf Vine")
);
let r = app.run("window.brushLibrary", json!({"library": "Paint"})).unwrap();
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("paint"), Some(4)));
let path = app.run("shape.line", json!({"x1": 10, "y1": 140, "x2": 180, "y2": 140})).unwrap()["id"].as_u64().unwrap();
let undo = undo_len(&app);
click(&mut app, &ctx, "Flat Sweep", Modifiers::NONE, 6.0);
assert!(has(&app, "Flat Sweep") && !has(&app, "Dry Drag"));
assert_eq!(undo_len(&app), undo + 1);
assert_eq!(
app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(),
Some("Flat Sweep")
);
let r = app.run("window.brushLibrary", json!({"library": "Image Brush"})).unwrap();
assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("image-brush"), Some(4)));
let undo = undo_len(&app);
click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 4.0);
click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 8.0);
assert!(has(&app, "Soft Bloom") && !has(&app, "Color Flecks"));
assert_eq!(undo_len(&app), undo + 1);
// Without brushes there is nothing to save.
let all: Vec<String> = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect();
app.run("brush.delete", json!({ "names": all })).unwrap();
let entries = crate::menus::menu_entries(&app);
assert!(entries.iter().any(|e| under(e) && e.command.as_deref() == Some("ui.saveBrushLibrary") && !e.enabled));
}
#[test]
+573 -1
View File
@@ -11,7 +11,9 @@ use vectorcraft_color::cms::{self, Cms, ColorSettings, delta_e2000};
use vectorcraft_color::{Color, Paint};
use vectorcraft_engine::Session;
use super::color_wheel::{ID, display_hsb, remembered_hsb, show, stored};
use super::color_wheel::{
ID, Settings, Sliders, chroma_tick, display_hsb, oklch_rows, oklch_track, remembered_hsb, remembered_hsl, remembered_oklch, set, show, stored,
};
use crate::VectorcraftApp;
/// An app with a selected rectangle filled with `fill`.
@@ -581,3 +583,573 @@ fn the_color_pickers_field_takes_the_arrow_keys() {
assert!(near(stepped, [after[0], after[1] + 0.01, after[2]], [1e-3, 1e-4, 1e-4]), "{after:?} → {stepped:?}");
assert!(h.state().ui.dialog.is_some(), "the dialog stays open");
}
/// The panel with OKLCH Sliders shown, in a flyout tall enough for the rows.
fn oklch_harness(mut app: VectorcraftApp) -> Harness<'static, VectorcraftApp> {
app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap();
oklch_harness_shown(app)
}
/// The panel in a flyout tall enough for the rows, with the app's settings as they are.
fn oklch_harness_shown(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> {
let mut h = Harness::builder().with_size(vec2(260.0, 420.0)).build_ui_state(
|ui, app: &mut VectorcraftApp| {
show(app, ui);
crate::shortcuts::handle(app, ui.ctx());
},
app,
);
h.run_steps(2);
h
}
/// The slider row named `name` (its number field has the same name).
fn oklch_slider<'a>(h: &'a Harness<'static, VectorcraftApp>, name: &'a str) -> egui_kittest::Node<'a> {
h.query_all_by_label(name).find(|n| n.accesskit_node().role() == egui::accesskit::Role::Slider).expect("a slider row")
}
/// The point at `t` (0..1) along the bar of a slider row.
fn on_rail(rail: Rect, t: f32) -> Pos2 {
Pos2::new(rail.left() + 4.0 + t * (rail.width() - 8.0), rail.top() + 7.0)
}
fn fill_oklch(app: &VectorcraftApp) -> [f64; 3] {
vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&fill(app)))
}
/// `ui.colorWheel {sliders: "oklch"}` shows L, C and H rows with the fill's OKLCH, and the panel
/// keeps the setting with the preferences.
#[test]
fn oklch_sliders_show_the_fills_lightness_chroma_and_hue() {
let h = oklch_harness(app(json!("#ff0000")));
assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Oklch);
let value = |name: &str| oklch_slider(&h, name).accesskit_node().numeric_value().unwrap();
assert_eq!((value("Lightness"), value("Chroma"), value("Hue")), (63.0, 64.0, 29.0));
let saved = serde_json::to_value(&h.state().ui).unwrap();
assert_eq!(saved["color_wheel"]["sliders"], json!("oklch"));
}
/// A drag on L past the chroma sRGB holds stores the largest chroma that fits at the same hue, and
/// the C row keeps the chroma asked for, so dragging L back brings it back.
#[test]
fn a_drag_on_lightness_keeps_the_chroma_asked_for() {
let mut h = oklch_harness(app(json!("#0000ff")));
let [l0, c0, h0] = fill_oklch(h.state());
let rail = oklch_slider(&h, "Lightness").rect();
drag(&mut h, &[on_rail(rail, l0 as f32), on_rail(rail, 0.9)], Modifiers::NONE);
let [l1, c1, h1] = fill_oklch(h.state());
assert!((l1 - 0.9).abs() < 0.01 && c1 < c0 - 0.1 && (h1 - h0).abs() < 1.0, "{:?} → {:?}", [l0, c0, h0], [l1, c1, h1]);
let chroma = oklch_slider(&h, "Chroma").accesskit_node().numeric_value().unwrap();
assert_eq!(chroma, (c0 / 0.4 * 100.0).round(), "the C row keeps the requested chroma");
drag(&mut h, &[on_rail(rail, 0.9), on_rail(rail, l0 as f32)], Modifiers::NONE);
let [l2, c2, _] = fill_oklch(h.state());
assert!((l2 - l0).abs() < 0.01 && (c2 - c0).abs() < 0.01, "{:?} → {:?}", [l0, c0], [l2, c2]);
}
/// A press on a row gives it the keyboard focus, and → raises it by one unit as one undo step.
/// Each row reports its range and the adjust actions to screen readers.
#[test]
fn the_oklch_rows_take_the_arrow_keys_and_screen_readers_actions() {
let mut h = oklch_harness(app(json!("#808080")));
for (name, max) in [("Lightness", 100.0), ("Chroma", 100.0), ("Hue", 360.0)] {
let node = oklch_slider(&h, name).accesskit_node();
assert_eq!((node.min_numeric_value(), node.max_numeric_value(), node.numeric_value_step()), (Some(0.0), Some(max), Some(1.0)), "{name}");
assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a)), "{name}");
}
let rail = oklch_slider(&h, "Lightness").rect();
let l = fill_oklch(h.state())[0];
click(&mut h, on_rail(rail, l as f32), Modifiers::NONE);
let before = fill_oklch(h.state())[0];
let undo = undo_len(h.state());
key(&mut h, egui::Key::ArrowRight, Modifiers::NONE);
let after = fill_oklch(h.state())[0];
assert!((after - ((before * 100.0).round() + 1.0) / 100.0).abs() < 0.003, "{before} → {after}");
assert_eq!(undo_len(h.state()), undo + 1, "one undo step");
let (gray, undo) = (fill(h.state()), undo_len(h.state()));
let (target_node, target_tree) = oklch_slider(&h, "Hue").accesskit_node().locate();
let data = Some(ActionData::NumericValue(200.0));
h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data }));
// The frame that takes the request draws the row before it applies it.
h.run_steps(2);
assert_eq!(oklch_slider(&h, "Hue").accesskit_node().numeric_value(), Some(200.0), "a gray keeps the hue it was given");
assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "a hue on a gray changes nothing and records no undo step");
}
/// Each track dims the colors outside sRGB, and the C track's tick sits at the largest chroma sRGB
/// holds, along the track's 0 to 0.4.
#[test]
fn the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma() {
let (l, h) = (0.7, 150.0);
let max = vectorcraft_color::oklab::max_chroma(l, h);
for max_chroma in [Some(max), None] {
assert_eq!(oklch_track([l, max * 0.5, h], max_chroma).a(), 255, "{max_chroma:?}: inside sRGB");
assert!(oklch_track([l, 0.4, h], max_chroma).a() < 255, "{max_chroma:?}: outside sRGB is dimmed");
}
// Near white, an L or H track shows the color a pick there stores: the largest chroma that fits,
// not each channel clamped on its own.
let (stored, lowered) = vectorcraft_color::oklab::from_oklch(0.98, 0.2, h);
let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8);
assert!(lowered);
assert_eq!(oklch_track([0.98, 0.2, h], None), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3));
// At blue's L and H the ray leaves sRGB below the largest chroma and comes back at blue: the C
// track dims that gap and shows the color a pick there stores.
let [bl, _, bh] = vectorcraft_color::oklab::to_oklch([0.0, 0.0, 1.0]);
let blue_max = vectorcraft_color::oklab::max_chroma(bl, bh);
let (stored, lowered) = vectorcraft_color::oklab::from_oklch(bl, 0.29, bh);
let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8);
assert!(lowered && blue_max > 0.3);
assert_eq!(oklch_track([bl, 0.29, bh], Some(blue_max)), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3));
assert_eq!(oklch_track([bl, blue_max, bh], Some(blue_max)).a(), 255, "blue itself is inside sRGB");
assert!((chroma_tick(max) - (max / 0.4) as f32).abs() < 1e-6 && chroma_tick(max) > 0.1 && chroma_tick(max) < 1.0);
assert_eq!((chroma_tick(0.0), chroma_tick(0.5)), (0.0, 1.0));
}
/// After Edit › Color Settings picks a working RGB space other than sRGB, Panel menu › OKLCH Sliders
/// is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows already shown are gray.
#[test]
fn oklch_sliders_are_gray_after_the_working_space_changes() {
const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_P3";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: change them in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "panels::tests_color_wheel::oklch_sliders_are_gray_after_the_working_space_changes", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated working space test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
let mut app = app(json!("#ff0000"));
app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap();
assert_eq!(app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap_err(), "OKLCH needs sRGB as the working RGB space");
assert_eq!(app.ui.color_wheel.sliders, Sliders::None);
let mut fonts = false;
let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if !fonts {
crate::theme::install_fonts(ui.ctx());
fonts = true;
return;
}
super::color_wheel::menu(app, ui);
},
app,
);
h.run_steps(3);
assert!(h.get_by_label(" OKLCH Sliders").accesskit_node().is_disabled());
// The color settings stay with the process, so a new app works in Display P3 as well.
let mut app = self::app(json!("#ff0000"));
app.ui.color_wheel.sliders = Sliders::Oklch;
let h = oklch_harness_shown(app);
assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled());
}
/// A drag on an OKLCH row during which Edit › Color Settings picks a working RGB space other than
/// sRGB keeps the color the drag previewed as one undo step and leaves no interaction open, though
/// the gray rows report no release.
#[test]
fn a_working_space_change_during_an_oklch_drag_keeps_its_color_as_one_undo_step() {
const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_P3_DRAG";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: change them in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"panels::tests_color_wheel::a_working_space_change_during_an_oklch_drag_keeps_its_color_as_one_undo_step",
"--nocapture",
])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated working space test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
let mut h = oklch_harness(app(json!("#ff8000")));
let rail = oklch_slider(&h, "Lightness").rect();
let undo = undo_len(h.state());
press(&mut h, on_rail(rail, 0.5), true, Modifiers::NONE);
for _ in 0..2 {
h.event(Event::PointerMoved(on_rail(rail, 0.25)));
h.run_steps(1);
}
assert!(h.state().session.in_interaction(), "the drag previews");
let previewed = fill(h.state());
h.state_mut().run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap();
h.run_steps(2);
assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled());
press(&mut h, on_rail(rail, 0.25), false, Modifiers::NONE);
assert!(!h.state().session.in_interaction(), "the interaction ended");
assert_eq!((fill(h.state()), undo_len(h.state())), (previewed, undo + 1));
}
/// A CMYK fill's L, C and H are those of its display color, not of its naive separation.
#[test]
fn a_cmyk_fills_oklch_is_that_of_its_display_color() {
let h = oklch_harness(app(json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0})));
let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0)));
let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]);
let lightness = oklch_slider(&h, "Lightness").accesskit_node().numeric_value().unwrap();
assert_eq!(lightness, (shown[0] * 100.0).round());
assert_ne!(lightness, (naive[0] * 100.0).round());
}
/// Panel menu › OKLCH Sliders shows the rows and, checked, hides them.
#[test]
fn the_panel_menu_shows_and_hides_the_oklch_rows() {
let mut fonts = false;
let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
// The fonts, which hold the check mark, take effect from the next frame.
if !fonts {
crate::theme::install_fonts(ui.ctx());
fonts = true;
return;
}
super::color_wheel::menu(app, ui);
},
app(json!("#ff0000")),
);
h.run_steps(3);
h.get_by_label(" OKLCH Sliders").click();
h.run_steps(2);
assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Oklch);
h.get_by_label("✓ OKLCH Sliders").click();
h.run_steps(2);
assert_eq!(h.state().ui.color_wheel.sliders, Sliders::None);
}
/// In a working RGB space other than sRGB, `sliders: "oklch"` is an error and the rows are gray;
/// the error leaves the settings as they were.
#[test]
fn oklch_sliders_need_srgb_as_the_working_space() {
let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap();
let mut settings = Settings::default();
assert_eq!(set(&mut settings, &json!({"sliders": "oklch"}), &p3).unwrap_err(), "OKLCH needs sRGB as the working RGB space");
assert_eq!(settings.sliders, Sliders::None);
set(&mut settings, &json!({"sliders": "oklch"}), &Cms::default()).unwrap();
assert_eq!(settings.sliders, Sliders::Oklch);
set(&mut settings, &json!({"sliders": "none"}), &p3).unwrap();
assert_eq!(settings.sliders, Sliders::None, "the rows can be hidden in any working space");
let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
let tgt = super::color::wheel_target(app, ui);
let color = tgt.color();
let picked = oklch_rows(app, ui, &tgt, color, &p3);
assert!(picked.is_none(), "a gray row picks nothing: {picked:?}");
},
app(json!("#ff0000")),
);
h.run_steps(2);
assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled());
let rail = oklch_slider(&h, "Lightness").rect();
click(&mut h, on_rail(rail, 0.2), Modifiers::NONE);
key(&mut h, egui::Key::ArrowRight, Modifiers::NONE);
set_slider_value(&mut h, "Lightness", 20.0);
}
/// The rows show what they asked for while the color displays as it did, and the color's own
/// OKLCH after the color settings change its display.
#[test]
fn the_remembered_oklch_follows_a_change_of_working_space() {
let srgb = Cms::default();
let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap();
let c = Color::rgb(0.5, 0.3, 0.2);
let asked = [0.5, 0.3, 40.0];
let shown = srgb.display_rgb(&c);
assert_eq!(remembered_oklch(&srgb, &c, shown, asked), asked);
assert_eq!(remembered_oklch(&p3, &c, shown, asked), vectorcraft_color::oklab::to_oklch(p3.display_rgb(&c)));
}
/// The panel with HSL Sliders shown, in a flyout tall enough for the rows. `oklch_slider` and
/// `oklch_harness_shown` find and draw any slider row, the HSL rows included.
fn hsl_harness(mut app: VectorcraftApp) -> Harness<'static, VectorcraftApp> {
app.run("ui.colorWheel", json!({"sliders": "hsl"})).unwrap();
oklch_harness_shown(app)
}
fn fill_hsl(app: &VectorcraftApp) -> [f32; 3] {
vectorcraft_color::rgb_to_hsl(cms::active().display_rgb(&fill(app)))
}
/// Sets the slider row named `name` to `v` as a screen reader does.
fn set_slider_value(h: &mut Harness<'static, VectorcraftApp>, name: &str, v: f64) {
let (target_node, target_tree) = oklch_slider(h, name).accesskit_node().locate();
let data = Some(ActionData::NumericValue(v));
h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data }));
// The frame that takes the request draws the row before it applies it.
h.run_steps(2);
}
/// `ui.colorWheel {sliders: "hsl"}` shows H, S and L rows with the fill's HSL, CSS Color 4's
/// `hsl()` of its display sRGB, and the panel keeps the setting with the preferences.
#[test]
fn hsl_sliders_show_the_fills_hue_saturation_and_lightness() {
let h = hsl_harness(app(json!("#ff8000")));
assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Hsl);
let value = |name: &str| oklch_slider(&h, name).accesskit_node().numeric_value().unwrap();
assert_eq!((value("HSL Hue"), value("HSL Saturation"), value("HSL Lightness")), (30.0, 100.0, 50.0));
assert!(h.query_by_label("Chroma").is_none(), "OKLCH Sliders are hidden");
let saved = serde_json::to_value(&h.state().ui).unwrap();
assert_eq!(saved["color_wheel"]["sliders"], json!("hsl"));
}
/// In Box View with the Saturation channel, screen readers tell the box strip's HSB saturation
/// from the S row's HSL saturation by their names.
#[test]
fn the_hsl_rows_names_differ_from_the_box_strips() {
let mut app = app(json!("#996633"));
app.run("ui.colorWheel", json!({"view": "box", "channel": "saturation"})).unwrap();
let h = hsl_harness(app);
let sliders = |name: &str| h.query_all_by_label(name).filter(|n| n.accesskit_node().role() == egui::accesskit::Role::Slider).count();
assert_eq!((sliders("Saturation"), sliders("HSL Saturation")), (1, 1));
let strip = oklch_slider(&h, "Saturation").accesskit_node().numeric_value().unwrap();
let row = oklch_slider(&h, "HSL Saturation").accesskit_node().numeric_value().unwrap();
assert_ne!(strip, row, "HSB and HSL saturation differ for this color");
}
/// A drag on L changes the lightness and keeps the hue and the saturation.
#[test]
fn a_drag_on_hsl_lightness_keeps_the_hue_and_saturation() {
let mut h = hsl_harness(app(json!("#ff8000")));
let rail = oklch_slider(&h, "HSL Lightness").rect();
let undo = undo_len(h.state());
drag(&mut h, &[on_rail(rail, 0.5), on_rail(rail, 0.25)], Modifiers::NONE);
assert!(near(fill_hsl(h.state()), [30.0, 1.0, 0.25], [1.0, 0.01, 0.01]), "{:?}", fill_hsl(h.state()));
assert_eq!(undo_len(h.state()), undo + 1, "a drag is one undo step");
}
/// A press on S gives it the keyboard focus, and → raises it by 1 % as one undo step. Each row
/// reports its range and the adjust actions to screen readers.
#[test]
fn the_hsl_rows_take_the_arrow_keys_and_screen_readers_actions() {
let mut h = hsl_harness(app(json!("#996633")));
for (name, max) in [("HSL Hue", 360.0), ("HSL Saturation", 100.0), ("HSL Lightness", 100.0)] {
let node = oklch_slider(&h, name).accesskit_node();
assert_eq!((node.min_numeric_value(), node.max_numeric_value(), node.numeric_value_step()), (Some(0.0), Some(max), Some(1.0)), "{name}");
assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a)), "{name}");
}
let rail = oklch_slider(&h, "HSL Saturation").rect();
let s = fill_hsl(h.state())[1];
click(&mut h, on_rail(rail, s), Modifiers::NONE);
let before = fill_hsl(h.state());
let undo = undo_len(h.state());
key(&mut h, egui::Key::ArrowRight, Modifiers::NONE);
let after = fill_hsl(h.state());
let raised = ((before[1] * 100.0).round() + 1.0) / 100.0;
assert!(near(after, [before[0], raised, before[2]], [1.0, 0.008, 0.003]), "{before:?} → {after:?}");
assert_eq!(undo_len(h.state()), undo + 1, "one undo step");
}
/// A gray has no hue: a hue given to it stays on the H row while the color is unchanged, and a
/// saturation picked next uses that hue.
#[test]
fn a_gray_keeps_the_hsl_hue_it_was_given() {
let mut h = hsl_harness(app(json!("#808080")));
let (gray, undo) = (fill(h.state()), undo_len(h.state()));
set_slider_value(&mut h, "HSL Hue", 200.0);
assert_eq!(oklch_slider(&h, "HSL Hue").accesskit_node().numeric_value(), Some(200.0), "a gray keeps the hue it was given");
assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "a hue on a gray changes nothing and records no undo step");
set_slider_value(&mut h, "HSL Saturation", 60.0);
let got = fill_hsl(h.state());
assert!(near(got, [200.0, 0.6, 0.5], [1.0, 0.01, 0.01]), "{got:?}");
}
/// In a working RGB space wider than sRGB, an HSL pick goes from display sRGB into that space
/// through the color settings: the fill displays the HSL asked for, and its stored RGB numbers are
/// those of the working space, not the sRGB numbers of that HSL.
#[test]
fn an_hsl_pick_in_display_p3_goes_into_the_working_space() {
const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_HSL_P3";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: change them in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "panels::tests_color_wheel::an_hsl_pick_in_display_p3_goes_into_the_working_space", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated working space test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
let mut app = app(json!("#996633"));
app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap();
let mut h = hsl_harness(app);
let [hue, sat, _] = fill_hsl(h.state());
let undo = undo_len(h.state());
set_slider_value(&mut h, "HSL Lightness", 60.0);
let asked = [hue, sat, 0.6];
assert!(near(fill_hsl(h.state()), asked, [0.5, 0.005, 0.005]), "{asked:?} → {:?}", fill_hsl(h.state()));
assert_eq!(undo_len(h.state()), undo + 1, "one undo step");
let Color::Rgb { r, g, b } = fill(h.state()) else { panic!("an RGB fill stays RGB") };
let srgb = vectorcraft_color::hsl_to_rgb(asked);
assert!((0..3).any(|i| ([r, g, b][i] - srgb[i]).abs() > 0.01), "{:?} is stored as the sRGB numbers {srgb:?}", [r, g, b]);
}
/// Panel menu › HSL Sliders shows the H, S and L rows in place of OKLCH Sliders and, checked,
/// hides them; it is offered in any working RGB space.
#[test]
fn the_panel_menu_shows_and_hides_the_hsl_rows() {
let mut fonts = false;
let mut app = app(json!("#ff0000"));
app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap();
let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
// The fonts, which hold the check mark, take effect from the next frame.
if !fonts {
crate::theme::install_fonts(ui.ctx());
fonts = true;
return;
}
super::color_wheel::menu(app, ui);
},
app,
);
h.run_steps(3);
h.get_by_label(" HSL Sliders").click();
h.run_steps(2);
assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Hsl);
assert!(h.query_by_label("✓ OKLCH Sliders").is_none(), "the two slider sets show one at a time");
h.get_by_label("✓ HSL Sliders").click();
h.run_steps(2);
assert_eq!(h.state().ui.color_wheel.sliders, Sliders::None);
let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap();
let mut settings = Settings::default();
set(&mut settings, &json!({"sliders": "hsl"}), &p3).unwrap();
assert_eq!(settings.sliders, Sliders::Hsl, "HSL needs no particular working space");
}
/// The rows show what they asked for while the color displays as it did, and the color's own HSL
/// after the color settings change its display.
#[test]
fn the_remembered_hsl_follows_a_change_of_working_space() {
let srgb = Cms::default();
let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap();
let c = Color::rgb(0.5, 0.3, 0.2);
let asked = [20.0, 0.43, 0.35];
let shown = srgb.display_rgb(&c);
assert_eq!(remembered_hsl(&srgb, &c, shown, asked), asked);
assert_eq!(remembered_hsl(&p3, &c, shown, asked), vectorcraft_color::rgb_to_hsl(p3.display_rgb(&c)));
}
/// Saved settings are read key by key: a value this version does not know (one a newer version
/// wrote) gives the default, and the other preferences still load.
#[test]
fn saved_color_wheel_settings_are_read_leniently() {
let mut saved = serde_json::to_value(crate::UiState::default()).unwrap();
saved["color_rgb_percent"] = json!(true);
for (value, sliders) in [
(json!({"sliders": "oklch"}), Sliders::Oklch),
(json!({"sliders": "hsl"}), Sliders::Hsl),
(json!({"sliders": "hwb", "view": "box"}), Sliders::None),
(json!(5), Sliders::None),
] {
saved["color_wheel"] = value.clone();
let ui: crate::UiState = serde_json::from_value(saved.clone()).unwrap();
assert_eq!((ui.color_wheel.sliders, ui.color_rgb_percent), (sliders, true), "{value}");
}
}
/// `ui.colorWheel {sliders}` sets the rows and keeps the view and the channel, and an unknown
/// `sliders` value is an error that changes nothing.
#[test]
fn ui_color_wheel_sets_and_reads_the_sliders() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("ui.colorWheel", json!({"view": "box", "channel": "red"})).unwrap();
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none"));
assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hwb"})).unwrap_err(), "`sliders` must be none, oklch or hsl");
let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap();
let want = json!({"view": "box", "channel": "red", "harmony": false, "harmonyRule": "complementary", "vision": false, "sliders": "oklch"});
assert_eq!(got, want);
let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hwb"})).unwrap_err();
assert_eq!(e, "`sliders` must be none, oklch or hsl");
assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing");
}
/// A hue given to a Gray color does not change how it displays, so its paint stays a Gray color
/// and no undo step is recorded; the hue row keeps the hue.
#[test]
fn a_hue_on_a_gray_color_leaves_its_paint_gray() {
for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] {
let mut app = app(json!({"gray": 0.5}));
app.run("ui.colorWheel", json!({"sliders": rows})).unwrap();
let mut h = oklch_harness_shown(app);
let (gray, undo) = (fill(h.state()), undo_len(h.state()));
assert!(matches!(gray, Color::Gray { .. }), "{gray:?}");
set_slider_value(&mut h, hue, 200.0);
assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(200.0), "{rows}");
assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "{rows}: the Gray fill stays as it was");
}
}
/// For a fill outside sRGB, the HSL and OKLCH rows show the components of its display color
/// clipped to sRGB, the color the panel shows, not of the unclipped one.
#[test]
fn the_rows_show_a_color_outside_srgb_clipped_to_srgb() {
let rgb = json!([1.6, 0.2, -0.4]);
let raw = cms::active().display_rgb(&fill(&app(rgb.clone())));
let clipped = raw.map(|v| v.clamp(0.0, 1.0));
assert_ne!(raw, clipped, "the fill lies outside sRGB");
let want_hsl = (f64::from(vectorcraft_color::rgb_to_hsl(clipped)[2]) * 100.0).round();
assert_ne!(want_hsl, (f64::from(vectorcraft_color::rgb_to_hsl(raw)[2]) * 100.0).round(), "the unclipped lightness differs");
let h = hsl_harness(app(rgb.clone()));
assert_eq!(oklch_slider(&h, "HSL Lightness").accesskit_node().numeric_value(), Some(want_hsl));
let want_l = (vectorcraft_color::oklab::to_oklch(clipped)[0] * 100.0).round();
assert_ne!(want_l, (vectorcraft_color::oklab::to_oklch(raw)[0] * 100.0).round(), "the unclipped OKLCH lightness differs");
let h = oklch_harness(app(rgb));
assert_eq!(oklch_slider(&h, "Lightness").accesskit_node().numeric_value(), Some(want_l));
}
/// The hue given to a gray is dropped once the panel shows another color, so the same gray applied
/// again later shows its own hue, 0°.
#[test]
fn a_remembered_hue_is_dropped_after_the_paint_changes() {
for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] {
let mut app = app(json!("#808080"));
app.run("ui.colorWheel", json!({"sliders": rows})).unwrap();
let mut h = oklch_harness_shown(app);
set_slider_value(&mut h, hue, 240.0);
assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(240.0), "{rows}");
h.state_mut().run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
h.run_steps(2);
h.state_mut().run("paint.setFill", json!({"color": "#808080"})).unwrap();
h.run_steps(2);
assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(0.0), "{rows}: the gray's own hue");
}
}
/// Hiding the rows, or showing the other rows, during a drag on a row keeps the color the drag
/// previewed as one undo step and leaves no interaction open.
#[test]
fn hiding_the_rows_during_a_drag_keeps_its_color_as_one_undo_step() {
for rows in ["none", "oklch"] {
let mut h = hsl_harness(app(json!("#ff8000")));
let rail = oklch_slider(&h, "HSL Lightness").rect();
let undo = undo_len(h.state());
press(&mut h, on_rail(rail, 0.5), true, Modifiers::NONE);
for _ in 0..2 {
h.event(Event::PointerMoved(on_rail(rail, 0.25)));
h.run_steps(1);
}
assert!(h.state().session.in_interaction(), "{rows}: the drag previews");
let previewed = fill(h.state());
h.state_mut().run("ui.colorWheel", json!({"sliders": rows})).unwrap();
h.run_steps(2);
press(&mut h, on_rail(rail, 0.25), false, Modifiers::NONE);
assert!(!h.state().session.in_interaction(), "{rows}: the interaction ended");
assert_eq!((fill(h.state()), undo_len(h.state())), (previewed, undo + 1), "{rows}");
}
}
@@ -167,7 +167,7 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() {
#[test]
fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let harmony = json!({"harmony": false, "harmonyRule": "complementary", "vision": false});
let harmony = json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "vision": false});
let with = |v: serde_json::Value| {
let mut v = v;
v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone());
@@ -217,9 +217,9 @@ fn ui_color_wheel_rejects_other_params() {
let e = app.run("ui.colorWheel", json!([1])).unwrap_err();
assert_eq!(e, "the params must be an object, not [1]");
let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err();
assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, harmony, harmonyRule, vision");
assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, sliders, harmony, harmonyRule, vision");
let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err();
assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, harmony, harmonyRule, vision");
assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders, harmony, harmonyRule, vision");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing");
}
@@ -225,8 +225,7 @@ fn the_panel_menu_turns_the_row_on_and_off() {
#[test]
fn ui_color_wheel_sets_and_reads_the_settings() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let settings =
|view: &str, vision: bool| json!({"view": view, "channel": "hue", "harmony": false, "harmonyRule": "complementary", "vision": vision});
let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none"});
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false));
assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), settings("wheel", true));
assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["vision"], true);
@@ -237,7 +236,7 @@ fn ui_color_wheel_sets_and_reads_the_settings() {
assert_eq!(app.run("ui.colorWheel", json!(5)).unwrap_err(), "the params must be an object, not 5");
assert_eq!(
app.run("ui.colorWheel", json!({"visoin": false})).unwrap_err(),
"unknown parameter `visoin`; the command takes: view, channel, harmony, harmonyRule, vision"
"unknown parameter `visoin`; the command takes: view, channel, sliders, harmony, harmonyRule, vision"
);
assert!(app.ui.color_wheel.vision);
assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true);
+7 -2
View File
@@ -502,6 +502,10 @@ pub struct UiState {
/// starts under the selection at every launch.
#[serde(skip)]
pub task_bar_place: TaskBarPlace,
/// The Contextual Task Bar's actions (`canvas::TASK_BAR_ACTIONS`) that More Options › Bar
/// Actions has off (`window.taskBar.actions`); none: the bar shows every action it offers.
#[serde(deserialize_with = "crate::canvas::read_hidden_task_bar_actions")]
pub task_bar_hidden_actions: std::collections::BTreeSet<String>,
/// The Pathfinder panel's Shape Mode buttons make a compound shape on a click, and give the
/// permanent Pathfinder result on Alt-click (off, the default: the other way round).
#[serde(default)]
@@ -821,8 +825,8 @@ pub struct UiState {
/// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]).
#[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")]
pub color_rgb_percent: bool,
/// Color Wheel panel: the wheel or the box, the box's channel, and the color vision row
/// (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]).
/// Color Wheel panel: the wheel or the box, the box's channel, the slider rows and the color
/// vision row (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]).
#[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")]
pub color_wheel: crate::panels::color_wheel::Settings,
/// Swatches panel: Show Recent Colors in its panel menu, which draws the panel's Recent Colors
@@ -1270,6 +1274,7 @@ impl Default for UiState {
toolbar_advanced: false,
task_bar: true,
task_bar_place: TaskBarPlace::default(),
task_bar_hidden_actions: Default::default(),
shape_modes_compound: false,
context_locked: None,
context_intertwine: None,
+466
View File
@@ -1573,3 +1573,469 @@ fn the_task_bar_follows_edits_and_undo() {
assert!(has(&texts, "10 pt") && !has(&texts, "20 pt"), "{texts:?}");
assert!(!locked(&app, rect), "the button doesn't lock the shape");
}
/// Turns the bar's action or chip `action` on or off (`window.taskBar.actions`).
fn show_action(app: &mut VectorcraftApp, action: &str, visible: bool) {
let r = app.run("window.taskBar.actions", json!({"action": action, "visible": visible})).unwrap();
assert_eq!(r, json!({"action": action, "visible": visible}));
}
/// An action turned off in Bar Actions leaves the bar for every selection that offers it, and its
/// Object menu command stays enabled. Toggled, it comes back.
#[test]
fn an_action_turned_off_leaves_the_bar_and_stays_in_its_menu() {
let mut app = app();
app.run("tool.select", json!({"tool": "selection"})).unwrap();
let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap());
select(&mut app, &[line]);
let (_, texts) = bar(&mut app);
assert!(has(&texts, "Offset Path") && has(&texts, "Join"), "{texts:?}");
show_action(&mut app, "offsetPath", false);
assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "offsetPath"})), Some(false));
assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "join"})), Some(true));
let (_, texts) = bar(&mut app);
assert!(!has(&texts, "Offset Path"), "{texts:?}");
assert!(has(&texts, "Join") && has(&texts, "Simplify") && has(&texts, "Edit Path"), "the other actions stay: {texts:?}");
assert!(crate::menus::enabled(&app, "object.path.offsetPath"), "Object › Path › Offset Path… still runs");
// Another selection that offers the same action leaves it out too: a rectangle.
let rect = id(app.run("shape.rectangle", json!({"x": 220, "y": 40, "width": 80, "height": 60})).unwrap());
select(&mut app, &[rect]);
let (_, texts) = bar(&mut app);
assert!(!has(&texts, "Offset Path") && has(&texts, "Edit Path"), "{texts:?}");
// Toggled (no `visible`), it shows again.
assert_eq!(app.run("window.taskBar.actions", json!({"action": "offsetPath"})).unwrap(), json!({"action": "offsetPath", "visible": true}));
let (_, texts) = bar(&mut app);
assert!(has(&texts, "Offset Path"), "{texts:?}");
// A `visible` of null counts as omitted and toggles too.
let r = app.run("window.taskBar.actions", json!({"action": "offsetPath", "visible": null})).unwrap();
assert_eq!(r, json!({"action": "offsetPath", "visible": false}));
}
/// The Fill, Stroke, Recolor Artwork, Lock and Shape Properties chips each turn off on their own:
/// Lock off leaves a basic shape's Shape Properties, and Shape Properties off leaves Lock.
#[test]
fn a_chip_turned_off_leaves_the_bar() {
let mut app = app();
app.run("tool.select", json!({"tool": "selection"})).unwrap();
let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap());
let line = id(app.run("shape.line", json!({"x1": 50, "y1": 150, "x2": 200, "y2": 220})).unwrap());
select(&mut app, &[rect]);
let names = |app: &mut VectorcraftApp| buttons(app).1.into_iter().map(|(n, _)| n).collect::<Vec<_>>();
let shown = names(&mut app);
for name in ["Fill", "Stroke", "Shape Properties"] {
assert!(shown.iter().any(|n| n == name), "{name}: {shown:?}");
}
show_action(&mut app, "fill", false);
show_action(&mut app, "lock", false);
let shown = names(&mut app);
assert!(!shown.iter().any(|n| n == "Fill"), "{shown:?}");
assert!(shown.iter().any(|n| n == "Stroke") && shown.iter().any(|n| n == "Shape Properties"), "{shown:?}");
select(&mut app, &[line]);
let shown = names(&mut app);
assert!(!shown.iter().any(|n| n.starts_with("Lock")), "Lock is off: {shown:?}");
show_action(&mut app, "lock", true);
show_action(&mut app, "shapeProperties", false);
let shown = names(&mut app);
assert!(shown.iter().any(|n| n.starts_with("Lock")), "Lock is on again: {shown:?}");
select(&mut app, &[rect]);
let shown = names(&mut app);
assert!(!shown.iter().any(|n| n == "Shape Properties"), "{shown:?}");
}
/// Reset Bar Actions shows every action and chip again and returns the ids it showed.
#[test]
fn reset_bar_actions_shows_every_action_again() {
let mut app = app();
app.run("tool.select", json!({"tool": "selection"})).unwrap();
let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap());
select(&mut app, &[line]);
show_action(&mut app, "simplify", false);
show_action(&mut app, "duplicate", false);
show_action(&mut app, "stroke", false);
let (_, texts) = bar(&mut app);
assert!(!has(&texts, "Simplify") && !has(&texts, "Duplicate"), "{texts:?}");
assert_eq!(app.run("window.taskBar.resetActions", json!({})).unwrap(), json!(["duplicate", "simplify", "stroke"]));
assert!(app.ui.task_bar_hidden_actions.is_empty());
let (_, texts) = bar(&mut app);
assert!(has(&texts, "Simplify") && has(&texts, "Duplicate"), "{texts:?}");
assert_eq!(app.run("window.taskBar.resetActions", json!({})).unwrap(), json!([]), "nothing left to show");
}
/// Each of the bar's actions and chips has its own id, and no two actions run the same command
/// with the same tool.
#[test]
fn bar_action_ids_are_distinct() {
let ids: Vec<&str> = canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(canvas::TASK_BAR_CHIPS).collect();
let set: std::collections::BTreeSet<&str> = ids.iter().copied().collect();
assert_eq!(set.len(), ids.len(), "{ids:?}");
let runs: std::collections::BTreeSet<(&str, Option<&str>)> = canvas::TASK_BAR_ACTIONS.iter().map(|a| (a.1, a.2)).collect();
assert_eq!(runs.len(), canvas::TASK_BAR_ACTIONS.len());
}
/// An action the bar does not have, a missing one, or a `visible` that is not true, false or null is
/// an error and changes nothing.
#[test]
fn bar_actions_refuse_bad_params() {
let mut app = app();
show_action(&mut app, "group", false);
for p in [json!({"action": "teleport"}), json!({}), json!({"action": 3}), json!({"action": "unite", "visible": "yes"})] {
assert!(app.run("window.taskBar.actions", p.clone()).is_err(), "{p}");
}
let err = app.run("window.taskBar.actions", json!({"action": "teleport"})).unwrap_err();
assert!(err.contains("imageTrace") && err.contains("shapeProperties"), "{err}");
assert_eq!(app.ui.task_bar_hidden_actions.iter().map(String::as_str).collect::<Vec<_>>(), ["group"]);
assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "teleport"})), Some(false));
}
/// The actions that are off are kept with the preferences. Ids the bar does not have are dropped,
/// a value that is not a list turns none off, and older preferences without it show every action.
#[test]
fn bar_actions_are_kept_with_the_preferences() {
let mut app = app();
show_action(&mut app, "unite", false);
show_action(&mut app, "recolor", false);
let mut prefs = serde_json::to_value(&app.ui).unwrap();
let back: crate::state::UiState = serde_json::from_value(prefs.clone()).unwrap();
let ids = |ui: &crate::state::UiState| ui.task_bar_hidden_actions.iter().cloned().collect::<Vec<_>>();
assert_eq!(ids(&back), ["recolor", "unite"]);
prefs["task_bar_hidden_actions"] = json!(["unite", "teleport", 7, "fill"]);
assert_eq!(ids(&serde_json::from_value(prefs.clone()).unwrap()), ["fill", "unite"], "ids the bar does not have are dropped");
prefs["task_bar_hidden_actions"] = json!("unite");
assert!(ids(&serde_json::from_value(prefs.clone()).unwrap()).is_empty(), "a value that is not a list turns none off");
prefs.as_object_mut().unwrap().remove("task_bar_hidden_actions");
assert!(ids(&serde_json::from_value(prefs).unwrap()).is_empty(), "older preferences show every action");
app.run("window.taskBar.resetActions", json!({})).unwrap();
assert_eq!(serde_json::to_value(&app.ui).unwrap()["task_bar_hidden_actions"], json!([]), "none off");
}
/// More Options › Bar Actions lists the actions and chips the bar offers for the selection, each
/// checked while it shows; a click turns one off, it is listed unchecked after that, and a click on
/// Reset Bar Actions shows it again.
#[test]
fn more_options_bar_actions_turns_an_action_off_and_on() {
let mut app = app();
app.run("tool.select", json!({"tool": "selection"})).unwrap();
let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap());
select(&mut app, &[line]);
let more = buttons(&mut app).1.into_iter().find(|(n, _)| n == "More Options").expect("More Options").1.center();
let (ctx, _) = bar(&mut app);
let click_at = |app: &mut VectorcraftApp, p: Pos2| {
let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() };
frame(app, &ctx, vec![Event::PointerMoved(p)]);
frame(app, &ctx, vec![press(true)]);
frame(app, &ctx, vec![press(false)]);
frame(app, &ctx, vec![])
};
let texts = click_at(&mut app, more);
let item = at(&texts, " Bar Actions");
frame(&mut app, &ctx, vec![Event::PointerMoved(item)]);
let texts = frame(&mut app, &ctx, vec![]);
for name in ["✓ Join", "✓ Edit Path", "✓ Offset Path", "✓ Simplify", "✓ Duplicate", "✓ Fill", "✓ Stroke", "✓ Lock"] {
assert!(has(&texts, name), "{name}: {texts:?}");
}
assert!(has(&texts, " Reset Bar Actions"), "{texts:?}");
let offset = at(&texts, "✓ Offset Path");
// Along the submenu's row first, so the pointer stays over the menu on its way.
frame(&mut app, &ctx, vec![Event::PointerMoved(Pos2::new(offset.x, item.y))]);
click_at(&mut app, offset);
assert!(app.ui.task_bar_hidden_actions.contains("offsetPath"), "{:?}", app.ui.task_bar_hidden_actions);
let (_, texts) = bar(&mut app);
assert!(!has(&texts, "Offset Path") && has(&texts, "Simplify"), "{texts:?}");
// Opened again, Bar Actions lists it unchecked; Reset Bar Actions turns it on.
let more = buttons(&mut app).1.into_iter().find(|(n, _)| n == "More Options").expect("More Options").1.center();
let (ctx, _) = bar(&mut app);
let click_at = |app: &mut VectorcraftApp, p: Pos2| {
let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() };
frame(app, &ctx, vec![Event::PointerMoved(p)]);
frame(app, &ctx, vec![press(true)]);
frame(app, &ctx, vec![press(false)]);
frame(app, &ctx, vec![])
};
let texts = click_at(&mut app, more);
let item = at(&texts, " Bar Actions");
let reset = at(&texts, " Reset Bar Actions");
frame(&mut app, &ctx, vec![Event::PointerMoved(item)]);
let texts = frame(&mut app, &ctx, vec![]);
assert!(has(&texts, " Offset Path") && has(&texts, "✓ Simplify"), "{texts:?}");
// Back along the menu's column to Reset Bar Actions, closing the submenu on the way.
frame(&mut app, &ctx, vec![Event::PointerMoved(Pos2::new(item.x, reset.y))]);
click_at(&mut app, reset);
assert!(app.ui.task_bar_hidden_actions.is_empty(), "{:?}", app.ui.task_bar_hidden_actions);
let (_, texts) = bar(&mut app);
assert!(has(&texts, "Offset Path"), "{texts:?}");
}
/// On a canvas too short for every action, More Options lists the ones that don't fit; an action
/// turned off in Bar Actions is listed neither there nor on the bar, and the others still are.
#[test]
fn an_action_turned_off_is_not_listed_in_more_options() {
let mut app = app();
app.run("tool.select", json!({"tool": "selection"})).unwrap();
let a = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 100})).unwrap());
let b = id(app.run("shape.ellipse", json!({"x": 70, "y": 60, "width": 50, "height": 50})).unwrap());
select(&mut app, &[a, b]);
let size = vec2(160.0, 150.0);
// More Options' list, opened on a new context, and what the bar itself shows.
let listed = |app: &mut VectorcraftApp| {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let (on_bar, r, _) = bar_texts_on_screen(app, &ctx, size, 3);
let more = r.min + vec2(9.0 + 4.0 + 6.0 + 15.0, 7.0 + 15.0);
let press = |pressed| Event::PointerButton { pos: more, button: PointerButton::Primary, pressed, modifiers: Default::default() };
let screen = Rect::from_min_size(Pos2::ZERO, size);
let mut texts = vec![];
for events in [vec![Event::PointerMoved(more)], vec![press(true)], vec![press(false)], vec![]] {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| canvas::show(app, ui));
out.textures_delta.clear();
texts = shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::<Vec<_>>());
}
assert!(texts.iter().any(|(t, _)| t.trim() == "Hide Bar"), "More Options opens: {texts:?}");
let names = |t: &[(String, Rect)]| t.iter().map(|(t, _)| t.trim().to_string()).collect::<Vec<_>>();
(names(&on_bar), names(&texts))
};
let (on_bar, menu) = listed(&mut app);
for label in ["Unite", "Duplicate"] {
assert!(!on_bar.iter().any(|t| t == label) && menu.iter().any(|t| t == label), "{label} in More Options: {menu:?}");
}
show_action(&mut app, "unite", false);
let (on_bar, menu) = listed(&mut app);
assert!(!on_bar.iter().any(|t| t == "Unite") && !menu.iter().any(|t| t == "Unite"), "{on_bar:?} {menu:?}");
assert!(on_bar.iter().chain(&menu).any(|t| t == "Duplicate"), "Duplicate is still offered: {on_bar:?} {menu:?}");
}
/// Every action and chip the bar offers, for every kind of selection and tool, has an id in Bar
/// Actions, and with all of them turned off the bar shows none of them but still shows, with More
/// Options. That covers Connect and Join (both `join`), the actions matched by the tool they switch
/// to (`editPath`, `drawPencil`, `smoothToolOptions`), the Smooth tool's Fidelity, Dynamic Text,
/// an Image Trace object's Expand, the Type tool's Fill with type selected and while it edits
/// type, and the Artboard tool's actions.
#[test]
fn every_action_the_bar_offers_can_be_turned_off() {
let dir = crate::tests_folder::Folder::new("ui-taskbar-actions");
let line = |app: &mut VectorcraftApp| {
id(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 150, "y": 80}, {"x": 250, "y": 200}]})).unwrap())
};
let two = |app: &mut VectorcraftApp| {
let a = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 100})).unwrap());
let b = id(app.run("shape.ellipse", json!({"x": 70, "y": 60, "width": 50, "height": 50})).unwrap());
select(app, &[a, b]);
};
type Setup<'a> = Box<dyn Fn(&mut VectorcraftApp) + 'a>;
let cases: Vec<(&str, Setup, &[&str])> = vec![
(
"an open path",
Box::new(|app| {
let l = line(app);
select(app, &[l]);
}),
&["join", "editPath", "offsetPath", "simplify", "duplicate"],
),
(
"a path the Direct Selection tool selects whole",
Box::new(|app| {
let l = line(app);
select(app, &[l]);
app.run("tool.select", json!({"tool": "directSelection"})).unwrap();
}),
&["join", "convertToCorner", "convertToSmooth", "simplify", "smooth", "duplicate"],
),
(
"anchors picked out",
Box::new(|app| {
let l = line(app);
app.run("tool.select", json!({"tool": "directSelection"})).unwrap();
app.run("select.anchors", json!({"id": l, "anchors": [[0, 1]]})).unwrap();
}),
&["removeAnchorPoints", "join", "cutPath", "convertToCorner", "convertToSmooth"],
),
("two paths", Box::new(|app| two(app)), &["group", "unite", "duplicate"]),
(
"a group",
Box::new(|app| {
two(app);
app.run("object.group", json!({})).unwrap();
}),
&["ungroup", "isolate", "duplicate"],
),
(
"a compound path",
Box::new(|app| {
two(app);
app.run("object.compoundPath.make", json!({})).unwrap();
}),
&["editPath", "releaseCompoundPath", "duplicate"],
),
(
"a clipping group",
Box::new(|app| {
two(app);
let g = id(app.run("object.clippingMask.make", json!({})).unwrap());
select(app, &[g]);
}),
&["editClippingPath", "releaseClippingMask", "duplicate"],
),
(
"point type",
Box::new(|app| {
let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap());
select(app, &[t]);
}),
&["createOutlines", "convertToAreaType", "dynamicText", "fill", "stroke", "lock"],
),
(
"the Type tool with type selected",
Box::new(|app| {
let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap());
select(app, &[t]);
app.run("tool.select", json!({"tool": "type"})).unwrap();
}),
&["fill"],
),
(
"the Type tool editing type",
Box::new(|app| {
edited_type(app, "type");
}),
&["fill"],
),
(
"area type",
Box::new(|app| {
let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap());
select(app, &[t]);
app.run("type.convertToAreaType", json!({})).unwrap();
select(app, &[t]);
}),
&["createOutlines", "convertToPointType", "dynamicText"],
),
(
"type on a closed path",
Box::new(|app| {
let circle = id(app.run("path.create", json!({"d": "M100 300 A100 100 0 1 1 300 300 A100 100 0 1 1 100 300 Z"})).unwrap());
let t = id(app.run("text.createInPath", json!({"path": circle, "mode": "onPath", "text": "Round", "at": [90, 300]})).unwrap());
select(app, &[t]);
}),
&["createOutlines", "typeOnPathOptions", "centerOnTop", "centerOnBottom", "dynamicText"],
),
(
"an Image Trace object",
Box::new(|app| {
place_image(app, &dir);
app.run("imageTrace.make", json!({"params": {}})).unwrap();
}),
&["expand", "duplicate"],
),
(
"an image",
Box::new(|app| {
place_image(app, &dir);
}),
&["imageTrace", "cropImage", "removeBackground", "duplicate"],
),
(
"an image with a path",
Box::new(|app| {
let img = place_image(app, &dir);
let r = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap());
select(app, &[img, r]);
}),
&["group", "makeClippingMask", "duplicate"],
),
(
"a blank canvas",
Box::new(|app| {
let board = app.session.active().unwrap().doc.artboards[0].rect;
bar(app);
let view = app.view_mut().unwrap();
(view.center, view.zoom) = (board.center(), 0.5);
}),
&["drawPencil", "placeImage"],
),
(
"a shape tool after drawing",
Box::new(|app| {
drag_with(app, "rectangle", (60.0, 60.0), (120.0, 120.0));
}),
&["editPath"],
),
(
"the Smooth tool",
Box::new(|app| {
let e = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap());
select(app, &[e]);
app.run("tool.select", json!({"tool": "smooth"})).unwrap();
}),
&["fidelity", "smoothToolOptions"],
),
(
"the Artboard tool",
Box::new(|app| {
app.run("artboard.new", json!({"x": 420, "y": 0, "width": 200, "height": 200})).unwrap();
app.run("tool.select", json!({"tool": "artboard"})).unwrap();
}),
&["resizeArtboard", "duplicateArtboards", "rearrangeArtboards", "exportArtboards"],
),
];
for (case, setup, expected) in cases {
let mut app = app();
app.run("tool.select", json!({"tool": "selection"})).unwrap();
setup(&mut app);
let (ctx, _) = bar(&mut app);
let offered: Vec<(&str, Option<&str>)> = canvas::task_bar_offered(&ctx).into_iter().map(|(label, action, _)| (label, action)).collect();
assert!(canvas::task_bar_rect(&ctx).is_some() && !offered.is_empty(), "{case}: the bar shows actions");
for (label, action) in &offered {
assert!(action.is_some(), "{case}: {label} has no id in Bar Actions");
}
let ids: Vec<&str> = offered.iter().filter_map(|(_, a)| *a).collect();
for action in expected.iter() {
assert!(ids.contains(action), "{case}: {action} in {ids:?}");
}
for action in &ids {
show_action(&mut app, action, false);
}
let (ctx, texts) = bar_texts(&mut app);
for (label, _) in &offered {
assert!(!has(&texts, label), "{case}: {label} is off: {texts:?}");
}
// The bar still shows, with More Options, where Bar Actions turns them back on.
assert!(canvas::task_bar_rect(&ctx).is_some(), "{case}: the bar still shows");
let names: Vec<String> = buttons(&mut app).1.into_iter().map(|(n, _)| n).collect();
assert!(names.iter().any(|n| n == "More Options"), "{case}: {names:?}");
for (label, _) in &offered {
assert!(!names.iter().any(|n| n == label), "{case}: {label} is off: {names:?}");
}
}
}
/// Bar Actions lists a field's name without its colon, as each language writes it, and an item
/// that opens a dialog without its ellipsis.
#[test]
fn bar_actions_list_names_without_a_colon_or_an_ellipsis() {
let lang = |code| crate::i18n::Lang::from_code(code).unwrap();
for (code, label, name) in
[("en", "Fidelity:", "Fidelity"), ("en", "Tool Options…", "Tool Options"), ("fr", "Fidelity:", "Fidélité"), ("ja", "Fidelity:", "精度")]
.into_iter()
.chain([("zh-hans", "Fidelity:", "精确度"), ("zh-hant", "Fidelity:", "精確度"), ("zh-hans", "Tool Options…", "工具选项")])
{
let label = crate::i18n::tr(lang(code), label);
assert_eq!(canvas::bar_action_name(label), name, "{code}: {label:?}");
}
assert_eq!(canvas::bar_action_name("Duplicate"), "Duplicate");
assert_eq!(canvas::bar_action_name("Tool Options..."), "Tool Options");
assert_eq!(canvas::bar_action_name("Offset Path."), "Offset Path.");
// The colon and the ellipsis go in either order, with or without a space between them.
for label in [
"Tool Options...:",
"Tool Options... :",
"Tool Options: ...",
"Tool Options …:",
"Tool Options… :",
"Tool Options…\u{a0}:",
"Tool Options...\u{202f}:",
] {
assert_eq!(canvas::bar_action_name(label), "Tool Options", "{label:?}");
}
}
+3 -1
View File
@@ -37,7 +37,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[
(
"Shapes",
&[
&["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "spiral", "rectangularGrid", "polarGrid", "flare"],
&["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "threePointArc", "spiral", "rectangularGrid", "polarGrid", "flare"],
&["ellipse", "circle", "curvatureCircle"],
&["polygon"],
&["shaper"],
@@ -475,6 +475,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::
// The Line Segment, Arc and grid tools: their Tool Options, the options of their next
// drag and click.
_ if crate::dialogs::shapes::OPTION_TOOLS.contains(&tool) => crate::dialogs::shapes::open_options(app, tool),
// The Three-Point Arc tool: whether the third point gives a direction.
vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)),
// The Flare tool: its options, which draw the next flare (OK draws none); with flares
// selected, the first one's settings, and OK draws the selected flares again.
"flare" => Ok(crate::dialogs::flare_options::open(app, None)),
+6 -4
View File
@@ -27,11 +27,11 @@ pub use blend::{
reference_point_named,
};
pub use buttons::{
SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_name, paint_icon_button, primary_button,
primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon,
SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_hint, menu_item_name, paint_icon_button,
primary_button, primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon,
};
pub(crate) use buttons::{
button_width, flat_button_fit_width, icon_button_info, paint_icon_button_named, primary_button_width, secondary_button_width,
button_width, flat_button_fit_width, icon_button_info, menu_item_response, paint_icon_button_named, primary_button_width, secondary_button_width,
};
#[cfg(test)]
use chips::gradient_chip_colors;
@@ -42,13 +42,15 @@ pub use color::{
color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, recolor_wheel, region_texture, ring_markers, ring_square,
segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of,
};
pub(crate) use color::{HEX_FIELD_CHARS, focus_by_pointer, hex_text, pointer_phase};
pub(crate) use color::{HEX_FIELD_CHARS, color_rail_bar, focus_by_pointer, hex_text, pointer_phase};
pub use drag::{
PanelDrag, RowClick, SwatchRows, apply_row_click, art_drag_doc, art_drop, doc_preview, drag_art, drag_ghost, drag_source, drop_target_outline,
ghost_row, row_click,
};
#[cfg(test)]
use dropdowns::combo_button_id;
#[cfg(test)]
pub(crate) use dropdowns::top_popup_shapes;
pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, menu_min_width, popover_is_open};
pub use dropdowns::{
dropdown, dropdown_icon_names, dropdown_icon_names_sized, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with,
+22 -1
View File
@@ -213,9 +213,30 @@ pub fn menu_item(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool
menu_item_name(ui, tl!(label), enabled, checked)
}
/// [`menu_item`] that returns the row's response, for a caller that needs to know how it was
/// clicked.
pub(crate) fn menu_item_response(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response {
menu_item_name_response(ui, tl!(label), enabled, checked)
}
/// [`menu_item`] for a name that is user or file data (a library, a recent URL), never translated.
/// Like the menu bar's items, the row lights up under the pointer.
pub fn menu_item_name(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool {
menu_item_name_response(ui, label, enabled, checked).clicked()
}
/// [`menu_item_name`] that returns the row's response.
fn menu_item_name_response(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response {
let text = if checked { format!("✓ {label}") } else { format!(" {label}") };
ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)).clicked()
ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false))
}
/// [`menu_item`] that shows `hint` under the pointer while the row is disabled, to say why it is
/// gray.
pub fn menu_item_hint(ui: &mut Ui, label: &str, enabled: bool, checked: bool, hint: &str) -> bool {
let label = tl!(label);
let text = if checked { format!("✓ {label}") } else { format!(" {label}") };
ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false))
.on_disabled_hover_text(tl!(hint))
.clicked()
}
+6 -1
View File
@@ -279,6 +279,11 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, always: bool, s: &SliderValue
(v != from || (end && v != s.value) || (always && asked)).then_some(if exact { v } else { round_to(v, STEP_DECIMALS).clamp(lo, hi) })
}
/// The colored bar inside the rail `rect` of [`color_slider_stepped`] and its siblings.
pub(crate) fn color_rail_bar(rect: Rect) -> Rect {
Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(rect.width() - 8.0, 7.0))
}
/// The rail of [`color_slider_valued`] with the id `id`: its response, the new value from 0 to 1
/// that a click or drag gives and the phase.
fn color_rail(
@@ -292,7 +297,7 @@ fn color_rail(
) -> (Response, Option<f32>, Live) {
let t = Tokens::get(ui.ctx());
let (rect, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover());
let bar = Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(width - 8.0, 7.0));
let bar = color_rail_bar(rect);
let resp = ui.interact(rect, id, Sense::click_and_drag());
gradient_strip(ui, bar, (bar.width() / 2.0).ceil().max(2.0) as usize, false, track);
ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside);
+182 -13
View File
@@ -149,9 +149,10 @@ fn option_row<'a>(ui: &mut Ui, enabled: bool, selected: bool, atoms: impl egui::
response
}
/// The id [`craft_ui::ComboBox::from_id_salt`] gives its button in this `Ui`: `from_id_salt`
/// stores `IdSalt::new(salt)` and hashes it once more with the scope, so the app must hash `id`
/// the same way to read the button's focus and open state before it is drawn.
/// The id of the button of [`combo_atoms_named`] in this `Ui`, the one
/// [`craft_ui::ComboBox::from_id_salt`] gives its button: `from_id_salt` stores
/// `IdSalt::new(salt)` and hashes it once more with the scope. The app reads the button's focus and
/// open state with it before the button is drawn.
pub(super) fn combo_button_id(ui: &Ui, id: &impl std::hash::Hash) -> egui::Id {
ui.make_persistent_id(egui::IdSalt::new(HashOnly(id)))
}
@@ -206,9 +207,8 @@ fn combo_atoms_named<'a, R>(
if opening {
ui.data_mut(|d| d.insert_temp(opened_key, pass));
}
// The menu measures itself against the whole screen on the pass it opens and takes
// the room beside its field on the next one, so the current option is scrolled into
// view on both.
// The list is laid out unseen to measure it on the pass it opens and placed on the
// next one, so the current option is scrolled into view on both.
let settling = ui.data(|d| d.get_temp::<u64>(opened_key)).is_some_and(|p| pass <= p + 1);
// A list drawn inside this one's rows finds its own record, and this one's comes back after it.
let outer = if settling { OPENING.replace(Some(Opening::default())) } else { OPENING.take() };
@@ -238,17 +238,14 @@ fn combo_atoms_named<'a, R>(
chosen
};
let enter_for_combo = ui.memory(|m| m.has_focus(button_id)) || craft_ui::ComboBox::is_open(ui.ctx(), button_id);
let response = craft_ui::ComboBox::from_id_salt(HashOnly(&id))
.selected_text(current)
.width(width - 4.0)
.height(ui.spacing().combo_height)
.show_ui(ui, list);
let response = combo_button(ui, button_id, current, width - 4.0);
let shown = combo_list(ui, &response, list);
// The button or open list handles Enter before the modal can accept it.
if enter_for_combo {
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
let _ = name_field(label_field(response.response.clone(), label), name);
let chosen = response.inner.flatten();
let _ = name_field(label_field(response, label), name);
let chosen = shown.flatten();
// egui closes the list on a click of the pointer only: an option picked with Space or
// Enter closes it here, and the combo gives the keyboard back, so that Enter reaches the
// dialog's OK (#2789).
@@ -261,6 +258,178 @@ fn combo_atoms_named<'a, R>(
.inner
}
/// The button of [`combo_atoms_named`] with the id `button_id`, at least `width` wide, showing
/// `current`: [`craft_ui::ComboBox`]'s button, with its look, its tooltip for a value cut short and
/// its role for screen readers. It is drawn here so that its list opens in [`combo_list`].
fn combo_button<'a>(ui: &mut Ui, button_id: egui::Id, current: impl egui::IntoAtoms<'a>, width: f32) -> Response {
use egui::class::HasClasses as _;
use egui::{AtomExt as _, NumExt as _};
let open = egui::Popup::is_id_open(ui.ctx(), button_id.with("popup"));
let mut classes = egui::class::Classes::default();
classes.add_class(craft_ui::ComboBox::CLASS);
classes.set_class(craft_ui::ComboBox::CLASS_OPEN, open);
let egui::widget_style::ButtonStyle { atom_layout } = ui.widget_style(button_id, &classes);
let visuals = if open {
ui.visuals().widgets.open
} else if let Some(response) = ui.ctx().read_response(button_id) {
*ui.style().interact(&response)
} else {
ui.visuals().widgets.inactive
};
let min_size = vec2(width, 0.0).at_least(atom_layout.min_size);
let current = current.into_atoms();
let text = current.text().map(String::from).unwrap_or_default();
let rtl = ui.style().right_to_left;
// The combo box's arrow: a downward triangle.
let arrow = egui::Atom::paint(Vec2::splat(ui.spacing().icon_width), move |ui, args| {
let rect = args.rect.expand(visuals.expansion);
let rect = Rect::from_center_size(rect.center(), vec2(rect.width() * 0.7, rect.height() * 0.45));
ui.painter().add(egui::Shape::rotated_triangle(rect, 0.0, visuals.fg_stroke.color));
})
.atom_grow(true)
.atom_align(if rtl { egui::Align2::LEFT_CENTER } else { egui::Align2::RIGHT_CENTER });
let button = atom_layout
.apply(
egui::WidgetAtom::new((current, arrow))
.id(button_id)
.sense(Sense::click())
.fallback_font(egui::TextStyle::Button)
.wrap_mode(ui.wrap_mode())
.direction(if rtl { egui::Direction::RightToLeft } else { egui::Direction::LeftToRight }),
)
.min_size(min_size)
.measure(ui, ui.available_size());
let elided = button.container.iter_texts().any(|galley| galley.elided);
let response = button.allocate(ui).paint(ui).response;
// A value cut short shows in full on hover, as a truncated `Label`'s does.
let response = if elided {
response.on_hover_ui(|ui| {
ui.set_max_width(ui.spacing().tooltip_width);
ui.add(egui::Label::new(text.as_str()).wrap());
})
} else {
response
};
response.widget_info(|| egui::WidgetInfo {
enabled: ui.is_enabled(),
current_text_value: Some(text.clone()),
..egui::WidgetInfo::new(egui::Role::ComboBox)
});
response
}
/// The list of [`combo_atoms_named`] while it is open, drawn by `list` in a popup of its own that
/// opens from `button` and takes the whole list whenever the window has room for it (#5941): below
/// the button when it fits there, above it when it fits there instead, and otherwise moved up from
/// below, over the button, until it ends at the bottom bars. It stays above the bottom bars
/// ([`menu_floor`]), and a list taller than the room above them scrolls. A click closes
/// the list, except a click on its scroll bar, which scrolls it. Returns what `list` returned, or
/// `None` while the list is closed.
fn combo_list<R>(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> Option<R> {
let ctx = ui.ctx();
let id = button.id.with("popup");
let style = egui::style::StyleModifier::new(|style| {
egui::containers::menu::menu_style(style);
style.spacing.scroll = list_scroll_style();
});
// The id of the list's scroll area. egui senses its vertical bar under the area's id with the
// axis, 1, and names the widget a click went to at the start of the pass.
let area_key = id.with("scroll-area-id");
let on_bar =
ctx.data(|d| d.get_temp::<egui::Id>(area_key)).is_some_and(|area| ctx.interaction_snapshot(|s| s.clicked == Some(area.with(1_usize))));
let close = if on_bar { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick };
let popup = egui::Popup::menu(button).id(id).width(button.rect.width()).style(style.clone()).close_behavior(close);
let screen = ctx.content_rect();
// The list stops above the bottom bars, as other menus do (#2086).
let floor = menu_floor(ctx).min(screen.bottom());
// The room on each side of the rect the popup opens from: the part of the button in view.
let anchor = popup.get_anchor_rect().unwrap_or(button.rect);
let below = floor - anchor.bottom();
let above = anchor.top() - screen.top();
// The list's size from its last pass: egui lays a popup out unseen on the pass it opens, so the
// list is measured before it is placed. A right-to-left layout lines the list up with the
// button's right edge, as egui's menus do.
let rtl = ui.style().right_to_left;
let expected = popup.get_expected_size();
let (align, popup) = match expected {
Some(size) if size.y > below && size.y <= above => (if rtl { egui::RectAlign::TOP_END } else { egui::RectAlign::TOP_START }, popup),
// A list too tall for either side moves up from below until it ends at the floor.
Some(size) if size.y > below => {
let top = (floor - size.y).max(screen.top());
let from = Rect::from_min_max(egui::pos2(anchor.left(), top), egui::pos2(anchor.right(), top));
(if rtl { egui::RectAlign::BOTTOM_END } else { egui::RectAlign::BOTTOM_START }, popup.anchor(from))
}
_ => (if rtl { egui::RectAlign::BOTTOM_END } else { egui::RectAlign::BOTTOM_START }, popup),
};
let mut popup_style = (*ctx.global_style()).clone();
style.apply(&mut popup_style);
let margins = egui::Frame::popup(&popup_style).total_margin().sum();
let height = (floor - screen.top() - margins.y).max(ui.spacing().interact_size.y);
// A list that was wider than the window keeps its scroll bar in view: until it closes, it is no
// wider than it measured or than the window, its names cut short and shown in full on hover.
// Only a size measured while the list is open counts: egui keeps the last one after it closes.
// The width it needs is its rows' width on the last pass before it was narrowed, with its
// margins, and the bar's column while the rows scroll.
let too_wide_key = id.with("too-wide");
let natural_key = id.with("natural-width");
let scrolls_key = id.with("scrolls");
let open_last_pass = ctx.read_response(id).is_some();
if popup.get_expected_size().is_some_and(|size| open_last_pass && size.x > screen.width()) {
// The first measurement is kept: later ones are of the list already narrowed.
ctx.data_mut(|d| {
if d.get_temp::<f32>(too_wide_key).is_none() {
let rows = d.get_temp::<f32>(natural_key).unwrap_or(screen.width());
d.insert_temp(too_wide_key, rows);
}
});
}
let (measured, scrolls) = ctx.data(|d| (d.get_temp::<f32>(too_wide_key), d.get_temp::<bool>(scrolls_key).unwrap_or(false)));
let too_wide = measured.is_some();
let shown = popup.align(align).align_alternatives(&[]).show(|ui| {
if let Some(rows) = measured {
let bar = if scrolls { list_scroll_style().allocated_width() } else { 0.0 };
ui.set_max_width((rows + bar).min(screen.width() - margins.x).max(0.0));
}
ui.set_min_width(ui.available_width());
// A popup offers its contents the height it had on its last pass; the list is offered the
// window's instead.
ui.set_max_height(height);
// Labels widen a narrow list rather than wrap, as in egui's combo box.
ui.style_mut().wrap_mode = Some(if too_wide { egui::TextWrapMode::Truncate } else { egui::TextWrapMode::Extend });
let painted = ui.ctx().graphics(|g| g.get(ui.layer_id()).map_or(0, |shapes| shapes.all_entries().len()));
let shown = egui::ScrollArea::vertical().max_height(height).show(ui, list);
if too_wide {
show_shortened_rows(ui, painted);
}
ui.data_mut(|d| {
if !too_wide {
d.insert_temp(natural_key, shown.content_size.x);
}
d.insert_temp(scrolls_key, shown.content_size.y > shown.inner_rect.height());
d.insert_temp(area_key, shown.id);
});
shown.inner
});
if shown.is_some() {
ctx.accesskit_node_builder(id, |node| node.set_role(egui::Role::ListBox));
} else {
ctx.data_mut(|d| {
d.remove::<f32>(too_wide_key);
d.remove::<f32>(natural_key);
d.remove::<bool>(scrolls_key);
});
}
shown.map(|r| r.inner)
}
/// The shapes painted so far in this pass on the topmost popup that was shown in the last one, such
/// as an open dropdown list, without what lies under it. Read at the end of a test's UI.
#[cfg(test)]
pub(crate) fn top_popup_shapes(ctx: &egui::Context) -> Vec<egui::epaint::ClippedShape> {
let top = ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last());
top.map_or_else(Vec::new, |layer| ctx.graphics(|g| g.get(layer).map(|p| p.all_entries().cloned().collect()).unwrap_or_default()))
}
/// The recessed combo box of [`dropdown`] showing `current`, whose menu keeps a search field and
/// filters in place over a list that scrolls (the font menu and the shortcut import's target
/// picker, #555). `menu` shows the menu with one of [`craft_ui::combo::Menu`]'s header forms and
+524 -5
View File
@@ -133,10 +133,13 @@ fn a_dropdown_in_a_short_window_opens_with_its_current_option_in_view() {
for (height, above, current) in [(260.0, 117.0, 19), (260.0, 117.0, 10), (180.0, 77.0, 10), (180.0, 77.0, 3)] {
let ctx = themed(Default::default());
let field = std::cell::Cell::new(Rect::NOTHING);
let popup = std::cell::RefCell::new(vec![]);
let mut add = |ui: &mut Ui| {
ui.add_space(above);
field.set(ui.horizontal(|ui| dropdown_names(ui, "short-list", labels[current], &labels, 160.0)).response.rect);
popup.replace(super::top_popup_shapes(ui.ctx()));
};
// The shapes of the open list, without the field under it.
let mut run = |time: f64, events: Vec<egui::Event>| {
let raw = egui::RawInput {
time: Some(time),
@@ -146,7 +149,7 @@ fn a_dropdown_in_a_short_window_opens_with_its_current_option_in_view() {
};
let mut out = ctx.run_ui(raw, &mut add);
out.textures_delta.clear();
out.shapes
popup.take()
};
run(0.0, vec![]);
let at = field.get().center();
@@ -206,6 +209,7 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) {
let ctx = themed(Default::default());
let field = std::cell::Cell::new(Rect::NOTHING);
let current = std::cell::RefCell::new(String::from("Row 00"));
let popup = std::cell::RefCell::new(vec![]);
let mut add = |ui: &mut Ui| {
ui.add_space(above);
let shown = current.borrow().clone();
@@ -224,8 +228,10 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) {
current.replace(items[i].clone());
}
field.set(r.response.rect);
popup.replace(super::top_popup_shapes(ui.ctx()));
};
let mut time = 0.0;
// The shapes of the open list, without the field under it.
let mut run = |events: Vec<egui::Event>| {
time += 0.1;
let raw = egui::RawInput {
@@ -236,7 +242,7 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) {
};
let mut out = ctx.run_ui(raw, &mut add);
out.textures_delta.clear();
out.shapes
popup.take()
};
// The rows that show whole, with their tops: inside the open list and the clip they are painted
// in.
@@ -298,10 +304,12 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) {
}
let scrolled = rows(clipped);
assert!(has(&scrolled, row), "{case}: the wheel scrolls {row} into view: {scrolled:?}");
// Closed and opened again twice: each time its rows are where they were when it closed.
// Closed and opened again twice: each time its rows are where they were when it closed. Escape
// closes it: a list taller than the room beside its field covers the field.
let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
for time in ["first", "second"] {
run(vec![egui::Event::PointerMoved(at), press(true)]);
run(vec![press(false)]);
run(vec![escape(true)]);
run(vec![escape(false)]);
run(vec![]);
let reopened = rows(open(&mut run));
assert_eq!(reopened, scrolled, "{case}: the list opens again where it was scrolled, the {time} time");
@@ -804,6 +812,517 @@ fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() {
}
}
/// Long dropdown lists use the window's room instead of stopping at `combo_height` (200 pt), and
/// show a solid scroll bar without hovering when the list still overflows.
#[test]
fn a_long_dropdown_uses_window_room_and_shows_its_scroll_bar_when_clipped() {
let items: Vec<String> = (0..20).map(|i| format!("Format {i:02}")).collect();
let labels: Vec<&str> = items.iter().map(String::as_str).collect();
let run = |win_h: f32| {
let ctx = themed(Default::default());
let button_rect = std::cell::Cell::new(Rect::NOTHING);
let mut draw = |ui: &mut Ui| {
ui.add_space(16.0);
ui.horizontal(|ui| {
ui.add_space(16.0);
let before = ui.next_widget_position();
let _ = dropdown_names(ui, "long-formats", labels[0], &labels, 160.0);
button_rect.set(Rect::from_min_size(before, vec2(160.0, 26.0)));
});
};
let mut step = |time: f64, events: Vec<egui::Event>| {
let raw = egui::RawInput {
time: Some(time),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, win_h))),
events,
..Default::default()
};
let mut out = ctx.run_ui(raw, &mut draw);
out.textures_delta.clear();
out.shapes
};
step(0.0, vec![]);
let at = button_rect.get().center();
let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
step(0.1, vec![egui::Event::PointerMoved(at), click(true)]);
step(0.2, vec![click(false)]);
// Move the pointer away so the scroll bar is dormant, not hovered, and let the popup settle.
step(0.3, vec![egui::Event::PointerMoved(pos2(350.0, 10.0))]);
let mut clipped = vec![];
for i in 4..10 {
clipped = step(f64::from(i) * 0.1, vec![]);
}
(ctx, clipped)
};
// In a tall window, all 20 items show without stopping at the 200 pt cap.
let (_tall_ctx, tall_shapes) = run(720.0);
let mut texts = vec![];
fn collect_text(s: &egui::Shape, out: &mut Vec<String>) {
match s {
egui::Shape::Vec(v) => v.iter().for_each(|s| collect_text(s, out)),
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
_ => {}
}
}
for c in &tall_shapes {
collect_text(&c.shape, &mut texts);
}
assert!(texts.iter().any(|t| t == "Format 19"), "the 20th option is shown without scrolling: {texts:?}");
// In a short window where the list overflows, a solid scroll bar is drawn even while dormant.
let (short_ctx, short_shapes) = run(220.0);
let mut short_texts = vec![];
for c in &short_shapes {
collect_text(&c.shape, &mut short_texts);
}
assert!(!short_texts.iter().any(|t| t == "Format 19"), "the list overflows the 220 pt window");
let popup = short_ctx
.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)))
.expect("the popup is open");
let mut bar_rects = vec![];
fn collect_rects(s: &egui::Shape, out: &mut Vec<egui::epaint::RectShape>) {
match s {
egui::Shape::Vec(v) => v.iter().for_each(|s| collect_rects(s, out)),
egui::Shape::Rect(r) => out.push(r.clone()),
_ => {}
}
}
for c in &short_shapes {
collect_rects(&c.shape, &mut bar_rects);
}
let has_scroll_bar = bar_rects.iter().any(|r| {
r.fill != Color32::TRANSPARENT
&& r.rect.width() <= list_scroll_style().bar_width + 1.0
&& r.rect.height() >= 12.0
&& r.rect.height() < popup.height()
&& r.rect.right() <= popup.right()
&& r.rect.left() >= popup.right() - list_scroll_style().allocated_width() - 8.0
});
assert!(has_scroll_bar, "the overflowing dropdown draws its scroll bar without hover in {popup:?}");
}
// #5941: a drop-down list stopped at the room on one side of its field, so a window with room for
// the whole list still cut it short. The list opens below its field when it fits there, above it
// when it fits there instead, and otherwise moves up from below into the window over its field;
// each time every option shows whole, inside the window.
#[test]
fn a_dropdown_list_shows_every_option_when_the_window_has_room() {
let items: Vec<String> = (0..20).map(|i| format!("Option {i:02}")).collect();
let labels: Vec<&str> = items.iter().map(String::as_str).collect();
// (window height, space above the field, where the list goes)
for (height, above, side) in [(700.0, 16.0, "below"), (700.0, 650.0, "above"), (640.0, 300.0, "over")] {
let case = format!("{height} pt window, field {above} pt down");
let ctx = themed(Default::default());
let field = std::cell::Cell::new(Rect::NOTHING);
let popup = std::cell::RefCell::new(vec![]);
let mut add = |ui: &mut Ui| {
ui.add_space(above);
field.set(ui.horizontal(|ui| dropdown_names(ui, "fit-list", labels[0], &labels, 160.0)).response.rect);
popup.replace(super::top_popup_shapes(ui.ctx()));
};
let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, height));
// The shapes of the open list, without the field under it.
let mut run = |time: f64, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add);
out.textures_delta.clear();
popup.take()
};
run(0.0, vec![]);
let at = field.get().center();
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(0.1, vec![egui::Event::PointerMoved(at), press(true)]);
run(0.2, vec![press(false)]);
run(0.3, vec![egui::Event::PointerMoved(pos2(390.0, 2.0))]);
let mut clipped = vec![];
for i in 4..10 {
clipped = run(f64::from(i) * 0.1, vec![]);
}
let list = ctx
.memory(|m| {
m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))
})
.expect("the list is open");
assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window");
let field = field.get();
// The list opens from the button, 1 pt inside the field's border.
match side {
"below" => assert!(list.top() >= field.bottom() - 1.5, "{case}: the list {list:?} opens below the field {field:?}"),
"above" => assert!(list.bottom() <= field.top() + 1.5, "{case}: the list {list:?} opens above the field {field:?}"),
_ => assert!(list.top() < field.bottom() && list.bottom() > field.top(), "{case}: the list {list:?} covers the field {field:?}"),
}
let mut texts = vec![];
fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) {
match s {
egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out)),
egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), clip)),
_ => {}
}
}
clipped.iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts));
let whole: Vec<&str> = labels
.iter()
.copied()
.filter(|name| {
texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom())
})
.collect();
assert_eq!(whole, labels, "{case}: every option shows whole in {list:?}");
}
}
// #5941: a drop-down list stops above the bottom bars, as other menus do (#2086). In a 700 pt window
// whose bars start at 640 pt, the list opens below a field near the top, and from a field in the
// middle it moves up over the field until it ends at the bars; each time every option shows whole.
#[test]
fn a_dropdown_list_stops_above_the_bottom_bars() {
let items: Vec<String> = (0..20).map(|i| format!("Option {i:02}")).collect();
let labels: Vec<&str> = items.iter().map(String::as_str).collect();
let floor = 640.0;
for above in [16.0, 300.0] {
let case = format!("field {above} pt down");
let ctx = themed(Default::default());
let field = std::cell::Cell::new(Rect::NOTHING);
let popup = std::cell::RefCell::new(vec![]);
let mut add = |ui: &mut Ui| {
set_menu_floor(ui.ctx(), floor);
ui.add_space(above);
field.set(ui.horizontal(|ui| dropdown_names(ui, "floor-list", labels[0], &labels, 160.0)).response.rect);
popup.replace(super::top_popup_shapes(ui.ctx()));
};
let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 700.0));
let mut run = |time: f64, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add);
out.textures_delta.clear();
popup.take()
};
run(0.0, vec![]);
let at = field.get().center();
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(0.1, vec![egui::Event::PointerMoved(at), press(true)]);
run(0.2, vec![press(false)]);
run(0.3, vec![egui::Event::PointerMoved(pos2(390.0, 2.0))]);
let mut clipped = vec![];
for i in 4..10 {
clipped = run(f64::from(i) * 0.1, vec![]);
}
let list = ctx
.memory(|m| {
m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))
})
.expect("the list is open");
assert!(list.top() >= 0.0 && list.bottom() <= floor + 0.5, "{case}: the list {list:?} ends above the bars at {floor}");
let mut texts = vec![];
fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) {
match s {
egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out)),
egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), clip)),
_ => {}
}
}
clipped.iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts));
let whole: Vec<&str> = labels
.iter()
.copied()
.filter(|name| {
texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom())
})
.collect();
assert_eq!(whole, labels, "{case}: every option shows whole in {list:?}");
}
}
// #5941: a click on the scroll bar's track of an open drop-down list scrolls it and leaves it open,
// so an option it scrolled into view can be picked. A list closed by that click would open again
// with its current option in view.
#[test]
fn a_click_on_a_dropdown_lists_scroll_bar_scrolls_it_and_leaves_it_open() {
let items: Vec<String> = (0..40).map(|i| format!("Option {i:02}")).collect();
let labels: Vec<&str> = items.iter().map(String::as_str).collect();
let ctx = themed(Default::default());
let field = std::cell::Cell::new(Rect::NOTHING);
let picked = std::cell::Cell::new(None);
let popup = std::cell::RefCell::new(vec![]);
let mut add = |ui: &mut Ui| {
ui.add_space(16.0);
let r = ui.horizontal(|ui| dropdown_names(ui, "bar-click", labels[0], &labels, 160.0));
field.set(r.response.rect);
if let Some(i) = r.inner {
picked.set(Some(i));
}
popup.replace(super::top_popup_shapes(ui.ctx()));
};
let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0));
let mut time = 0.0;
// The options that show whole on the open list, with their rects, and the scroll bar's rects.
let mut run = |events: Vec<egui::Event>| {
time += 0.1;
let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add);
out.textures_delta.clear();
let (mut texts, mut bars) = (vec![], vec![]);
fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect)>, bars: &mut Vec<Rect>) {
match s {
egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out, bars)),
egui::Shape::Text(t) => {
let r = t.visual_bounding_rect();
if r.top() >= clip.top() && r.bottom() <= clip.bottom() {
out.push((t.galley.text().to_owned(), r));
}
}
egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect),
_ => {}
}
}
popup.take().iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts, &mut bars));
(texts, bars)
};
let list_rect = || {
ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)))
};
let click =
|at: Pos2, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(vec![]);
let at = field.get().center();
run(vec![egui::Event::PointerMoved(at), click(at, true)]);
run(vec![click(at, false)]);
let (mut before, mut bars) = (vec![], vec![]);
for _ in 0..4 {
(before, bars) = run(vec![]);
}
assert!(list_rect().is_some(), "the list is open");
assert!(before.iter().any(|(s, _)| s == "Option 00"), "the list opens at its first option: {before:?}");
// The track, below the handle: near the bottom of the tallest bar rect drawn (the track).
let bar = bars
.iter()
.copied()
.max_by(|a, b| a.height().total_cmp(&b.height()))
.unwrap_or_else(|| panic!("the list {:?} draws its scroll bar: {before:?}", list_rect()));
let track = pos2(bar.center().x, bar.bottom() - 6.0);
run(vec![egui::Event::PointerMoved(track), click(track, true)]);
run(vec![]);
// The button is let go just past the bar's edge, closer than a drag, and the pointer then moves
// sideways onto the rows, in the same pass.
let let_go = pos2(bar.right() + 1.0, track.y);
let onto_row = before.first().map(|(_, r)| pos2(r.center().x, track.y)).expect("a row shows");
run(vec![egui::Event::PointerMoved(let_go), click(let_go, false), egui::Event::PointerMoved(onto_row)]);
let mut after = vec![];
for _ in 0..4 {
(after, _) = run(vec![]);
}
assert!(list_rect().is_some(), "a click on the scroll bar leaves the list open");
let new = after
.iter()
.find(|(s, _)| !before.iter().any(|(b, _)| b == s))
.cloned()
.unwrap_or_else(|| panic!("the click scrolled options into view: {after:?}"));
let row = new.1.center();
run(vec![egui::Event::PointerMoved(row), click(row, true)]);
run(vec![click(row, false)]);
run(vec![]);
let index = labels.iter().position(|l| *l == new.0);
assert_eq!(picked.get(), index, "the option scrolled into view is picked: {}", new.0);
assert!(list_rect().is_none(), "picking an option closes the list");
}
// #5941: a drop-down list with an option wider than the window ran past the window's right edge,
// and its scroll bar with it. The list stays inside the window and its bar shows; the long option's
// name is cut short.
#[test]
fn a_dropdown_list_wider_than_the_window_keeps_its_scroll_bar_in_view() {
let mut items: Vec<String> = (0..40).map(|i| format!("Option {i:02}")).collect();
items[1] = "Option 01, whose name is much wider than this window".into();
let labels: Vec<&str> = items.iter().map(String::as_str).collect();
let short: Vec<&str> = labels.iter().copied().filter(|l| l.len() < 10).collect();
let two: Vec<&str> = labels[..2].to_vec();
// Which list the field offers: 0 all, 1 the short names, 2 the first two.
let offered = std::cell::Cell::new(0);
let ctx = themed(Default::default());
let field = std::cell::Cell::new(Rect::NOTHING);
let popup = std::cell::RefCell::new(vec![]);
let mut add = |ui: &mut Ui| {
ui.add_space(16.0);
let options = [&labels, &short, &two][offered.get()];
field.set(ui.horizontal(|ui| dropdown_names(ui, "wide-list", options[0], options, 160.0)).response.rect);
popup.replace(super::top_popup_shapes(ui.ctx()));
};
let screen = Rect::from_min_size(Pos2::ZERO, vec2(220.0, 300.0));
let window = std::cell::Cell::new(screen);
let mut time = 0.0;
// The texts painted on the open list with their clip rects, and the scroll bar's rects.
let mut run = |events: Vec<egui::Event>| {
time += 0.1;
let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(window.get()), events, ..Default::default() }, &mut add);
out.textures_delta.clear();
let (mut texts, mut bars) = (vec![], vec![]);
fn flat(s: &egui::Shape, clip: Rect, texts: &mut Vec<(String, bool)>, bars: &mut Vec<Rect>) {
match s {
egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, texts, bars)),
egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.galley.elided)),
egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect.intersect(clip)),
_ => {}
}
}
popup.take().iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts, &mut bars));
(texts, bars)
};
run(vec![]);
let at = field.get().center();
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(vec![egui::Event::PointerMoved(at), press(true)]);
run(vec![press(false)]);
run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]);
let (mut texts, mut bars) = (vec![], vec![]);
for _ in 0..6 {
(texts, bars) = run(vec![]);
}
let list_rect = || {
ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)))
};
let list = list_rect().expect("the list is open");
assert!(screen.contains_rect(list), "the list {list:?} is inside the window");
assert!(
bars.iter().any(|b| b.width() > 0.0 && screen.contains_rect(*b) && list.contains_rect(*b)),
"the bar shows in the list {list:?}: {bars:?}"
);
assert!(texts.iter().any(|(s, elided)| *elided && s.starts_with("Option 01")), "the long name is cut short: {texts:?}");
// The window grows while the list is open: the list grows as wide as its names need, and no
// wider.
window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0)));
for _ in 0..6 {
(texts, _) = run(vec![]);
}
let grown = list_rect().expect("the list is still open");
assert!(grown.width() < 500.0, "the list {grown:?} stays as wide as its names need");
assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full: {texts:?}");
// Narrowed and widened again, it comes back to the same width.
for size in [screen.size(), vec2(1000.0, 300.0)] {
window.set(Rect::from_min_size(Pos2::ZERO, size));
for _ in 0..6 {
run(vec![]);
}
}
let again = list_rect().expect("the list is still open");
assert!((again.width() - grown.width()).abs() < 0.5, "the list is as wide as before: {again:?}, {grown:?}");
// Closed, the window narrowed again and the long option gone: the list opens as narrow as its
// names, not as wide as the window.
let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
run(vec![escape(true)]);
run(vec![escape(false)]);
assert!(list_rect().is_none(), "Escape closes the list");
window.set(screen);
offered.set(1);
run(vec![]);
let at = field.get().center();
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(vec![egui::Event::PointerMoved(at), press(true)]);
run(vec![press(false)]);
run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]);
let mut widths = vec![];
for _ in 0..4 {
run(vec![]);
widths.push(list_rect().expect("the list is open").width());
}
assert!(widths.iter().all(|w| *w < 180.0), "the list of short names stays narrow: {widths:?}");
// Opened in a wide window, narrowed and widened again: it comes back to the width it opened at,
// the long list that scrolls and a list of two that does not.
for (which, count) in [(0, "40"), (2, "2")] {
run(vec![escape(true)]);
run(vec![escape(false)]);
offered.set(which);
window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0)));
run(vec![]);
run(vec![egui::Event::PointerMoved(at), press(true)]);
run(vec![press(false)]);
run(vec![egui::Event::PointerMoved(pos2(990.0, 290.0))]);
for _ in 0..6 {
run(vec![]);
}
let opened = list_rect().expect("the list is open");
for size in [screen.size(), vec2(1000.0, 300.0)] {
window.set(Rect::from_min_size(Pos2::ZERO, size));
for _ in 0..6 {
run(vec![]);
}
}
let restored = list_rect().expect("the list is still open");
// Within the half point that egui rounds a popup's position to.
assert!((restored.width() - opened.width()).abs() < 0.5, "{count} options: the list is as wide as it opened: {restored:?}, {opened:?}");
}
// Opened in a narrow window tall enough for every option, then made wide and short: the list
// scrolls now, and its bar's column comes on top of the long name, which shows in full.
run(vec![escape(true)]);
run(vec![escape(false)]);
offered.set(0);
window.set(Rect::from_min_size(Pos2::ZERO, vec2(220.0, 1400.0)));
run(vec![]);
run(vec![egui::Event::PointerMoved(at), press(true)]);
run(vec![press(false)]);
run(vec![egui::Event::PointerMoved(pos2(210.0, 1390.0))]);
for _ in 0..6 {
run(vec![]);
}
window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0)));
for _ in 0..6 {
(texts, _) = run(vec![]);
}
assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full beside the bar: {texts:?}");
}
// #5941: in a drop-down list narrowed to the window, an option whose name is cut short shows the
// full name in a tooltip while the pointer rests on it.
#[test]
fn a_dropdown_option_cut_short_shows_its_full_name_on_hover() {
let mut items: Vec<String> = (0..10).map(|i| format!("Option {i:02}")).collect();
items[1] = "Option 01, whose name is much wider than this window".into();
let labels: Vec<&str> = items.iter().map(String::as_str).collect();
let ctx = themed(Default::default());
let field = std::cell::Cell::new(Rect::NOTHING);
let mut add = |ui: &mut Ui| {
ui.add_space(16.0);
field.set(ui.horizontal(|ui| dropdown_names(ui, "hover-list", labels[0], &labels, 160.0)).response.rect);
};
let screen = Rect::from_min_size(Pos2::ZERO, vec2(220.0, 300.0));
let mut time = 0.0;
// Every text painted, on any layer, with its rect and whether it was cut short.
let mut run = |events: Vec<egui::Event>| {
time += 0.1;
let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add);
out.textures_delta.clear();
let mut texts = vec![];
fn flat(s: &egui::Shape, out: &mut Vec<(String, Rect, bool)>) {
match s {
egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, out)),
egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), t.galley.elided)),
_ => {}
}
}
out.shapes.iter().for_each(|c| flat(&c.shape, &mut texts));
texts
};
run(vec![]);
let at = field.get().center();
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(vec![egui::Event::PointerMoved(at), press(true)]);
run(vec![press(false)]);
run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]);
let mut texts = vec![];
for _ in 0..6 {
texts = run(vec![]);
}
let full = |texts: &[(String, Rect, bool)]| texts.iter().any(|(s, _, elided)| !*elided && s == labels[1]);
assert!(!full(&texts), "the long name is not shown in full before the hover: {texts:?}");
let row = texts
.iter()
.find(|(s, _, elided)| *elided && s.starts_with("Option 01"))
.map(|(_, r, _)| r.center())
.unwrap_or_else(|| panic!("the long name is cut short: {texts:?}"));
run(vec![egui::Event::PointerMoved(row)]);
for _ in 0..10 {
texts = run(vec![]);
}
assert!(full(&texts), "the full name shows on hover: {texts:?}");
}
/// Enter on text that reads as no number in a range field refuses it as a unit field does: the
/// field flashes and an open dialog is not confirmed with the old value.
#[test]
+44
View File
@@ -42,6 +42,10 @@ pub struct Workspace {
pub toolbar_compact: bool,
pub toolbar_advanced: bool,
pub task_bar: bool,
/// The Contextual Task Bar's actions and chips its Bar Actions has off (built-in workspaces, and
/// workspaces saved without this field: none).
#[serde(skip_serializing_if = "std::collections::BTreeSet::is_empty", deserialize_with = "crate::canvas::read_hidden_task_bar_actions")]
pub task_bar_hidden_actions: std::collections::BTreeSet<String>,
pub dock: bool,
pub dock_tab: DockTab,
/// The dock's tabbed group is collapsed to icons (built-in workspaces: expanded).
@@ -208,6 +212,7 @@ pub fn capture(ui: &UiState, name: &str) -> Workspace {
toolbar_compact: ui.toolbar_compact,
toolbar_advanced: ui.toolbar_advanced,
task_bar: ui.task_bar,
task_bar_hidden_actions: ui.task_bar_hidden_actions.clone(),
dock: ui.dock,
dock_tab: ui.dock_tab,
dock_collapsed: ui.dock_collapsed,
@@ -247,6 +252,7 @@ pub fn apply(ui: &mut UiState, w: &Workspace) {
ui.toolbar_compact = w.toolbar_compact;
ui.toolbar_advanced = w.toolbar_advanced;
ui.task_bar = w.task_bar;
ui.task_bar_hidden_actions = w.task_bar_hidden_actions.clone();
ui.dock = w.dock;
ui.tab_hid = None;
ui.dock_tab = w.dock_tab;
@@ -949,4 +955,42 @@ mod tests {
let read: UiState = serde_json::from_value(prefs).unwrap();
assert!(read.control_bar_hidden_groups.is_empty(), "older preferences show every group");
}
/// A workspace keeps the Contextual Task Bar's actions its Bar Actions has off: switching
/// brings each workspace's back, Reset turns a built-in workspace's on again, and they survive
/// the preferences' JSON. A workspace saved without them, or with ids the bar does not have,
/// shows every action, or the ones it names that the bar has.
#[test]
fn saved_workspaces_restore_the_task_bar_actions() {
let hidden = |ids: &[&str]| ids.iter().map(|s| s.to_string()).collect::<std::collections::BTreeSet<String>>();
let mut ui = UiState { task_bar_hidden_actions: hidden(&["duplicate", "fill"]), ..Default::default() };
save_as(&mut ui, "Lean").unwrap();
switch(&mut ui, ESSENTIALS).unwrap();
assert!(ui.task_bar_hidden_actions.is_empty(), "Essentials shows every action");
ui.task_bar_hidden_actions = hidden(&["simplify"]);
switch(&mut ui, "Lean").unwrap();
assert_eq!(ui.task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "the saved workspace's actions");
switch(&mut ui, ESSENTIALS).unwrap();
assert_eq!(ui.task_bar_hidden_actions, hidden(&["simplify"]), "Essentials as it was left");
reset(&mut ui);
assert!(ui.task_bar_hidden_actions.is_empty(), "Reset Essentials shows every action again");
switch(&mut ui, "Lean").unwrap();
let json = serde_json::to_value(&ui).unwrap();
assert_eq!(json["custom_workspaces"][0]["taskBarHiddenActions"], serde_json::json!(["duplicate", "fill"]));
let back: UiState = serde_json::from_value(json).unwrap();
assert_eq!(back.task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "kept in the preferences");
assert_eq!(back.custom_workspaces[0].task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "kept with the workspace");
let mut old = serde_json::to_value(&back.custom_workspaces[0]).unwrap();
assert!(old.as_object_mut().unwrap().remove("taskBarHiddenActions").is_some());
let old: Workspace = serde_json::from_value(old).unwrap();
apply(&mut ui, &old);
assert!(ui.task_bar_hidden_actions.is_empty(), "an older workspace shows every action");
let mut prefs = serde_json::to_value(&back).unwrap();
prefs["custom_workspaces"][0]["taskBarHiddenActions"] = serde_json::json!(["fill", "teleport", 3]);
let read: UiState = serde_json::from_value(prefs.clone()).unwrap();
assert_eq!(read.custom_workspaces[0].task_bar_hidden_actions, hidden(&["fill"]), "ids the bar does not have are dropped");
prefs["custom_workspaces"][0]["taskBarHiddenActions"] = serde_json::json!("fill");
let read: UiState = serde_json::from_value(prefs).unwrap();
assert!(read.custom_workspaces[0].task_bar_hidden_actions.is_empty(), "a value that is not a list shows every action");
}
}
+3
View File
@@ -276,6 +276,9 @@ point (the first stop or point when none is selected). `ui.colorWheel {view?, ch
shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, shows the
other colors of a harmony rule as markers on the wheel's ring, and shows or hides the color vision row; it returns
the settings, and `ui.inspect` reports them as `ui.color_wheel`.
The key `sliders` shows OKLCH Sliders, HSL Sliders or
neither (`"oklch"`, `"hsl"` or `"none"`; `"oklch"` is an error while the active document's RGB space, its assigned
profile or else the working RGB space, is not sRGB), and the settings carry it too.
Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/
`global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`,
+2
View File
@@ -144,6 +144,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall
macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate.
- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain.
- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged.
- **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged.
+89 -10
View File
@@ -689,6 +689,17 @@ each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, `
`highContrast2`). Keys left out keep their values. Params that are not an object, another key or a value off
the list return an error and change nothing. The command returns `{view, channel, harmony, harmonyRule, vision}`,
and the settings are kept with the preferences.
`ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or
the box), and `"none"` hides them in any RGB space. `"oklch"` is an error while the active document's RGB space is
not sRGB: the profile assigned to the document when it has one, else the working RGB space of Edit › Color Settings.
`ui.colorWheel {"sliders": "hsl"}` shows HSL Sliders in their place: H, S and L rows with the hue (0 to 360°),
saturation and lightness (0 to 100 %) of the color's display sRGB, as CSS Color 4's `hsl()` defines them.
`color.convert {"color": "#ff0000", "to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB.
A color outside sRGB (a Lab or CMYK color, an RGB color in a wider RGB space, or RGB numbers past 0 to 1) is clipped
to sRGB first.
The answer of `ui.colorWheel` and the settings also carry `sliders`.
`ui.colorWheel {"vision": true}` turns on the Color Wheel panel's Show Color Vision Preview, as its panel menu
does: a row of four chips under the wheel or the box shows the current color through the protanopia, deuteranopia
and tritanopia simulations of `view.proofSetup`, and for achromatopsia as the gray with the color's CIE L*. Each
@@ -825,6 +836,35 @@ from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100
`` `baseAlong` must be one of x, y ``), as is a `slope` outside its range; the arc is not drawn and no undo step is
added.
`shape.threePointArc {start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: "start"|"end"}` draws an
open circular arc from `start` to `end` and selects it. With `through`, the arc passes through that point. With
`toward`, the arc leaves `start` heading toward that point, so the line from `start` to the point is the arc's tangent
there. With `at: "end"`, the line from `end` to the point is the tangent at `end` instead. `at` is `"start"` when left
out, and `at` with `through` is an error. The arc has no fill and the current stroke (black when the stroke is none),
its ends are exactly the two points (it is not pixel-aligned), and it has a smooth anchor at the `through` point and
further smooth anchors so that no curve of the path turns more than a quarter turn. The result is
`{id, cx, cy, radius, sweep}`: the circle's center and radius, and the arc's turn in degrees, positive clockwise on the
page. One undo removes the arc. The command returns an error and draws nothing when two of the points are the same,
when the third point lies on the line through the ends, when the arc would reach past the canvas, when a point is not
`[x, y]`, when both or neither of `through` and `toward` are given, when `at` is anything but `"start"` or `"end"`, and
when `at` is given with `through`.
The Three-Point Arc tool, in the Line Segment tool's group after the Arc tool, runs this command. A drag from one end to
the other, or a click on each, places the ends; Shift keeps the second end at 45° steps from the first (from General ›
Constrain Angle). A click on a third point, or a press dragged to it, then draws the arc through it. With the tool's
`direction` option on, the third point gives the direction the arc leaves the first end in; with `mods.alt`, the
direction is at the second end, and Shift keeps the direction at 45° steps. Three-Point Arc Tool Options (`tool.options`,
or a double-click on the tool) sets `direction` with its Third Point Sets Direction box, and
`]` (with or without Shift) switches it while the ends are placed; the option is saved with the preferences. Until the
third point is placed, the tool shows the arc as a dashed outline, its center as a small cross, the direction line in
direction mode and, with Measurement Labels on, the radius. Where no arc fits, the tool shows "Arc too large" by the
pointer (nothing while the pointer is on an end), and a click there draws nothing and keeps the ends. Escape, and an
edit, Undo or Redo made outside the tool, remove the ends.
```json
{"name":"run_command","arguments":{"command":"shape.threePointArc","params":{"start":[0,0],"end":[80,0],"through":[40,-40]}}}
```
While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the
spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows
the pointer. With `mods.alt` alone, dragging outward adds whole winds of four segments and dragging inward removes
@@ -2306,7 +2346,7 @@ naming the key, and leave the document and its undo history as they were: `opaci
The blend and envelope commands refuse a string, a number or another value that is not true or false with
`` `smooth` must be true or false ``, naming the key, and leave the document, its undo history and the options new
blends and envelopes start with as they were: `smooth` in `object.blend.make` and `object.blend.options`;
`independent` and `link` in `object.blend.spine.moveAnchor`; `perpendicular` in `object.blend.spine.reshapeSegment`; `horizontal`
`independent`, `symmetric` and `link` in `object.blend.spine.moveAnchor`; `perpendicular` in `object.blend.spine.reshapeSegment`; `horizontal`
in `object.envelope.makeWithWarp`, `resetWithWarp` and `options`, also when an `orientation` is given; `maintainShape`
in `object.envelope.resetWithMesh`; `antiAlias`, `distortAppearance`, `distortLinearGradients` and
`distortPatternFills` in `object.envelope.options`; and `editing` in `object.envelope.editContents`. A null is read as
@@ -5724,7 +5764,10 @@ Brushes with one bristle brush for each tip shape, Pattern Borders, Decorative w
Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, Engraving with Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching art brushes, id `engraving`, and Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`), the `.vectorcraft` files in the user library folder of the desktop app (User
Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has
the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and
`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name).
`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). A name
that a built-in library and a User Defined or loaded library share selects the built-in one; select the other by its
`user/…` or `loaded/…` id. The exact id `artistic` selects the built-in Artistic Brushes library, and `Artistic`
selects it too when no library is named `Artistic`.
`brush.addFromLibrary {library, name? | names?}` copies brushes into the document's Brushes as one undo step (no
names: the whole library), with the resources their art uses: patterns, symbols, swatches (`swatchConflict` as for
`edit.paste`), graphic styles and images. Brushes the document already has (same name and definition) are reported
@@ -6718,6 +6761,14 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a
an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded.
`path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that
keeps its kind, leave the document as it is and record no undo step.
`path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same
length, and the anchor keeps its kind. At an open end, where no segment leaves the anchor on the other side,
`symmetric` has no effect and the handle moves as it would without it. Both `symmetric` and `independent` default to false, and a call with both true is
refused with `` `independent` and `symmetric` cannot both be true ``; the document does not change and no undo step
is recorded. Direct Selection sends `symmetric` while Cmd/Ctrl is held during a handle drag, unless that Cmd/Ctrl
press lent Direct Selection for the gesture while another tool, such as the Pen, was chosen and has not been let go
since (#7842). A call that puts both handles where they already are records no undo step. `symmetric: true` with `link: true` is refused
("`link` and `symmetric` cannot both be true"), and so is `symmetric: true` with `link: true` in `object.blend.spine.moveAnchor`.
`path.setHandle` with `link: true` (the Anchor Point tool's Alt-drag on a handle) places the handle and makes the
anchor smooth: the other handle turns to lie in line on the far side of the anchor and keeps its length. A retracted
other handle is pulled out to the placed handle's length when a segment leaves the anchor on its side, and stays
@@ -6844,7 +6895,7 @@ Left out or null, `width` is 8 pt. The range is VectorCraft's own value.
These commands refuse a string, a number or another value that is not true or false with
`` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded:
`independent` in `path.close` and `path.setHandle`; `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and
`independent` in `path.close` and `path.setHandle`; `symmetric` and `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and
`fill` in `path.freehand` (and in `brush.freehand`); `closed` and the `corner` of a point in `path.curvature`; `corner`
in `path.curvatureEdit`; `perpendicular` in `path.reshapeSegment`; and `keepSelected`, `mergeOnlySelection` and
`merge` in `path.blob`. A null is read as a key left out.
@@ -8158,7 +8209,7 @@ snap the pointer as drawing tools do, so dragging a corner onto another object's
Every point a drawing tool places snaps the same way, through one snapper (#506): the Pen's and Curvature tool's
anchors, the shape tools' start and dragged corner or radius (`rectangle`,
`roundedRectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, `arc`, `spiral`, `rectangularGrid`, `polarGrid`), the
Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and
Three-Point Arc tool's ends and third point, the Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and
shows no Smart Guides: its strokes and straight lines follow the hand (Snap to Grid and Snap to Pixel still move
their ends). The point lands on another object's anchor, centre or
path ("anchor", "center", "path"), else lines up with the anchors, edges and centres of the art and the artboards (a
@@ -8572,6 +8623,27 @@ is kept with the preferences and with the workspace; a workspace or preferences
and a group id the bar does not have is dropped when they are read. Another `group`, or none, fails with "`group` must
be one of …", and a `visible` that is not true or false fails with "`visible` must be true or false"; either leaves
every group as it is. The groups and their contents are VectorCraft's own.
`window.taskBar.actions {action, visible?}` (desktop app) turns one of the Contextual Task Bar's actions or chips on
(`visible: true`), off (`false`) or toggles it (omitted or null), and returns `{action, visible}`. The actions are `imageTrace`,
`cropImage`, `removeBackground`, `removeAnchorPoints`, `join` (Connect and Join), `cutPath`, `convertToCorner`,
`convertToSmooth`, `group`, `makeClippingMask`, `unite`, `expand`, `editClippingPath`, `releaseClippingMask`,
`ungroup`, `isolate`, `editPath`, `releaseCompoundPath`, `createOutlines`, `convertToPointType`, `convertToAreaType`,
`typeOnPathOptions`, `centerOnTop`, `centerOnBottom`, `dynamicText`, `offsetPath`, `simplify`, `smooth`, `duplicate`,
`drawPencil`, `placeImage`, `fidelity` and `smoothToolOptions` (the Smooth tool's), and `resizeArtboard`,
`duplicateArtboards`, `rearrangeArtboards` and `exportArtboards` (the Artboard tool's); the chips are `fill`, `stroke`,
`recolor` (Recolor Artwork), `lock` and `shapeProperties` (a basic shape's Shape Properties, in Lock's place). The bar's
More Options menu has Bar Actions, which lists the actions and chips the bar offers for the current selection or tool,
each checked while it is on and named without a final colon or ellipsis, and runs the command for the one clicked. An
action or chip that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off
changes only the bar. With every action and chip it would offer off, the bar still shows its handle and More Options,
where Bar Actions turns them on again. Every action starts
on. The type font controls are not in Bar Actions and stay on the bar. Which actions are off is kept with the preferences
and with the workspace; a workspace or preferences saved without them show every action, and an id the bar does not have
is dropped when they are read. A `visible` of null toggles, as an omitted one does. Another `action`, or none, fails
with "`action` must be one of …", and a `visible` that is not true, false or null fails with "`visible` must be true
or false"; either leaves every action as it is.
`window.taskBar.resetActions {}` (More Options › Reset Bar Actions) turns every action and chip on again and returns
the ids it turned on. Choosing the bar's actions is VectorCraft's own.
```json
{"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}}
@@ -10003,7 +10075,11 @@ images and point type in the font the file names. Type keeps the file's characte
kerning off. On a single left to right line, an advance that tracking can't give (wider than its range, or a tab)
starts a new point type object at the position the advance gives, and an underline or strikethrough is filled across the space between and on to the end
of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and
split as a single line is. An EMF that
split as a single line is. A character cell runs from the font's OS/2
`usWinAscent` above the baseline to its `usWinDescent` below it: top and bottom aligned text has the top or the
bottom of its cells at the reference point. Text drawn in the opaque background mode, which a file is in until it
sets the mode to transparent, gets one filled rectangle of the background color behind the character cells of each
line, as far as its advances reach (NULs' included), placed before the type. An EMF that
draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning.
A file, or a metafile image inside it, cut short by one of the reader's limits adds one warning without a count.
Each of these adds one warning, with a count: images and pattern brushes whose bitmap can't be read, which are left
@@ -10854,10 +10930,12 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane
`text.reshapePath {id, anchors: [[subpath, anchor]…], dx, dy}` does the same for the path of type on a path
(Direct Selection dragging one of its anchors): the start and end brackets keep their fractions of the path and the
text reflows along it.
`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?}` moves a direction handle of one
of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in one
undo step. A call of `text.reshapeArea`, `text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and
`dy` both 0, or a handle moved to where it already is) adds no undo step and keeps redo.
`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?, symmetric?}` moves a direction handle
of one of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in
one undo step. With `symmetric: true` the other handle goes opposite the moved one at the same length, measured on
the page, as in `path.setHandle`; `symmetric` and `independent` cannot both be true. A call of `text.reshapeArea`,
`text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and `dy` both 0, or handles left where they
already are) adds no undo step and keeps redo.
```json
{"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}}
@@ -13518,7 +13596,8 @@ the compound path selected), and the next click starts a new path. Choosing any
A blend's spine is the straight lines between its key centres until it is edited. `object.blend.info` lists it
(`spine.anchors`, `keyAnchors`: the point each key sits on). `object.blend.spine.addAnchor {x, y}` adds a point where
the spine passes nearest, `object.blend.spine.moveAnchor {anchor, x, y}` moves a point (a key on it moves along; with
`handle: "in" | "out"` it places that handle), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment
`handle: "in" | "out"` it places that handle, and with `symmetric: true` also the other handle opposite it at the
same length, as `path.setHandle` does; `symmetric` needs `handle` and cannot go with `independent`), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment
so its point at `t` moves by (dx, dy), turning a straight spine into a curve (`perpendicular` works as in `path.reshapeSegment`), and `object.blend.spine.removeAnchor
{anchor}` deletes a point no key sits on; the first edit turns the spine into a path. Moving a key moves its end of the spine. Release
(`object.blend.release`) leaves the spine of a blend that has one as a path that paints nothing (`spines` in the result):
+7
View File
@@ -738,12 +738,14 @@ since 2026-10-01.
- **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests.
- **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged.
- **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=65>) says that moving the pointer around in a curve during the drag turns the new spiral, and the help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged.
- **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc and its center, and with Measurement Labels on its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged.
- **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged.
- **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged.
- **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged.
- **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged.
- **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`.
- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`.
- **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`.
- **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`.
- **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`.
@@ -1073,6 +1075,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The contextual task bar offers more next steps by selection (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html>): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, point or area type Convert To Area Type or Convert To Point Type beside Create Outlines, and type on a path, for which the overview names an item to add an effect and rearrange the text, Type on a Path Options (`type.pathOptions`; its options: <https://helpx.adobe.com/illustrator/using/creating-type-path.html>) beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`.
- While a Type tool (Type, Area Type, Type on a Path and their vertical versions) adds or edits type, the contextual task bar shows the font family menu, the font style menu, the Font Size combo and the Fill chip (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html>); the Touch Type tool shows no bar, as the same page describes. Type selected with a selection tool shows the same three font controls beside its Create Outlines, conversion and Type on a Path items (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html>). The controls act as the Character panel's do: on the characters a Type tool selects, else on every selected type object, with the size left blank where the sizes differ. VectorCraft's own rules: a Type tool's bar leaves out the object actions, the Stroke chip, Recolor Artwork and Lock; a Type tool shows no bar before it adds type or with other art selected; type selected with other art shows no font controls; the font controls go on a second row when one row would be wider than the canvas, and narrow to fit a canvas narrower than they are; while a Type tool edits type, the Fill chip shows the edited characters' fill ("?" where it differs). Evidence: `the_type_tools_show_font_and_fill_controls`, `the_type_tools_show_no_bar_without_type`, `selected_type_shows_font_controls_beside_its_actions`, `the_task_bars_font_size_sets_what_the_character_panel_would`, `the_type_tools_fill_chip_activates_the_fill`, `the_type_tools_bar_is_named_and_stays_on_the_canvas`, `selected_types_font_controls_take_a_second_row_on_a_narrow_canvas` and `the_type_tools_fill_chip_shows_the_edited_characters_fill` in `crates/ui-egui/src/tests/taskbar.rs`.
- The help page describes the contextual task bar as one horizontal row (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html>) and gives no rule for a canvas narrower than that row. VectorCraft's own rule: the bar stays whole on the canvas. When its actions don't fit in one row, they wrap, in order, onto rows under the row with the handle, the chips and More Options; an action wider than any row, or one that would need a row past the canvas's height, is listed in More Options instead; when the chips don't fit beside the handle and More Options, they take rows after the actions; with no row to spare for the font controls, the bar leaves them out; a canvas too small for the handle and More Options shows no bar. Evidence: `a_task_bars_actions_wrap_on_a_narrow_canvas` and `a_task_bar_action_wider_than_the_canvas_goes_in_more_options` in `crates/ui-egui/src/tests/taskbar.rs`.
- The contextual task bar's More Options menu has Bar Actions, which lists the actions and the Fill, Stroke, Recolor Artwork, Lock or Shape Properties chips the bar offers for the current selection or tool, each checked while it is on, and Reset Bar Actions, which turns every one on again (`window.taskBar.actions`, `window.taskBar.resetActions`). An action that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. With all of them off, the bar still shows its handle and More Options. The type font controls are not in Bar Actions. Which actions are off is kept with the preferences and with the workspace. Choosing the bar's actions is VectorCraft's own. Evidence: `an_action_turned_off_leaves_the_bar_and_stays_in_its_menu`, `an_action_turned_off_is_not_listed_in_more_options`, `every_action_the_bar_offers_can_be_turned_off`, `a_chip_turned_off_leaves_the_bar`, `reset_bar_actions_shows_every_action_again`, `bar_actions_are_kept_with_the_preferences`, `bar_actions_list_names_without_a_colon_or_an_ellipsis` and `more_options_bar_actions_turns_an_action_off_and_on` in `crates/ui-egui/src/tests/taskbar.rs`, and `saved_workspaces_restore_the_task_bar_actions` in `crates/ui-egui/src/workspaces.rs`.
- With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`.
- Rectangle Properties and Ellipse Properties in the Transform panel, the Properties panel and the task bar's Shape Properties popup have an Angle field, as Polygon Properties does: the help page lists Rectangle Angle and Ellipse Angle as the shape's rotation on the canvas from 0° to 360° (<https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html>). A typed angle turns the shape through `object.setLiveShape {rectangleAngle, ellipseAngle}`. VectorCraft's own rules: degrees counterclockwise, 0 for a shape drawn level; each selected shape of that kind turns about its own center and keeps its size, corners and pie; the field is blank when the selected shapes of that kind differ, as the Polygon Properties angle now is too; the shape keeps its angle after Reset Bounding Box squares the Rotate field's box to the page; the angle a shape already has records no undo step. Evidence: `a_rectangle_and_an_ellipse_take_their_angle` in `crates/engine/src/tests/livecorners.rs` and `a_rectangle_and_an_ellipse_show_their_angle` in `crates/ui-egui/src/panels/transform/tests.rs`.
- While the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool is in use, the contextual task bar offers Edit Path (the Direct Selection tool), the Fill and Stroke chips, and Shape Properties for the shape it draws, as the help page lists for those five tools (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html>). VectorCraft's own rules: the bar shows while one of those tools has one closed path selected whole, as right after it draws one, and not with nothing selected, several objects, a group, an open path, type or picked-out anchors; it shows nothing during the drag that draws the shape; it leaves out the selection tools' Duplicate, Offset Path, Simplify, Recolor Artwork and Lock; the Line Segment tool shows no bar. Not done: Shape Properties for a star, which the app draws as a plain path, and Gen Shape Fill and Generate Vectors, which the app doesn't have. Evidence: `shape_tools_show_edit_path_paint_and_properties_after_drawing`, `shape_tools_have_no_shape_bar_without_a_single_shape` and `shape_tool_bar_retargets_after_another_shape_and_undo` in `crates/ui-egui/src/tests/taskbar.rs`.
@@ -1239,6 +1242,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Image Brush library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Image Brush offers Soft Bloom, Halftone Field, Solar Grain and Color Flecks as original image stamp designs. Each preset places copies of its embedded, transparent PNG along a path as a scatter brush; adding a brush carries its image resource into the document, and saving a library keeps the pixels. The public page names the category but not these presets. Evidence: `image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved` in `crates/engine/src/tests/brushlib.rs` covers stamps, add/apply and reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the UI.
- **Pressure Sensitive library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Pressure Sensitive offers Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow. The first two are art brushes whose width follows recorded pen pressure; the other two are calligraphic nibs whose size follows it. They use the engine's existing pressure input where the device and platform deliver it, and a neutral width for a mouse path. These presets and names are VectorCraft's own. Evidence: `pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` checks light and heavy pressure, short and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI.
- **Decorative library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Decorative offers Leaf Vine, Blossom Chain, Pennant Garland and Lantern String. The four original vector pattern brushes repeat plant, flower and hanging ornament tiles along paths and take the stroke color as tints. The public source identifies Decorative as a classic brush library; these preset designs are VectorCraft's own. Evidence: `decorative_brushes_repeat_distinct_art_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers distinct finite output, add/apply and saved-library reopening, and `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI.
- **Paint library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Paint offers Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep. These original art brushes stretch broad, broken, loaded and fanned vector marks along a path and take the stroke color as tints. The public source describes the Paint category's varied thickness, textured edges and natural effects; the preset designs and names are VectorCraft's own. Evidence: `paint_brushes_draw_distinct_marks_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers finite output on short, long and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI.
- **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`).
- **Arrows library:** Window › Brush Libraries › Arrows holds five art brushes, each 100 pt long: Solid Arrow, Open Arrow (an outlined head), Double Arrow (a head at each end), Chevron Arrow (a second chevron on the shaft) and Dashed Arrow (five separate dashes and a head). Each brush stretches only the part between its guides, so the shaft follows the path's length and the heads keep their proportions, with Tints colorization. The brushes, their names and their art are VectorCraft's own, generated in code (`brush.libraries`, `brush.addFromLibrary`; `arrows_library_lists_renders_and_applies_original_brushes`, `dashed_arrow_keeps_separate_dashes_and_survives_library_save`).
- **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`).
@@ -1944,6 +1948,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels.
- **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel.
- **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given.
- **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged.
- **HSL Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item HSL Sliders (`ui.colorWheel {sliders: "hsl"}`, kept with the preferences) shows H, S and L rows in place of OKLCH Sliders that edit the color by the hue (0 to 360°), saturation and lightness (0 to 100 %) of its display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes from display sRGB into the working RGB space as the wheel's picks do, and the rows keep the hue of a gray. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. Evidence: `hsl_follows_css_color_4` and `hsl_roundtrip` in `crates/color/src/lib.rs`; the HSL tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `a_gray_keeps_the_hsl_hue_it_was_given` among them. Scores and estimates are unchanged.
- **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
@@ -2292,6 +2298,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`).
- EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`).
- EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`).
- EMF and WMF text drawn in the opaque background mode, which a playback starts in ([MS-EMF 2.1.4 BackgroundMode](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/2f57054c-2b69-4303-a6f8-5aacd401f759), [SetBkMode](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-setbkmode)), gets one rectangle of the background color behind each line's character cells, placed before the type; transparent text gets none. A character cell runs from the font's OS/2 `usWinAscent` above the baseline to its `usWinDescent` below it, and top or bottom aligned text puts the top or the bottom of the cell at the reference point (`opaque_backgrounds_fill_behind_the_character_cells`, `opaque_backgrounds_reach_as_far_as_the_advances`, `wmf_text_fills_its_cells_in_the_opaque_background_mode`).
- EMF and WMF import warns about what the reader leaves out or does not play as the file asks: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), with one warning without a count, and, with counts, images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`).
- Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
- HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
+2 -1
View File
@@ -253,7 +253,7 @@ tools, never checked side by side) isn't captured row by row.
| Drag a curved segment to bend it, a straight one to move its anchors | done | |
| Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 |
| Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 |
| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) |
| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) |
| Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display |
| Convert selected anchors to corner/smooth from the Control bar and Properties | done | |
| Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor |
@@ -349,6 +349,7 @@ tools, never checked side by side) isn't captured row by row.
| Sliders in dialogs and popups (Save for Web, raster export options, Preferences, the opacity popup) show their rail, filled up to the handle | done | #1483 |
| Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) |
| Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) |
| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and, with Measurement Labels on, the radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored |
## Modifier keys and temporary tools
+1 -1
View File
@@ -5,7 +5,7 @@ use std::process::Command;
use serde_json::Value;
const REV: &str = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b";
const REV: &str = "50b0ee7bf811e363b5f238382b5c77318cf33e46";
const PACKAGES: &[(&str, &str, &str)] = &[
("craft-pdf", "0.1.0", REV),
("krilla", "0.8.2", REV),