mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into fix/issue-8307
This commit is contained in:
commit
a0058a06e6
111 files changed
+4485
-356
No files matched your search
@@ -7,11 +7,17 @@
|
||||
//! fails in a Flatpak sandbox (`XCURSOR_PATH` unset, no cursor theme in the runtime) and where the
|
||||
//! `default` theme is a dangling symlink; the desktop's own setting names a theme that loads.
|
||||
//!
|
||||
//! Where no cursor theme can be found at all (KDE or sway without gsettings), the env fix does
|
||||
//! nothing: [`shell_caps`] leaves out [`Caps::SYSTEM_CURSOR`], and the framework keeps the system
|
||||
//! pointer and paints no tool cursor beside it (#5311).
|
||||
//!
|
||||
//! This reads the desktop's cursor theme and size and sets what the user left unset, once, before
|
||||
//! any thread starts and before the window opens.
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
|
||||
use craft::host::target::Caps;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Where a Flatpak sandbox mounts the host's cursor themes (user and system).
|
||||
const FLATPAK_HOST_ICONS: [&str; 2] = ["/run/host/user-share/icons", "/run/host/share/icons"];
|
||||
@@ -48,6 +54,74 @@ pub fn plan(var: impl Fn(&str) -> Option<OsString>, host_icons: &[&str], desktop
|
||||
out
|
||||
}
|
||||
|
||||
/// Xcursor's default search path when `XCURSOR_PATH` is unset (relative entries are in `$HOME`).
|
||||
const DEFAULT_ICON_DIRS: [&str; 5] = ["~/.local/share/icons", "~/.icons", "/usr/share/icons", "/usr/share/pixmaps", "/usr/X11R6/lib/X11/icons"];
|
||||
|
||||
/// The themes `index.theme` lists after `Inherits=`.
|
||||
fn inherits(index: &str) -> Vec<String> {
|
||||
index
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("Inherits="))
|
||||
.map(|v| v.split([',', ';']).map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Can Xcursor load a pointer for the environment's theme (`XCURSOR_THEME`, else `default`)? It does
|
||||
/// when the theme, or one it inherits from, has a `default` or `left_ptr` cursor file in a folder of
|
||||
/// `XCURSOR_PATH` (else Xcursor's default folders). `read` returns a file's text, `exists` tells
|
||||
/// whether a file is there.
|
||||
pub fn theme_usable(
|
||||
var: impl Fn(&str) -> Option<OsString>,
|
||||
home: Option<&Path>,
|
||||
read: impl Fn(&Path) -> Option<String>,
|
||||
exists: impl Fn(&Path) -> bool,
|
||||
) -> bool {
|
||||
let dirs: Vec<PathBuf> = match var("XCURSOR_PATH").filter(|v| !v.is_empty()) {
|
||||
Some(v) => std::env::split_paths(&v).collect(),
|
||||
None => DEFAULT_ICON_DIRS
|
||||
.iter()
|
||||
.filter_map(|d| match d.strip_prefix("~/") {
|
||||
Some(rest) => home.map(|h| h.join(rest)),
|
||||
None => Some(PathBuf::from(d)),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let first = var("XCURSOR_THEME").and_then(|v| v.into_string().ok()).filter(|t| !t.is_empty()).unwrap_or_else(|| "default".into());
|
||||
let mut todo = vec![first];
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
while let Some(theme) = todo.pop() {
|
||||
// Bounded: themes inherit in short chains, and a cycle must end.
|
||||
if seen.contains(&theme) || seen.len() >= 16 {
|
||||
continue;
|
||||
}
|
||||
for dir in &dirs {
|
||||
let base = dir.join(&theme);
|
||||
if ["default", "left_ptr"].iter().any(|c| exists(&base.join("cursors").join(c))) {
|
||||
return true;
|
||||
}
|
||||
if let Some(index) = read(&base.join("index.theme")) {
|
||||
todo.extend(inherits(&index));
|
||||
}
|
||||
}
|
||||
seen.push(theme);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// On this machine, after [`apply`]: is there no cursor theme Xcursor can load? Then winit never
|
||||
/// sets a pointer, and a hidden system pointer does not come back (#2450).
|
||||
pub fn theme_missing() -> bool {
|
||||
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
|
||||
!theme_usable(|n| std::env::var_os(n), home.as_deref(), |p| std::fs::read_to_string(p).ok(), |p| p.exists())
|
||||
}
|
||||
|
||||
/// The shell's capabilities `caps`, without [`Caps::SYSTEM_CURSOR`] when the window opens on
|
||||
/// Wayland and `theme_missing` finds no cursor theme. The framework then keeps the system pointer
|
||||
/// and paints no tool cursor beside it (#5311). `theme_missing` runs only on Wayland.
|
||||
pub fn shell_caps(caps: Caps, wayland: bool, theme_missing: impl FnOnce() -> bool) -> Caps {
|
||||
if wayland && theme_missing() { caps.difference(Caps::SYSTEM_CURSOR) } else { caps }
|
||||
}
|
||||
|
||||
/// The value of a `gsettings get` line: `'Adwaita'` becomes `Adwaita`, `24` stays `24`.
|
||||
fn gsettings_value(output: &str) -> &str {
|
||||
output.trim().trim_matches('\'')
|
||||
@@ -113,6 +187,43 @@ mod tests {
|
||||
assert!(plan(env(&[("WAYLAND_DISPLAY", "wayland-0")]), &[], odd).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_theme_is_usable_directly_or_through_inherits_and_missing_otherwise() {
|
||||
let files = ["/i/Bibata/cursors/left_ptr", "/i/Breeze/index.theme", "/i/Loop/index.theme"];
|
||||
// Compared as paths, so the joins match on Windows too, where they use `\`.
|
||||
let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p);
|
||||
let read = |p: &Path| {
|
||||
if p == Path::new("/i/Breeze/index.theme") {
|
||||
Some("[Icon Theme]\nInherits=Other, Bibata\n".to_owned())
|
||||
} else if p == Path::new("/i/Loop/index.theme") {
|
||||
Some("Inherits=Loop\n".to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let with = |theme: &'static str| {
|
||||
move |n: &str| (n == "XCURSOR_PATH").then(|| OsString::from("/i")).or((n == "XCURSOR_THEME").then(|| OsString::from(theme)))
|
||||
};
|
||||
assert!(theme_usable(with("Bibata"), None, read, exists));
|
||||
assert!(theme_usable(with("Breeze"), None, read, exists));
|
||||
// No such theme, a theme without cursors, an inheritance loop: nothing to load.
|
||||
assert!(!theme_usable(with("Nope"), None, read, exists));
|
||||
assert!(!theme_usable(with("Loop"), None, read, exists));
|
||||
// Unset: Xcursor's default folders and the `default` theme.
|
||||
assert!(!theme_usable(|_| None, Some(Path::new("/home/u")), read, exists));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_cursor_theme_on_wayland_the_system_pointer_stays_alone() {
|
||||
let native = Caps::native(craft::host::target::Os::Linux);
|
||||
assert!(native.contains(Caps::SYSTEM_CURSOR));
|
||||
let without = shell_caps(native, true, || true);
|
||||
assert!(!without.contains(Caps::SYSTEM_CURSOR), "Wayland with no cursor theme: no painted cursor beside the system pointer");
|
||||
assert_eq!(without.union(Caps::SYSTEM_CURSOR), native, "only the system cursor is left out");
|
||||
assert_eq!(shell_caps(native, true, || false), native, "Wayland with a theme");
|
||||
assert_eq!(shell_caps(native, false, || panic!("the theme is looked up only on Wayland")), native, "X11 and XWayland");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gsettings_output_is_unquoted() {
|
||||
assert_eq!(gsettings_value("'Adwaita'\n"), "Adwaita");
|
||||
|
||||
@@ -667,6 +667,11 @@ fn main() -> std::process::ExitCode {
|
||||
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
|
||||
// Preferences › User Interface › System Title Bar.
|
||||
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
|
||||
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
|
||||
// beside it (#2450, #5311).
|
||||
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
|
||||
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
|
||||
let shell_info = shell_info.caps(caps);
|
||||
let titlebar_pref =
|
||||
if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated };
|
||||
let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref);
|
||||
|
||||
+33
-4
@@ -571,6 +571,15 @@ pub struct PatternBrush {
|
||||
pub end_swatch: Option<String>,
|
||||
/// Scale in percent.
|
||||
pub scale: f64,
|
||||
/// How the scale varies along a stroke: `None` (Fixed) always `scale`; a mode that follows the
|
||||
/// pen goes from `scale` to [`Self::scale_max`] over the ranges [`Variation`] gives, as an Art
|
||||
/// brush's width does ([`ArtBrush::width_mode`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scale_mode: Option<Variation>,
|
||||
/// The second scale (%) of a mode that follows the pen: at the heaviest pressure, upright, at
|
||||
/// 180° or at the wheel's far end (`scale` without one).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scale_max: Option<f64>,
|
||||
/// Space between tiles in percent of the tile width.
|
||||
pub spacing: f64,
|
||||
pub fit: PatternFit,
|
||||
@@ -583,6 +592,15 @@ impl PatternBrush {
|
||||
/// The ranges of the scale and of the spacing (%).
|
||||
pub const SCALE_RANGE: (f64, f64) = (1.0, 10000.0);
|
||||
pub const SPACING_RANGE: (f64, f64) = (0.0, 10000.0);
|
||||
|
||||
/// The scales (%) where the pen reads 0 and 1 for the scale's mode (the lightest and the
|
||||
/// heaviest pressure, for Pressure): `scale` for both unless the scale follows the pen.
|
||||
pub fn scale_range(&self) -> (f64, f64) {
|
||||
match self.scale_mode {
|
||||
Some(m) if m.follows_pen() => (self.scale, self.scale_max.unwrap_or(self.scale)),
|
||||
_ => (self.scale, self.scale),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PatternBrush {
|
||||
@@ -606,6 +624,8 @@ impl Default for PatternBrush {
|
||||
end_frame: None,
|
||||
end_swatch: None,
|
||||
scale: 100.0,
|
||||
scale_mode: None,
|
||||
scale_max: None,
|
||||
spacing: 0.0,
|
||||
fit: PatternFit::Stretch,
|
||||
flip_along: false,
|
||||
@@ -791,6 +811,11 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0);
|
||||
// The scale follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed.
|
||||
if !p.scale_mode.is_some_and(Variation::follows_pen) {
|
||||
p.scale_mode = None;
|
||||
}
|
||||
p.scale_max = p.scale_max.map(|s| within(s, PatternBrush::SCALE_RANGE, p.scale));
|
||||
p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0);
|
||||
for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] {
|
||||
if frame.is_some_and(|f| !valid_tile_frame(f)) {
|
||||
@@ -846,6 +871,8 @@ struct ArtOptions {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PatternOptions {
|
||||
scale: f64,
|
||||
scale_mode: Option<Variation>,
|
||||
scale_max: Option<f64>,
|
||||
spacing: f64,
|
||||
fit: PatternFit,
|
||||
flip_along: bool,
|
||||
@@ -873,7 +900,7 @@ impl BrushKind {
|
||||
"brightness_jitter",
|
||||
],
|
||||
BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"],
|
||||
BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"],
|
||||
BrushKind::Pattern(_) => &["scale", "scale_mode", "scale_max", "spacing", "fit", "flip_along", "flip_across", "colorization"],
|
||||
BrushKind::Bristle(_) => &[],
|
||||
}
|
||||
}
|
||||
@@ -911,6 +938,8 @@ impl BrushKind {
|
||||
}),
|
||||
BrushKind::Pattern(p) => serde_json::to_value(PatternOptions {
|
||||
scale: p.scale,
|
||||
scale_mode: p.scale_mode,
|
||||
scale_max: p.scale_max,
|
||||
spacing: p.spacing,
|
||||
fit: p.fit,
|
||||
flip_along: p.flip_along,
|
||||
@@ -940,8 +969,8 @@ impl BrushKind {
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
let o: PatternOptions = serde_json::from_value(v)?;
|
||||
(p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) =
|
||||
(o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization);
|
||||
(p.scale, p.scale_mode, p.scale_max, p.spacing) = (o.scale, o.scale_mode, o.scale_max, o.spacing);
|
||||
(p.fit, p.flip_along, p.flip_across, p.colorization) = (o.fit, o.flip_along, o.flip_across, o.colorization);
|
||||
}
|
||||
BrushKind::Bristle(_) => {}
|
||||
}
|
||||
@@ -1165,7 +1194,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w, stroke),
|
||||
};
|
||||
let colorization = brush.kind.colorization();
|
||||
for n in &mut out {
|
||||
|
||||
@@ -2381,6 +2381,297 @@ fn art_brush_width_follows_tilt_bearing_and_rotation() {
|
||||
assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]);
|
||||
}
|
||||
|
||||
/// A pattern brush with `scale`, `scale_mode` and `scale_max`, its 10 × 4 pt side tile on `fit`.
|
||||
fn scaled_pattern(fit: PatternFit, corners: bool, scale: f64, mode: Option<Variation>, max: Option<f64>) -> Brush {
|
||||
let mut b = pattern_brush(fit, corners);
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
(p.scale, p.scale_mode, p.scale_max) = (scale, mode, max);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The bounds of each piece, left to right.
|
||||
fn piece_spans(out: &[Node]) -> Vec<Rect> {
|
||||
let mut spans: Vec<Rect> = out.iter().filter_map(Node::geometric_bounds).collect();
|
||||
spans.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||
spans
|
||||
}
|
||||
|
||||
/// Pattern Brush Options: with Scale on Pressure the tiles go from Scale at the lightest pen
|
||||
/// pressure to the second scale at the heaviest, taller and longer along the stroke where the pen
|
||||
/// pressed harder, and each Fit still fits them to the path.
|
||||
#[test]
|
||||
fn pattern_brush_scale_follows_the_pressure() {
|
||||
let bp = line(0.0, 0.0, 200.0, 0.0);
|
||||
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
// 4 pt tall tiles at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest.
|
||||
let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp);
|
||||
assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
|
||||
assert!(near(half_width(&out, 199.0, 200.0), 6.0, 0.2), "{}", half_width(&out, 199.0, 200.0));
|
||||
assert!(near(half_width(&out, 99.0, 101.0), 3.5, 0.2), "{}", half_width(&out, 99.0, 101.0));
|
||||
// Stretch to Fit fills the path, and the tiles grow longer along it.
|
||||
let spans = piece_spans(&out);
|
||||
assert!(near(bounds(&out).x0, 0.0, 1e-6) && near(bounds(&out).x1, 200.0, 1e-6), "{:?}", bounds(&out));
|
||||
assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{spans:?}");
|
||||
assert!(spans.last().unwrap().width() > 4.0 * spans[0].width(), "{spans:?}");
|
||||
// The stroke weight scales it.
|
||||
let out =
|
||||
draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() });
|
||||
assert!(near(half_width(&out, 199.0, 200.0), 12.0, 0.4), "{}", half_width(&out, 199.0, 200.0));
|
||||
// Without recorded pressure, half way between the two scales.
|
||||
let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &stroke(1.0));
|
||||
assert!(near(bounds(&out).height(), 7.0, 1e-6), "{:?}", bounds(&out));
|
||||
// With an even pressure, Add Space with spacing places as many tiles as the one scale that
|
||||
// pressure gives: the spacing counts when the tiles are counted again.
|
||||
let even = pressed(vec![(0.0, 0.5), (1.0, 0.5)]);
|
||||
let spaced = |mode: Option<Variation>, max: Option<f64>| {
|
||||
let mut b = scaled_pattern(PatternFit::AddSpace, false, if max.is_some() { 50.0 } else { 100.0 }, mode, max);
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.spacing = 100.0;
|
||||
}
|
||||
piece_spans(&draw(&b, &even)).len()
|
||||
};
|
||||
assert_eq!(spaced(Some(Variation::Pressure), Some(150.0)), spaced(None, None));
|
||||
// With spacing, Stretch to Fit still fills the path and Approximate Path still centers the
|
||||
// tiles, with the gaps between them counted and none after the last.
|
||||
for fit in [PatternFit::Stretch, PatternFit::Approximate] {
|
||||
let mut b = scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.spacing = 50.0;
|
||||
}
|
||||
let spans = piece_spans(&draw(&b, &ramp));
|
||||
let (first, last) = (spans[0], spans[spans.len() - 1]);
|
||||
assert!(spans.len() > 1 && near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{fit:?}: {spans:?}");
|
||||
if fit == PatternFit::Stretch {
|
||||
assert!(near(first.x0, 0.0, 1e-6) && near(last.x1, 200.0, 1e-6), "{spans:?}");
|
||||
}
|
||||
}
|
||||
// Add Space to Fit keeps the tiles apart within the path; Approximate Path centers them on it.
|
||||
for fit in [PatternFit::AddSpace, PatternFit::Approximate] {
|
||||
let out = draw(&scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp);
|
||||
let spans = piece_spans(&out);
|
||||
assert!(spans.len() > 1 && spans.windows(2).all(|w| w[1].x0 >= w[0].x1 - 1e-6), "{fit:?}: {spans:?}");
|
||||
assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{fit:?}: {spans:?}");
|
||||
let (first, last) = (spans[0], spans[spans.len() - 1]);
|
||||
if fit == PatternFit::AddSpace {
|
||||
assert!(first.x0 >= -1e-6 && last.x1 <= 200.0 + 1e-6, "{spans:?}");
|
||||
} else {
|
||||
assert!(near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{spans:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pattern Brush Options: Scale on Tilt, Bearing, Rotation or Stylus Wheel reads only its own
|
||||
/// input, half way without it; Fixed, a mode without a second scale and equal scales draw as a
|
||||
/// brush without the setting does.
|
||||
#[test]
|
||||
fn pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel() {
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
|
||||
let brush = |mode: Variation| scaled_pattern(PatternFit::Stretch, false, 50.0, Some(mode), Some(300.0));
|
||||
let wheel = |v: f64| StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, v), (1.0, v)] }), ..stroke(1.0) };
|
||||
// 4 pt tiles: 2 pt tall at 50 %, 12 pt at 300 %.
|
||||
for (mode, st, height) in [
|
||||
(Variation::Tilt, posed(Some(0.0), None, None), 12.0),
|
||||
(Variation::Tilt, posed(Some(1.0), None, None), 2.0),
|
||||
(Variation::Bearing, posed(Some(0.5), Some(90.0), None), 9.5),
|
||||
(Variation::Rotation, posed(None, None, Some(-90.0)), 4.5),
|
||||
(Variation::StylusWheel, wheel(1.0), 12.0),
|
||||
(Variation::StylusWheel, wheel(0.0), 2.0),
|
||||
// Without its own input, half way.
|
||||
(Variation::Tilt, posed(None, Some(90.0), Some(90.0)), 7.0),
|
||||
(Variation::Bearing, posed(Some(0.0), None, Some(90.0)), 7.0),
|
||||
(Variation::Rotation, posed(Some(0.0), Some(90.0), None), 7.0),
|
||||
(Variation::StylusWheel, pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 7.0),
|
||||
(Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0)), 7.0),
|
||||
] {
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, height, 1e-6), "{mode:?}: {h}");
|
||||
}
|
||||
// Fixed, a mode without a second scale, and a second scale equal to the first draw what the
|
||||
// brush draws without them.
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
let plain = draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &ramp);
|
||||
for (mode, max) in [(None, Some(300.0)), (Some(Variation::Pressure), None), (Some(Variation::Pressure), Some(50.0))] {
|
||||
assert_eq!(draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, mode, max), &ramp), plain, "{mode:?} {max:?}");
|
||||
}
|
||||
let saved = serde_json::to_value(scaled_pattern(PatternFit::Stretch, false, 50.0, None, None)).unwrap();
|
||||
assert!(saved.get("scale_mode").is_none() && saved.get("scale_max").is_none(), "{saved}");
|
||||
// A mode the scale does not take is read as Fixed, and the second scale is kept within range.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "a", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "random", "scale_max": 1e308},
|
||||
{"name": "b", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "stylusWheel", "scale_max": 0.0},
|
||||
]));
|
||||
let [BrushKind::Pattern(a), BrushKind::Pattern(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") };
|
||||
assert_eq!((a.scale_mode, a.scale_max, b.scale_mode, b.scale_max), (None, Some(10000.0), Some(Variation::StylusWheel), Some(1.0)));
|
||||
// A stroke sets its own mode and second scale.
|
||||
let mut own = serde_json::Map::new();
|
||||
own.insert("scale_mode".into(), serde_json::json!("pressure"));
|
||||
own.insert("scale_max".into(), serde_json::json!(300.0));
|
||||
let edited = scaled_pattern(PatternFit::Stretch, false, 100.0, None, None).with_stroke_options(&own).unwrap();
|
||||
assert!(matches!(&edited.kind, BrushKind::Pattern(p) if p.scale_range() == (100.0, 300.0)), "{edited:?}");
|
||||
}
|
||||
|
||||
/// A pattern brush whose scale follows the pen keeps its start, end and corner tiles at the scale
|
||||
/// where they are, on open and closed paths, and stays finite at the ends of the scale's range.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() {
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
// Start and end tiles, 6 × 4 pt: the start tile at the light end is smaller than the end tile.
|
||||
let mut ends = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut ends.kind {
|
||||
(p.start, p.end) = (Some(rect_art(6.0, 4.0)), Some(rect_art(6.0, 4.0)));
|
||||
}
|
||||
let out = stroke_pieces(&doc, &ends, &line(0.0, 0.0, 200.0, 0.0), &ramp);
|
||||
let (start, end) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap());
|
||||
assert!(near(start.x0, 0.0, 1e-6) && near(end.x1, 200.0, 1e-6), "{start:?} {end:?}");
|
||||
assert!(start.width() < 3.5 && end.width() > 17.0 && start.height() < end.height() / 4.0, "{start:?} {end:?}");
|
||||
// A closed rectangle with corner tiles, on each Fit, and the scale's range at its ends.
|
||||
let mut rect = BezPath::new();
|
||||
rect.move_to((0.0, 0.0));
|
||||
rect.line_to((100.0, 0.0));
|
||||
rect.line_to((100.0, 60.0));
|
||||
rect.line_to((0.0, 60.0));
|
||||
rect.close_path();
|
||||
for fit in [PatternFit::Stretch, PatternFit::AddSpace, PatternFit::Approximate] {
|
||||
for (scale, max) in [(50.0, 300.0), (1.0, 10000.0), (10000.0, 1.0)] {
|
||||
for bp in [&rect, &line(0.0, 0.0, 3.0, 0.0)] {
|
||||
let b = scaled_pattern(fit, true, scale, Some(Variation::Pressure), Some(max));
|
||||
let out = stroke_pieces(&doc, &b, bp, &ramp);
|
||||
assert!(!out.is_empty(), "{fit:?} {scale} {max}");
|
||||
let r = bounds(&out);
|
||||
assert!([r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()), "{fit:?} {scale} {max}: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// On the rectangle the corner tiles grow with the pressure: the first corner's tile is smaller
|
||||
// than the last one's.
|
||||
let b = scaled_pattern(PatternFit::Stretch, true, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
let out = stroke_pieces(&doc, &b, &rect, &ramp);
|
||||
let fixed = stroke_pieces(&doc, &scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &rect, &ramp);
|
||||
assert_ne!(out, fixed);
|
||||
let corner = |n: &Node| n.geometric_bounds().map_or(0.0, |r| r.width().max(r.height()));
|
||||
let corners: Vec<f64> = out.iter().take(4).map(corner).collect();
|
||||
assert!(corners[0] < corners[3], "{corners:?}");
|
||||
// The side tiles start half the corner tile beside them away from the corner: 1.5 pt from the
|
||||
// first corner, where the 6 pt corner tile is drawn at 50 %, not half the largest corner tile.
|
||||
let first_side = out.get(4).and_then(Node::geometric_bounds);
|
||||
assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}");
|
||||
}
|
||||
|
||||
/// A start or end tile whose scale follows the pen is placed where it is as long as the scale at
|
||||
/// its middle, even when the scale rises again further along and the tile would not fit at the
|
||||
/// whole run's length.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_falls_back() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
// From 100 % to 10000 %: 300 % from 5 to 20 pt, 10000 % from 50 pt on; mirrored for the end.
|
||||
let q = 2.0 / 99.0;
|
||||
for (start, points, span) in [
|
||||
(true, vec![(0.0, 0.0), (0.05, q), (0.2, q), (0.5, 1.0), (1.0, 1.0)], (0.0, 18.0)),
|
||||
(false, vec![(0.0, 1.0), (0.5, 1.0), (0.8, q), (0.95, q), (1.0, 0.0)], (82.0, 100.0)),
|
||||
] {
|
||||
let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(10000.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
let tile = Some(rect_art(6.0, 4.0));
|
||||
(p.start, p.end) = if start { (tile, None) } else { (None, tile) };
|
||||
}
|
||||
// The 6 pt tile at 300 %: 18 pt long, its middle where the scale is 300 %.
|
||||
let out = stroke_pieces(&doc, &b, &bp, &pressed(points));
|
||||
let r = out.first().and_then(Node::geometric_bounds);
|
||||
assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}");
|
||||
}
|
||||
// 400 % at the start, 100 % from 15 to 20 pt, 400 % from 40 pt on, mirrored for the end: a 30 pt
|
||||
// tile at 100 % fits at its middle, although at the scale at its first length's middle it is as
|
||||
// long as that length.
|
||||
for (start, points, span) in [
|
||||
(true, vec![(0.0, 1.0), (0.15, 0.0), (0.2, 0.0), (0.4, 1.0), (1.0, 1.0)], (0.0, 30.0)),
|
||||
(false, vec![(0.0, 1.0), (0.6, 1.0), (0.8, 0.0), (0.85, 0.0), (1.0, 1.0)], (70.0, 100.0)),
|
||||
] {
|
||||
let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(400.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
let tile = Some(rect_art(30.0, 4.0));
|
||||
(p.start, p.end) = if start { (tile, None) } else { (None, tile) };
|
||||
}
|
||||
let out = stroke_pieces(&doc, &b, &bp, &pressed(points));
|
||||
let r = out.first().and_then(Node::geometric_bounds);
|
||||
assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale
|
||||
/// recorded at the end of the stroke there, where the tile is drawn.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_wraps_before_a_closed_paths_start() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let b = scaled_pattern(PatternFit::Approximate, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
// Light over the first 90 % of the stroke, heavy at its end.
|
||||
let st = pressed(vec![(0.0, 0.0), (0.9, 0.0), (1.0, 1.0)]);
|
||||
let mut before = 0;
|
||||
for r in (100..=120).map(f64::from) {
|
||||
// A circle of radius `r` as 720 sides, from (r, 0) on towards +y.
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((r, 0.0));
|
||||
for i in 1..720 {
|
||||
let a = std::f64::consts::TAU * f64::from(i) / 720.0;
|
||||
bp.line_to((r * a.cos(), r * a.sin()));
|
||||
}
|
||||
bp.close_path();
|
||||
let out = stroke_pieces(&doc, &b, &bp, &st);
|
||||
let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("{r}: no tiles") };
|
||||
if first.y0 < -0.5 {
|
||||
// The 4 pt tall tile is 2 pt tall at the light 50 % and nearly 12 pt at the heavy end.
|
||||
before += 1;
|
||||
assert!(first.x1 > r + 3.0, "{r}: {first:?}");
|
||||
}
|
||||
}
|
||||
assert!(before > 0, "no first tile starts before the path's start");
|
||||
}
|
||||
|
||||
/// On a closed path, a tile over the path's start follows the scale on both sides of the start,
|
||||
/// even when the scale is the same at the tile's ends, its middle and every pen sample within it.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_changes_where_a_closed_path_wraps_round() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let mut b = scaled_pattern(PatternFit::Approximate, false, 100.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.side = rect_art(54.0, 4.0);
|
||||
}
|
||||
// A closed path 256 pt long without corners, from (0, 0) along +x: its sides in each quarter
|
||||
// turn, and the same turned three more times.
|
||||
let quarter = [(28.0, 0.0), (12.0, 5.0), (4.0, 3.0), (3.0, 4.0), (5.0, 12.0)];
|
||||
let mut bp = BezPath::new();
|
||||
let mut at = (0.0, 0.0);
|
||||
bp.move_to(at);
|
||||
for turn in 0..4 {
|
||||
for &(x, y) in &quarter {
|
||||
let (dx, dy) = match turn {
|
||||
0 => (x, y),
|
||||
1 => (-y, x),
|
||||
2 => (-x, -y),
|
||||
_ => (y, -x),
|
||||
};
|
||||
at = (at.0 + dx, at.1 + dy);
|
||||
if at != (0.0, 0.0) {
|
||||
bp.line_to(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
bp.close_path();
|
||||
// 100 % up to 4 pt before the end, rising to 300 % at the end. Approximate Path places five
|
||||
// 54 pt tiles, the first from 7 pt before the start: at 100 % at both its ends, its middle and
|
||||
// the samples at 4 pt before the start and at the start, but larger from 4 pt before it.
|
||||
let st = pressed(vec![(0.0, 0.0), (252.0 / 256.0, 0.0), (1.0, 1.0)]);
|
||||
let out = stroke_pieces(&doc, &b, &bp, &st);
|
||||
let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("no tiles") };
|
||||
// The 4 pt tall tile is 2 pt either side of the path at 100 %, and 5 pt at 1 pt before the
|
||||
// start, where the scale is 250 %.
|
||||
assert!(first.y0 < -3.5, "{first:?}");
|
||||
}
|
||||
|
||||
/// Definitions from files and commands are kept within their ranges.
|
||||
#[test]
|
||||
fn sanitize_keeps_values_within_their_ranges() {
|
||||
|
||||
+284
-11
@@ -649,6 +649,253 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti
|
||||
bend(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), cross)
|
||||
}
|
||||
|
||||
/// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies
|
||||
/// (`marks`: the arc lengths of the recorded pen samples in order, between which the scale runs
|
||||
/// in a straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it
|
||||
/// is too when the scale is the same at both ends of the span, at every sample within it and, at
|
||||
/// a closed track's start within it, on both sides of the start.
|
||||
fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option<Node> {
|
||||
let mid = k((s0 + s1) / 2.0);
|
||||
// Only the samples within the span are looked at.
|
||||
let within = |marks: &[f64]| {
|
||||
let from = marks.partition_point(|&s| s <= s0);
|
||||
let to = from + marks[from..].partition_point(|&s| s < s1);
|
||||
marks[from..to].iter().all(|&s| k(s) == mid)
|
||||
};
|
||||
// A closed track's scale goes from the one at its end to the one at its start where it wraps
|
||||
// round, so a span over its start (or a track's length before or after it) takes both.
|
||||
let l = t.len();
|
||||
let seam = t.closed && l > 0.0 && (s0 / l).ceil() <= (s1 / l).floor();
|
||||
let ends = || !seam || (k(0.0) == mid && k(l) == mid);
|
||||
let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks) && ends();
|
||||
if mid <= 0.0 || marks.is_none_or(even) {
|
||||
return tile_on(t, tile, s0, s1, mid);
|
||||
}
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid)
|
||||
}
|
||||
|
||||
/// The most side tiles a run of a pattern brush places.
|
||||
const MAX_TILES: usize = 20000;
|
||||
|
||||
/// How many times a pattern brush whose scale varies measures its side tiles again where the fit
|
||||
/// puts them.
|
||||
const REFITS: usize = 3;
|
||||
|
||||
/// How many times a pattern brush whose scale varies halves the range a start or end tile's
|
||||
/// length lies in.
|
||||
const END_SOLVE_STEPS: usize = 48;
|
||||
|
||||
/// How many evenly spaced lengths a pattern brush whose scale varies tries for a start or end
|
||||
/// tile before it halves the range the tile's length lies in.
|
||||
const END_SCAN_STEPS: usize = 64;
|
||||
|
||||
/// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along
|
||||
/// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and
|
||||
/// how many tiles fit whole and what fraction of the next one fits after them. The tiles include
|
||||
/// that next one when there is room for part of it.
|
||||
fn varied_tiles(a: f64, avail: f64, natural: &dyn Fn(f64) -> (f64, f64)) -> (Vec<(f64, f64)>, f64) {
|
||||
let mut tiles = vec![];
|
||||
let mut pos = 0.0;
|
||||
while tiles.len() < MAX_TILES {
|
||||
let (w, g) = natural(a + pos);
|
||||
if !(w > 1e-9 && w.is_finite() && g.is_finite() && g >= 0.0) {
|
||||
break;
|
||||
}
|
||||
tiles.push((w, g));
|
||||
if pos + w > avail {
|
||||
let whole = (tiles.len() - 1) as f64;
|
||||
return (tiles, whole + ((avail - pos + g) / (w + g)).clamp(0.0, 1.0));
|
||||
}
|
||||
pos += w + g;
|
||||
}
|
||||
let whole = tiles.len() as f64;
|
||||
(tiles, whole)
|
||||
}
|
||||
|
||||
/// The size factor of a pattern brush's tiles at `weight` where its scale's pen input is `p`
|
||||
/// (0 at the first scale, 1 at the second).
|
||||
fn pattern_scale_at(pb: &PatternBrush, weight: f64, p: f64) -> f64 {
|
||||
let (light, heavy) = pb.scale_range();
|
||||
weight * (light + (heavy - light) * p).max(1.0) / 100.0
|
||||
}
|
||||
|
||||
/// A pattern brush's size factor on `stroke` at `weight`, and whether it varies along the stroke.
|
||||
/// A stroke with no recording of the input the scale follows is drawn at one scale, the one that
|
||||
/// input's missing value gives.
|
||||
fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, bool) {
|
||||
let (light, heavy) = pb.scale_range();
|
||||
match pb.scale_mode {
|
||||
Some(m) if light != heavy && pen_recorded(stroke, m) => (weight * pb.scale.max(1.0) / 100.0, true),
|
||||
Some(m) if light != heavy => (pattern_scale_at(pb, weight, PenAt::of(stroke, 0.0).control(m).unwrap_or(0.5)), false),
|
||||
_ => (weight * pb.scale.max(1.0) / 100.0, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at
|
||||
/// the middle of the tile when it is `w` long: the shortest length that is as long as the scale at
|
||||
/// its own middle. The scale can rise and fall along the stroke, so the lengths up to `room` are
|
||||
/// tried in order (evenly spaced ones, and `breaks`, the lengths whose middle falls on a recorded
|
||||
/// pen sample), and the range between the last one the tile is too long for and the first one it
|
||||
/// fits is halved. A tile that fits at no length up to `room` gets the length it needs at `room`,
|
||||
/// longer than `room`. `breaks` is `None` when the scale is the same along the whole track, and
|
||||
/// the tile then takes its length at that scale.
|
||||
fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: Option<&[f64]>) -> f64 {
|
||||
let length = |w: f64| width * k_mid(w);
|
||||
let first = length(0.0);
|
||||
let Some(breaks) = breaks.filter(|_| !room.is_nan() && room > 0.0) else {
|
||||
return first;
|
||||
};
|
||||
let mut tries: Vec<f64> = (1..=END_SCAN_STEPS).map(|i| room * i as f64 / END_SCAN_STEPS as f64).collect();
|
||||
tries.extend(breaks.iter().copied().filter(|&w| w > 0.0 && w < room));
|
||||
tries.sort_by(f64::total_cmp);
|
||||
let Some(i) = tries.iter().position(|&w| length(w) <= w) else {
|
||||
return length(room);
|
||||
};
|
||||
let (mut short, mut long) = (if i == 0 { 0.0 } else { tries[i - 1] }, tries[i]);
|
||||
for _ in 0..END_SOLVE_STEPS {
|
||||
let mid = (short + long) / 2.0;
|
||||
if length(mid) > mid {
|
||||
short = mid;
|
||||
} else {
|
||||
long = mid;
|
||||
}
|
||||
}
|
||||
long
|
||||
}
|
||||
|
||||
/// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its
|
||||
/// arc length, and again a track's length before and after it, for tiles of a closed track that
|
||||
/// wrap round, in order.
|
||||
fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec<f64> {
|
||||
let points = match mode {
|
||||
Variation::Fixed | Variation::Random => None,
|
||||
Variation::Pressure => stroke.pressure.as_ref().map(|p| &p.points),
|
||||
Variation::Tilt => stroke.tilt.as_ref().map(|p| &p.points),
|
||||
Variation::Bearing => stroke.bearing.as_ref().map(|p| &p.points),
|
||||
Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points),
|
||||
Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points),
|
||||
};
|
||||
let mut marks: Vec<f64> = points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect();
|
||||
marks.sort_by(f64::total_cmp);
|
||||
marks
|
||||
}
|
||||
|
||||
/// Whether `stroke` recorded the pen input `mode` follows.
|
||||
fn pen_recorded(stroke: &StrokeLayer, mode: Variation) -> bool {
|
||||
match mode {
|
||||
Variation::Fixed | Variation::Random => false,
|
||||
Variation::Pressure => stroke.pressure.is_some(),
|
||||
Variation::Tilt => stroke.tilt.is_some(),
|
||||
Variation::Bearing => stroke.bearing.is_some(),
|
||||
Variation::Rotation => stroke.rotation.is_some(),
|
||||
Variation::StylusWheel => stroke.wheel.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Leaves out or adds tiles at the end of `tiles` (each a length and the gap after it) once they
|
||||
/// have been measured again: with `add_space` as many as fit in `avail` with the gaps between
|
||||
/// them, at least one, otherwise the count whose lengths and gaps between them come nearest to
|
||||
/// `avail`. An added tile is
|
||||
/// `natural(s)` long at `s` from the run's start.
|
||||
fn recount(tiles: &mut Vec<(f64, f64)>, avail: f64, add_space: bool, natural: &dyn Fn(f64) -> (f64, f64)) {
|
||||
let mut length: f64 = tiles.iter().map(|t| t.0).sum();
|
||||
let mut gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum());
|
||||
// How much of the run the tiles and the spacing between them take.
|
||||
let run = |length: f64, gaps: f64| length + gaps;
|
||||
while let [.., (_, before), (w, _)] = tiles.as_slice() {
|
||||
let (w, before) = (*w, *before);
|
||||
let (now, without) = (run(length, gaps), run(length - w, gaps - before));
|
||||
let drop = if add_space { now > avail } else { (without - avail).abs() < (now - avail).abs() };
|
||||
if !drop {
|
||||
break;
|
||||
}
|
||||
tiles.pop();
|
||||
length -= w;
|
||||
gaps -= before;
|
||||
}
|
||||
while tiles.len() < MAX_TILES {
|
||||
let last_gap = tiles.last().map_or(0.0, |t| t.1);
|
||||
let now = run(length, gaps);
|
||||
let (w, g) = natural(run(length, gaps + last_gap));
|
||||
if w.is_nan() || w <= 1e-9 {
|
||||
break;
|
||||
}
|
||||
let with = run(length + w, gaps + last_gap);
|
||||
let add = if add_space { with <= avail } else { (with - avail).abs() < (now - avail).abs() };
|
||||
if !add {
|
||||
break;
|
||||
}
|
||||
tiles.push((w, g));
|
||||
length += w;
|
||||
gaps += last_gap;
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern brush's side tiles on the run `avail` long from `a` of `t` (`marks` as
|
||||
/// [`tile_scaled`] takes them), at the scale `k(s)` at
|
||||
/// arc length `s` ([`varied_tiles`]), fitted as `pb.fit` says: Stretch scales the lengths and gaps
|
||||
/// to fill the run, Add Space keeps the lengths and shares out what is left between the tiles
|
||||
/// (around a lone tile), and Approximate keeps both and centers the tiles on the run.
|
||||
fn varied_side_tiles(
|
||||
out: &mut Budget,
|
||||
t: &Track,
|
||||
pb: &PatternBrush,
|
||||
side: &(Node, Rect),
|
||||
(a, avail): (f64, f64),
|
||||
k: &dyn Fn(f64) -> f64,
|
||||
marks: &[f64],
|
||||
) {
|
||||
let tw = side.1.width();
|
||||
// Each side tile and the gap after it as long as the scale at the tile's middle.
|
||||
let natural = |s: f64| {
|
||||
let w = tw * k(s + tw * k(s) / 2.0);
|
||||
(w, w * pb.spacing.max(0.0) / 100.0)
|
||||
};
|
||||
let (tiles, count) = varied_tiles(a, avail, &natural);
|
||||
let n = match pb.fit {
|
||||
PatternFit::AddSpace => count.floor(),
|
||||
PatternFit::Stretch | PatternFit::Approximate => count.round(),
|
||||
}
|
||||
.max(1.0) as usize;
|
||||
let mut tiles = tiles[..n.min(tiles.len())].to_vec();
|
||||
// How far the fit stretches the tiles and gaps, where the first tile starts, and the space
|
||||
// between tiles when the fit sets it.
|
||||
let fitted = |tiles: &[(f64, f64)]| {
|
||||
let length: f64 = tiles.iter().map(|t| t.0).sum();
|
||||
// The gaps between the tiles: after every tile but the last.
|
||||
let gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum());
|
||||
match pb.fit {
|
||||
PatternFit::Stretch => (avail / (length + gaps), 0.0, None),
|
||||
PatternFit::AddSpace if tiles.len() > 1 => (1.0, 0.0, Some(((avail - length) / (tiles.len() - 1) as f64).max(0.0))),
|
||||
PatternFit::AddSpace => (1.0, (avail - tiles.first().map_or(0.0, |t| t.0)) / 2.0, None),
|
||||
PatternFit::Approximate => (1.0, (avail - length - gaps) / 2.0, None),
|
||||
}
|
||||
};
|
||||
// The fit moves the tiles from where they were measured, so each is measured again at the
|
||||
// middle of where the fit puts it, and the fit worked out again, a few times over.
|
||||
for _ in 0..REFITS {
|
||||
let (stretch, lead, space) = fitted(&tiles);
|
||||
let mut s0 = a + lead;
|
||||
for tile in &mut tiles {
|
||||
let placed = tile.0 * stretch;
|
||||
let w = tw * k(s0 + placed / 2.0);
|
||||
s0 += placed + space.unwrap_or(tile.1 * stretch);
|
||||
*tile = (w, w * pb.spacing.max(0.0) / 100.0);
|
||||
}
|
||||
recount(&mut tiles, avail, pb.fit == PatternFit::AddSpace, &|s| natural(a + s));
|
||||
}
|
||||
let (stretch, lead, space) = fitted(&tiles);
|
||||
let mut s0 = a + lead;
|
||||
for &(w, g) in &tiles {
|
||||
let w = w * stretch;
|
||||
out.take(tile_scaled(t, side, s0, s0 + w, k, Some(marks)));
|
||||
if out.full() {
|
||||
break;
|
||||
}
|
||||
s0 += w + space.unwrap_or(g * stretch);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pattern brush draws at a corner: corner tile art (oriented, with its bounds), or what
|
||||
/// [`CornerSource`] gives.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -803,10 +1050,15 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option<Node> {
|
||||
Some(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(n)], clip: true }))
|
||||
}
|
||||
|
||||
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node> {
|
||||
/// A pattern brush's tiles along `bp`. With a scale that follows the pen (its pressure, tilt,
|
||||
/// bearing, rotation or wheel), the tiles are as tall as what `stroke` recorded at each point gives
|
||||
/// (half way without a recording), each tile and the gap after it as long as the scale at its
|
||||
/// middle, and each corner tile at the scale at its corner.
|
||||
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec<Node> {
|
||||
let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across);
|
||||
let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] };
|
||||
let k = weight * pb.scale.max(1.0) / 100.0;
|
||||
let scale_at = |p: f64| pattern_scale_at(pb, weight, p);
|
||||
let (k, varies) = pattern_scale(pb, weight, stroke);
|
||||
let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame));
|
||||
let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame));
|
||||
let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame));
|
||||
@@ -825,6 +1077,17 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
if l <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
// The scale at arc length `s` of the track; on a closed track a point before its start or
|
||||
// past its end wraps round as `Track::frame` places it (its end itself keeps the scale at
|
||||
// the end), and on an open track a point past either end takes the scale at that end.
|
||||
let ks = |s: f64| {
|
||||
if !varies {
|
||||
return k;
|
||||
}
|
||||
let at = if t.closed && !(0.0..=l).contains(&s) { s.rem_euclid(l) } else { s.clamp(0.0, l) };
|
||||
scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5))
|
||||
};
|
||||
let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l));
|
||||
let corners = t.corner_positions();
|
||||
// Corner tiles, centred on the corner and turned to the bisector. The path on each side of
|
||||
// a corner is shortened by `trims` (`None`: half the widest corner tile art).
|
||||
@@ -848,17 +1111,18 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
};
|
||||
before.min(after)
|
||||
};
|
||||
for (ci, &(i, _)) in corners.iter().enumerate() {
|
||||
for (ci, &(i, at)) in corners.iter().enumerate() {
|
||||
if out.full() {
|
||||
break;
|
||||
}
|
||||
let kc = ks(at);
|
||||
let (a, b) = t.in_out(i);
|
||||
// Turning towards the left normal puts the tile's +y side on the inside.
|
||||
let tile = if a.cross(b) > 0.0 { inner_tile.or(outer.as_ref().map(Corner::Art)) } else { outer_tile.or(inner.as_ref().map(Corner::Art)) };
|
||||
let (art, bb) = match tile {
|
||||
Some(Corner::Art(tile)) => tile,
|
||||
Some(Corner::Source(source)) => {
|
||||
let (pieces, trim) = auto_corner(&t, i, source, &side, k, room(ci));
|
||||
let (pieces, trim) = auto_corner(&t, i, source, &side, kc, room(ci));
|
||||
for n in pieces {
|
||||
out.take(Some(n));
|
||||
}
|
||||
@@ -870,8 +1134,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
continue;
|
||||
}
|
||||
};
|
||||
trims.push(None);
|
||||
corner_half = corner_half.max(bb.width() * k / 2.0);
|
||||
// With a scale that varies, each corner's tile is its own size, so the path beside it
|
||||
// is shortened by half of that tile.
|
||||
trims.push(varies.then_some(bb.width() * kc / 2.0));
|
||||
corner_half = corner_half.max(bb.width() * kc / 2.0);
|
||||
// Inner and outer corner art is the corner that joins a side tile on its right to one
|
||||
// below it, so its arms point along +x and +y (as the flips leave them). The tile is
|
||||
// turned so that the line halving its arms lies on the line halving the sides at the
|
||||
@@ -881,7 +1147,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 });
|
||||
let sides = b - a;
|
||||
let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x);
|
||||
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2());
|
||||
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(kc) * Affine::translate(-bb.center().to_vec2());
|
||||
let mut n = art.clone();
|
||||
n.transform(xf, true);
|
||||
out.take(Some(n));
|
||||
@@ -914,9 +1180,11 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
&& ri == 0
|
||||
&& let Some(st) = &start
|
||||
{
|
||||
let w = st.1.width() * k;
|
||||
// As long as the scale at its middle.
|
||||
let breaks: Option<Vec<f64>> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (m - a)).collect());
|
||||
let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), breaks.as_deref());
|
||||
if b - a > w {
|
||||
out.take(tile_on(&t, st, a, a + w, k));
|
||||
out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref()));
|
||||
a += w;
|
||||
}
|
||||
}
|
||||
@@ -924,9 +1192,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
&& ri + 1 == nruns
|
||||
&& let Some(en) = &end
|
||||
{
|
||||
let w = en.1.width() * k;
|
||||
let breaks: Option<Vec<f64>> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (b - m)).collect());
|
||||
let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), breaks.as_deref());
|
||||
if b - a > w {
|
||||
out.take(tile_on(&t, en, b - w, b, k));
|
||||
out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref()));
|
||||
b -= w;
|
||||
}
|
||||
}
|
||||
@@ -934,6 +1203,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
if avail <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
if let Some(marks) = &marks {
|
||||
varied_side_tiles(&mut out, &t, pb, &side, (a, avail), &ks, marks);
|
||||
continue;
|
||||
}
|
||||
let unit = tw + gap;
|
||||
match pb.fit {
|
||||
PatternFit::Stretch => {
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
//! Color text in the forms CSS Color 4 defines: hex colors with or without an alpha
|
||||
//! (<https://www.w3.org/TR/css-color-4/#hex-notation>), `rgb()` and `rgba()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#rgb-functions>), `hsl()` and `hsla()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>) and `oklch()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch>). The functions take the
|
||||
//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also
|
||||
//! take the comma-separated legacy form (<https://www.w3.org/TR/css-color-4/#legacy-color-syntax>).
|
||||
//! Hues take the angle units of CSS Values 4 (<https://www.w3.org/TR/css-values-4/#angles>). A hex
|
||||
//! color may leave out its `#`.
|
||||
//!
|
||||
//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages,
|
||||
//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`,
|
||||
//! `var()`, `color-mix()`, relative color syntax and every other nested function are refused, as are
|
||||
//! named colors and the other color spaces and functions (`hwb()`, `lab()`, `oklab()`, `color()`).
|
||||
|
||||
use crate::oklab::{self, CHROMA_FULL};
|
||||
|
||||
/// The most characters a color text may have, spaces around it not counted.
|
||||
pub const MAX_CHARS: usize = 48;
|
||||
|
||||
/// The space a parsed color's red, green and blue are in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Space {
|
||||
/// The numbers as written: a hex color, `rgb()` or `hsl()`.
|
||||
Srgb,
|
||||
/// sRGB converted from `oklch()`.
|
||||
Oklch,
|
||||
}
|
||||
|
||||
/// A color read from CSS text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct CssColor {
|
||||
/// Red, green and blue from 0 to 1.
|
||||
pub rgb: [f32; 3],
|
||||
/// The alpha from 0 to 1, when the text gives one (CSS reads a missing alpha as 1).
|
||||
pub alpha: Option<f32>,
|
||||
pub space: Space,
|
||||
}
|
||||
|
||||
/// The color `text` gives, or `None` when it is not one of the module's forms or has more than
|
||||
/// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green
|
||||
/// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness
|
||||
/// to 0..=1 and chroma to 0 or more. `none` reads as 0, as CSS reads a missing component when it
|
||||
/// converts a color. Spaces, tabs, line breaks and form feeds may surround the text and its
|
||||
/// arguments; other whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or
|
||||
/// blue falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its
|
||||
/// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such
|
||||
/// colors into the gamut by its own rules instead. An `hsl()` color whose saturation and lightness
|
||||
/// are so large that a channel overflows to an infinity is refused.
|
||||
pub fn parse(text: &str) -> Option<CssColor> {
|
||||
let text = css_trim(text);
|
||||
if text.chars().nth(MAX_CHARS).is_some() {
|
||||
return None;
|
||||
}
|
||||
match text.find('(') {
|
||||
None => hex(text),
|
||||
Some(open) => {
|
||||
// CSS allows no space between a function's name and its `(`.
|
||||
let name = text.get(..open)?.to_ascii_lowercase();
|
||||
let args = text.get(open + 1..)?.strip_suffix(')')?;
|
||||
if args.contains(['(', ')']) {
|
||||
return None;
|
||||
}
|
||||
match name.as_str() {
|
||||
"rgb" | "rgba" => rgb(args),
|
||||
"hsl" | "hsla" => hsl(args),
|
||||
"oklch" => oklch(args),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` without the CSS whitespace (spaces, tabs, line breaks and form feeds, which CSS reads as line
|
||||
/// breaks) around it (<https://www.w3.org/TR/css-syntax-3/#whitespace>,
|
||||
/// <https://www.w3.org/TR/css-syntax-3/#input-preprocessing>).
|
||||
fn css_trim(s: &str) -> &str {
|
||||
s.trim_matches(|c: char| c.is_ascii_whitespace())
|
||||
}
|
||||
|
||||
/// `#rrggbb` of red, green and blue from 0 to 1, each rounded to the nearest of 256 steps.
|
||||
pub fn hex_of(rgb: [f32; 3]) -> String {
|
||||
let [r, g, b] = rgb.map(byte);
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
|
||||
/// `v` (0 to 1) as one of 256 steps.
|
||||
fn byte(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// A hex color of 3, 4, 6 or 8 digits, with or without `#`.
|
||||
fn hex(text: &str) -> Option<CssColor> {
|
||||
let digits = text.strip_prefix('#').unwrap_or(text);
|
||||
if !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let nibbles: Vec<u8> = digits.bytes().filter_map(|b| (b as char).to_digit(16)).map(|d| d as u8).collect();
|
||||
let values: Vec<u8> = match nibbles.len() {
|
||||
3 | 4 => nibbles.iter().map(|n| n * 17).collect(),
|
||||
6 | 8 => nibbles.chunks(2).map(|p| p.iter().fold(0, |v, n| v * 16 + n)).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
let unit = |i: usize| values.get(i).map(|v| f32::from(*v) / 255.0);
|
||||
Some(CssColor { rgb: [unit(0)?, unit(1)?, unit(2)?], alpha: unit(3), space: Space::Srgb })
|
||||
}
|
||||
|
||||
/// One argument of a color function.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Arg {
|
||||
Number(f64),
|
||||
Percent(f64),
|
||||
/// An angle, in degrees.
|
||||
Angle(f64),
|
||||
None,
|
||||
}
|
||||
|
||||
/// The arguments of a color function, `args` being the text inside its parentheses: the three
|
||||
/// components and the alpha, if any, and whether they were separated by commas (the legacy form).
|
||||
fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option<Arg>, bool)> {
|
||||
let (parts, alpha, legacy): (Vec<&str>, Option<&str>, bool) = if args.contains(',') {
|
||||
if !legacy_allowed || args.contains('/') {
|
||||
return None;
|
||||
}
|
||||
let mut parts: Vec<&str> = args.split(',').map(css_trim).collect();
|
||||
let alpha = if parts.len() == 4 { parts.pop() } else { None };
|
||||
(parts, alpha, true)
|
||||
} else {
|
||||
let mut halves = args.split('/');
|
||||
let colors = halves.next().unwrap_or_default();
|
||||
let alpha = halves.next();
|
||||
if halves.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
(colors.split_ascii_whitespace().collect(), alpha.map(css_trim), false)
|
||||
};
|
||||
let [a, b, c] = parts.as_slice() else { return None };
|
||||
let one = |s: &str| {
|
||||
let arg = arg(s)?;
|
||||
// The legacy form has no `none`.
|
||||
(!(legacy && arg == Arg::None)).then_some(arg)
|
||||
};
|
||||
let alpha = match alpha {
|
||||
Some(s) => Some(one(s)?),
|
||||
None => None,
|
||||
};
|
||||
Some(([one(a)?, one(b)?, one(c)?], alpha, legacy))
|
||||
}
|
||||
|
||||
/// One argument: `none`, a number, a percentage or an angle (`deg`, `grad`, `rad`, `turn`), with no
|
||||
/// spaces inside it.
|
||||
fn arg(s: &str) -> Option<Arg> {
|
||||
if s.eq_ignore_ascii_case("none") {
|
||||
return Some(Arg::None);
|
||||
}
|
||||
let end = number_end(s)?;
|
||||
let n: f64 = s.get(..end)?.parse().ok().filter(|n: &f64| n.is_finite())?;
|
||||
let unit = s.get(end..)?.to_ascii_lowercase();
|
||||
let arg = match unit.as_str() {
|
||||
"" => Arg::Number(n),
|
||||
"%" => Arg::Percent(n),
|
||||
"deg" => Arg::Angle(n),
|
||||
"grad" => Arg::Angle(n * 0.9),
|
||||
"rad" => Arg::Angle(n.to_degrees()),
|
||||
"turn" => Arg::Angle(n * 360.0),
|
||||
_ => return None,
|
||||
};
|
||||
match arg {
|
||||
Arg::Angle(a) if !a.is_finite() => None,
|
||||
_ => Some(arg),
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte length of the CSS number at the start of `s`: an optional sign, digits with an
|
||||
/// optional fraction (at least one digit, and digits after a `.`), and an optional exponent.
|
||||
fn number_end(s: &str) -> Option<usize> {
|
||||
let b = s.as_bytes();
|
||||
let digits = |from: usize| b.get(from..).map_or(0, |rest| rest.iter().take_while(|c| c.is_ascii_digit()).count());
|
||||
let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-')));
|
||||
let whole = digits(i);
|
||||
i += whole;
|
||||
let mut fraction = 0;
|
||||
if b.get(i) == Some(&b'.') {
|
||||
fraction = digits(i + 1);
|
||||
if fraction == 0 {
|
||||
return None;
|
||||
}
|
||||
i += 1 + fraction;
|
||||
}
|
||||
if whole + fraction == 0 {
|
||||
return None;
|
||||
}
|
||||
if matches!(b.get(i), Some(b'e' | b'E')) {
|
||||
let sign = usize::from(matches!(b.get(i + 1), Some(b'+' | b'-')));
|
||||
let exp = digits(i + 1 + sign);
|
||||
if exp > 0 {
|
||||
i += 1 + sign + exp;
|
||||
}
|
||||
}
|
||||
Some(i)
|
||||
}
|
||||
|
||||
/// The alpha argument from 0 to 1.
|
||||
fn alpha(a: Option<Arg>) -> Option<Option<f32>> {
|
||||
let v = match a {
|
||||
None => return Some(None),
|
||||
Some(Arg::Number(n)) => n,
|
||||
Some(Arg::Percent(p)) => p / 100.0,
|
||||
Some(Arg::None) => 0.0,
|
||||
Some(Arg::Angle(_)) => return None,
|
||||
};
|
||||
Some(Some(v.clamp(0.0, 1.0) as f32))
|
||||
}
|
||||
|
||||
/// A hue argument in degrees from 0 to 360.
|
||||
fn hue(a: Arg) -> Option<f64> {
|
||||
match a {
|
||||
Arg::Number(d) | Arg::Angle(d) => Some(d.rem_euclid(360.0)).filter(|d| d.is_finite()),
|
||||
Arg::None => Some(0.0),
|
||||
Arg::Percent(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, legacy) = split(args, true)?;
|
||||
let percents = comps.iter().filter(|c| matches!(c, Arg::Percent(_))).count();
|
||||
if legacy && percents != 0 && percents != 3 {
|
||||
return None;
|
||||
}
|
||||
let unit = |c: Arg| match c {
|
||||
Arg::Number(n) => Some(n / 255.0),
|
||||
Arg::Percent(p) => Some(p / 100.0),
|
||||
Arg::None => Some(0.0),
|
||||
Arg::Angle(_) => None,
|
||||
};
|
||||
let [r, g, b] = comps;
|
||||
let rgb = [unit(r)?, unit(g)?, unit(b)?].map(|v| v.clamp(0.0, 1.0) as f32);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb })
|
||||
}
|
||||
|
||||
fn hsl(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, legacy) = split(args, true)?;
|
||||
let [h, s, l] = comps;
|
||||
let percent = |c: Arg| match c {
|
||||
Arg::Percent(v) => Some(v),
|
||||
Arg::Number(v) if !legacy => Some(v),
|
||||
Arg::None => Some(0.0),
|
||||
_ => None,
|
||||
};
|
||||
// CSS clamps a negative saturation to 0 and nothing else.
|
||||
let (h, s, l) = (hue(h)?, percent(s)?.max(0.0) / 100.0, percent(l)? / 100.0);
|
||||
// CSS Color 4's hslToRgb (https://www.w3.org/TR/css-color-4/#hsl-to-rgb); a channel outside
|
||||
// 0..=1 is clipped.
|
||||
let f = |n: f64| {
|
||||
let k = (n + h / 30.0) % 12.0;
|
||||
let amount = s * l.min(1.0 - l);
|
||||
l - amount * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
|
||||
};
|
||||
// Huge saturation and lightness values overflow to an infinity or NaN, which is refused.
|
||||
let rgb = [f(0.0), f(8.0), f(4.0)];
|
||||
if rgb.iter().any(|v| !v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let rgb = rgb.map(|v| v.clamp(0.0, 1.0) as f32);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb })
|
||||
}
|
||||
|
||||
fn oklch(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, _) = split(args, false)?;
|
||||
let [l, c, h] = comps;
|
||||
let l = match l {
|
||||
Arg::Number(v) => v,
|
||||
Arg::Percent(p) => p / 100.0,
|
||||
Arg::None => 0.0,
|
||||
Arg::Angle(_) => return None,
|
||||
};
|
||||
let c = match c {
|
||||
Arg::Number(v) => v,
|
||||
Arg::Percent(p) => p / 100.0 * CHROMA_FULL,
|
||||
Arg::None => 0.0,
|
||||
Arg::Angle(_) => return None,
|
||||
};
|
||||
let (rgb, _) = oklab::from_oklch(l.clamp(0.0, 1.0), c.max(0.0), hue(h)?);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Oklch })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn bytes(text: &str) -> ([u8; 3], Option<u8>) {
|
||||
let c = parse(text).unwrap_or_else(|| panic!("{text} should parse"));
|
||||
(c.rgb.map(byte), c.alpha.map(|a| (a * 255.0).round() as u8))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_colors_take_three_four_six_or_eight_digits_with_or_without_the_hash() {
|
||||
assert_eq!(bytes("#336699"), ([0x33, 0x66, 0x99], None));
|
||||
assert_eq!(bytes("33669980"), ([0x33, 0x66, 0x99], Some(0x80)));
|
||||
assert_eq!(bytes("#369"), ([0x33, 0x66, 0x99], None));
|
||||
assert_eq!(bytes("#3698"), ([0x33, 0x66, 0x99], Some(0x88)));
|
||||
assert_eq!(bytes(" #AbCdEf "), ([0xab, 0xcd, 0xef], None));
|
||||
for bad in ["", "#", "#12", "#12345", "#1234567", "#123456789", "#ggg", "##123", "#+12", "#12 3", "123"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_reads_the_modern_and_the_legacy_forms() {
|
||||
assert_eq!(bytes("rgb(51 102 153)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(51 102 153 / 50%)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("RGBA(51 102 153/0.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(20% 40% 60%)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(20% 102 none)"), ([51, 102, 0], None), "the modern form mixes numbers and percentages");
|
||||
assert_eq!(bytes("rgb(51, 102, 153)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgba(51,102,153,.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(51, 102, 153, 50%)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(300 -20 1e2)"), ([255, 0, 100], None), "components are clamped");
|
||||
assert_eq!(bytes("rgb(0 0 0 / 2)"), ([0, 0, 0], Some(255)), "the alpha is clamped");
|
||||
assert_eq!(bytes("rgb(0 0 0 / none)"), ([0, 0, 0], Some(0)));
|
||||
for bad in [
|
||||
"rgb(51, 102%, 153)",
|
||||
"rgb(51, 102, none)",
|
||||
"rgb(51 102)",
|
||||
"rgb(51 102 153 0.5)",
|
||||
"rgb(51, 102 153)",
|
||||
"rgb(51, 102, 153 / 0.5)",
|
||||
"rgb(51 102 153 / 0.5 / 1)",
|
||||
"rgb(51 102 153deg)",
|
||||
"rgb(1. 2 3)",
|
||||
"rgb(1e999 0 0)",
|
||||
"rgb(51 102 153",
|
||||
"rgb(51 102 153))",
|
||||
"rgb(51 102 153) x",
|
||||
"rgb(calc(1) 2 3)",
|
||||
"rgb(,,)",
|
||||
"rgb (1 2 3)",
|
||||
"rgb()",
|
||||
"rgbx(1 2 3)",
|
||||
] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_spaces_tabs_and_line_breaks_are_whitespace() {
|
||||
assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("\u{c}#336699\u{c}"), ([51, 102, 153], None), "CSS reads a form feed as a line break");
|
||||
assert_eq!(bytes("rgb(51\u{c}102\u{c}153)"), ([51, 102, 153], None));
|
||||
for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)", "\u{b}#336699"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hsl_reads_hues_in_every_angle_unit() {
|
||||
assert_eq!(bytes("hsl(210 50% 40%)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("hsl(210deg 50 40 / 25%)"), ([51, 102, 153], Some(64)));
|
||||
assert_eq!(bytes("hsla(210, 50%, 40%, 0.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("hsl(-150 50% 40%)"), ([51, 102, 153], None), "a hue is normalized");
|
||||
assert_eq!(bytes("hsl(0.5turn 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(200grad 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(3.14159265rad 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(120 -20% 50%)"), ([128, 128, 128], None), "a negative saturation is 0");
|
||||
assert_eq!(bytes("hsl(15 150% 50%)"), ([255, 32, 0], None), "a saturation over 100 % is kept and the channels are clipped");
|
||||
assert_eq!(bytes("hsl(0 50% 150%)"), ([255, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(none 0% 100%)"), ([255, 255, 255], None));
|
||||
for bad in
|
||||
["hsl(210, 50, 40)", "hsl(210% 50% 40%)", "hsl(210 50% 40% 1)", "hsl(210deg, 50%, none)", "hsl(1e999deg 0% 0%)", "hsl(1e306turn 0% 0%)"]
|
||||
{
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
// Saturation and lightness this large overflow to an infinity or NaN.
|
||||
for bad in ["hsl(90 1e308% 1e308%)", "hsl(90 1e308 -1e308)"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oklch_converts_through_srgb_and_has_no_legacy_form() {
|
||||
let c = parse("oklch(62.8% 0.2577 29.23)").unwrap();
|
||||
assert_eq!((c.rgb.map(byte), c.alpha, c.space), ([255, 0, 0], None, Space::Oklch));
|
||||
let c = parse("oklch(0.628 64.4% 29.23 / 0.5)").unwrap();
|
||||
assert_eq!((c.rgb.map(byte), c.alpha), ([255, 0, 0], Some(0.5)));
|
||||
assert_eq!(parse("oklch(1 0 0)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]));
|
||||
assert_eq!(parse("oklch(2 -1 none)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]), "L and C are clamped");
|
||||
let wide = parse("oklch(0.7 0.4 150)").unwrap();
|
||||
assert!(wide.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a color outside sRGB is brought inside: {:?}", wide.rgb);
|
||||
let huge = parse("oklch(0.5 1e308 30)").unwrap();
|
||||
assert!(huge.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a huge chroma is brought inside: {:?}", huge.rgb);
|
||||
for bad in ["oklch(0.6, 0.1, 30)", "oklch(0.6 0.1 30% )", "oklch(0.6deg 0.1 30)", "oklch(0.6 0.1)"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_longer_than_the_limit_is_refused() {
|
||||
let at_limit = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 15));
|
||||
assert_eq!(at_limit.chars().count(), MAX_CHARS);
|
||||
assert!(parse(&at_limit).is_some());
|
||||
let over = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 14));
|
||||
assert_eq!(parse(&over), None);
|
||||
assert_eq!(parse(&format!(" {at_limit} ")).map(|c| c.rgb.map(byte)), Some([51, 102, 153]), "spaces around it are not counted");
|
||||
assert_eq!(parse(&"(".repeat(100_000)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_of_rounds_each_component() {
|
||||
assert_eq!(hex_of([0.2, 0.4, 0.6]), "#336699");
|
||||
assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn random_text_never_panics(text in "\\PC{0,60}") {
|
||||
// `contains` is false for NaN, so these also check that every channel is finite.
|
||||
if let Some(c) = parse(&text) {
|
||||
prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));
|
||||
prop_assert!(c.alpha.is_none_or(|a| (0.0..=1.0).contains(&a)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_shaped_text_never_panics(
|
||||
name in "(rgb|rgba|hsl|hsla|oklch|RGB)",
|
||||
args in "[-+0-9.eE%a-z ,/]{0,40}",
|
||||
) {
|
||||
if let Some(c) = parse(&format!("{name}({args})")) {
|
||||
prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_digit_hex_round_trips(r: u8, g: u8, b: u8, a: u8) {
|
||||
let c = parse(&format!("#{r:02x}{g:02x}{b:02x}{a:02x}")).unwrap();
|
||||
prop_assert_eq!(c.rgb.map(byte), [r, g, b]);
|
||||
prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a));
|
||||
prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod blend;
|
||||
pub mod cms;
|
||||
pub mod css;
|
||||
pub mod freeform;
|
||||
pub mod gradient;
|
||||
pub mod harmony;
|
||||
|
||||
@@ -170,7 +170,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Options of Selected Object…",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization, hue_jitter, saturation_jitter, brightness_jitter; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
|
||||
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization, hue_jitter, saturation_jitter, brightness_jitter; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, scale_mode, scale_max, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
|
||||
has_doc,
|
||||
brush_object_options
|
||||
),
|
||||
|
||||
@@ -583,7 +583,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result<Value>
|
||||
merged.insert(k.clone(), next);
|
||||
}
|
||||
keep_drawn_modes(b, &was, ¶ms, &mut merged);
|
||||
keep_largest_width(b, &was, ¶ms, &mut merged);
|
||||
keep_second_value(b, &was, ¶ms, &mut merged);
|
||||
b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))?
|
||||
};
|
||||
options.get_or_insert_with(|| next.clone());
|
||||
@@ -646,27 +646,34 @@ fn keep_drawn_modes(
|
||||
merged.insert("modes".into(), Value::Array(kept));
|
||||
}
|
||||
|
||||
/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when
|
||||
/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is
|
||||
/// the width, so without this a changed width would also change the largest width.
|
||||
fn keep_largest_width(
|
||||
/// Keep the second value a stroke of brush `b` draws with (with its own settings `was`) when
|
||||
/// `params` sets the first and not the second: an art brush's `width` and `width_max`, a pattern
|
||||
/// brush's `scale` and `scale_max`. Without a second value of its own the second value is the
|
||||
/// first, so without this a changed first value would also change the second.
|
||||
fn keep_second_value(
|
||||
b: &Brush,
|
||||
was: &serde_json::Map<String, Value>,
|
||||
params: &serde_json::Map<String, Value>,
|
||||
merged: &mut serde_json::Map<String, Value>,
|
||||
) {
|
||||
if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) {
|
||||
let (first, second) = match b.kind {
|
||||
BrushKind::Art(_) => ("width", "width_max"),
|
||||
BrushKind::Pattern(_) => ("scale", "scale_max"),
|
||||
_ => return,
|
||||
};
|
||||
if params.get(first).is_none_or(Value::is_null) || params.get(second).is_some_and(|m| !m.is_null()) {
|
||||
return;
|
||||
}
|
||||
let art = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
|
||||
Some(BrushKind::Art(a)) => Some(a),
|
||||
// The first value, the second value of its own, and whether the value follows the pen.
|
||||
let values = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
|
||||
Some(BrushKind::Art(a)) => Some((a.width, a.width_max, a.width_mode.is_some_and(|m| m.follows_pen()))),
|
||||
Some(BrushKind::Pattern(p)) => Some((p.scale, p.scale_max, p.scale_mode.is_some_and(|m| m.follows_pen()))),
|
||||
_ => None,
|
||||
};
|
||||
let (Some(before), Some(after)) = (art(was), art(merged)) else { return };
|
||||
let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen());
|
||||
// Only a width that followed the pen has a largest width, and only one that still does uses it.
|
||||
if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width {
|
||||
merged.insert("width_max".into(), json!(before.width));
|
||||
let (Some(before), Some(after)) = (values(was), values(merged)) else { return };
|
||||
// Only a value that followed the pen has a second value, and only one that still does uses it.
|
||||
if before.1.is_none() && before.2 && after.2 && after.0 != before.0 {
|
||||
merged.insert(second.into(), json!(before.0));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::cms::Model;
|
||||
use vectorcraft_color::css;
|
||||
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
|
||||
use vectorcraft_color::wcag::{self, Category};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint, keep_model};
|
||||
@@ -136,6 +137,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
harmony
|
||||
),
|
||||
cmd!(
|
||||
query "color.parse",
|
||||
"Parse Color",
|
||||
[],
|
||||
None,
|
||||
"{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in the comma-separated legacy form, or oklch(), as CSS Color 4 defines them: https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch; this is a subset of CSS: a function's arguments are literal numbers, percentages, angles (deg, grad, rad or turn) and none, so calc(), var(), color-mix() and every other function, named colors and the other color spaces are errors; at most 48 characters, the spaces, tabs, line breaks and form feeds around it not counted)} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB",
|
||||
always,
|
||||
parse_color
|
||||
),
|
||||
cmd!(
|
||||
query "color.contrast",
|
||||
"Contrast",
|
||||
@@ -148,6 +158,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
fn parse_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.parse";
|
||||
let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?;
|
||||
let parsed = css::parse(text).ok_or_else(|| {
|
||||
bad(C, "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters")
|
||||
})?;
|
||||
if parsed.space == css::Space::Oklch && !vectorcraft_color::cms::active().rgb_is_srgb() {
|
||||
return Err(bad(C, "OKLCH needs sRGB as the working RGB space"));
|
||||
}
|
||||
let [r, g, b] = parsed.rgb;
|
||||
// As paint.proxies answers an opacity: a percentage to two places.
|
||||
let opacity = parsed.alpha.map(|a| (f64::from(a) * 10_000.0).round() / 100.0);
|
||||
Ok(json!({ "color": Color::rgb(r, g, b), "hex": css::hex_of(parsed.rgb), "opacity": opacity }))
|
||||
}
|
||||
|
||||
/// The RGB inverse of `c`, expressed in `c`'s colour model.
|
||||
pub(crate) fn invert(c: Color) -> Color {
|
||||
c.invert_keep_model()
|
||||
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o
Line truncated
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o
Line truncated
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -911,6 +911,11 @@ fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `p` gives `key` a value other than null.
|
||||
fn names(p: &Value, key: &str) -> bool {
|
||||
p.get(key).is_some_and(|v| !v.is_null())
|
||||
}
|
||||
|
||||
/// The error for an `opacity` that would go to type characters, which have no opacity of their own.
|
||||
fn characters_have_no_opacity(cmd: &str) -> EngineError {
|
||||
bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke")
|
||||
@@ -945,8 +950,13 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option<Paint>, opacity
|
||||
let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?;
|
||||
// Characters selected with the Type tool take the paint, not the whole type object (#1063). A
|
||||
// null `ids` or `id` names no object, as `given_nodes` reads it.
|
||||
if ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null))
|
||||
&& p.get("item").is_none()
|
||||
let on_characters = !names(p, "ids") && !names(p, "id") && p.get("item").is_none();
|
||||
// An opacity for the characters is refused before their typing session ends, so the session
|
||||
// and its undo step stay as they are.
|
||||
if on_characters && opacity.is_some() && super::textedit::selected_range(s).is_some_and(|(_, a, b)| a != b) {
|
||||
return Err(characters_have_no_opacity(cmd));
|
||||
}
|
||||
if on_characters
|
||||
&& let Some((id, a, b)) = super::textedit::editing_range(s)?
|
||||
&& a != b
|
||||
{
|
||||
@@ -1455,11 +1465,13 @@ impl DocState {
|
||||
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
|
||||
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
|
||||
fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result<Option<(NodeId, Vec<u32>)>> {
|
||||
if p.get("ids").is_some() || p.get("id").is_some() || p.get("item").is_some() {
|
||||
if names(p, "ids") || names(p, "id") || p.get("item").is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let part = super::brushsym::selected_part(s)?;
|
||||
if part.is_some() {
|
||||
// Read `target` first: `item_target` stops at a null `id` or `ids` before it reads `target`.
|
||||
super::appearance::targets_contents(p)?;
|
||||
item_target(s, p, cmd)?;
|
||||
}
|
||||
Ok(part)
|
||||
|
||||
@@ -156,6 +156,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
}
|
||||
entry["menu"] = menu;
|
||||
}
|
||||
if !c.context.is_empty() {
|
||||
entry["menu"]["context"] = json!(c.context);
|
||||
}
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
@@ -2405,7 +2408,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
|
||||
@@ -154,6 +154,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"color.convert",
|
||||
"color.gamutCheck",
|
||||
"color.harmony",
|
||||
"color.parse",
|
||||
"color.plates",
|
||||
"color.used",
|
||||
"dataset.capture",
|
||||
|
||||
@@ -848,6 +848,13 @@ fn path_key(p: &str) -> String {
|
||||
if windows { p.to_lowercase() } else { p }
|
||||
}
|
||||
|
||||
/// `app.redraw()`: returns without changing anything. The app draws a frame between the run's
|
||||
/// slices on its own, and it draws the documents as they were before the run until the run ends,
|
||||
/// so there is nothing for the call to draw. It adds no undo step.
|
||||
fn app_redraw(_: &Host, _: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is
|
||||
/// compared as text with the documents' files and is not resolved; a document whose file the
|
||||
/// automation read roots do not allow does not count, and that check can look the file up on disk.
|
||||
@@ -2565,6 +2572,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("selection", property(l, app_selection, app_set_selection), typed("*")),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
("toString", class_text("Application"), returns("string", &[])),
|
||||
]);
|
||||
|
||||
@@ -242,6 +242,70 @@ fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_chang
|
||||
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0)));
|
||||
}
|
||||
|
||||
/// The scales (%) the first stroke of `id`, painted with Stitches, draws with where the pen reads 0
|
||||
/// and 1.
|
||||
fn stitches_scale_range(s: &Session, id: NodeId) -> (f64, f64) {
|
||||
let lib = vectorcraft_brush::library(&s.doc().unwrap().doc);
|
||||
let b = lib.iter().find(|b| b.name == "Stitches").unwrap();
|
||||
match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind {
|
||||
vectorcraft_brush::BrushKind::Pattern(p) => p.scale_range(),
|
||||
k => panic!("not a pattern brush: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Stitches", "ids": [a.0, b.0]})).unwrap();
|
||||
// Both scales follow the pressure; the first path's second scale is its scale, the second
|
||||
// path's is its own.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100, "scale_mode": "pressure"}})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"scale": 100, "scale_mode": "pressure", "scale_max": 150}})).unwrap();
|
||||
assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((100.0, 100.0), (100.0, 150.0)));
|
||||
// The scale the path has already changes nothing.
|
||||
let steps = undo_steps(&s);
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100}})).unwrap()["changed"], json!([]));
|
||||
assert_eq!(own_options(&s, a), json!({"scale_mode": "pressure"}));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// A new first scale leaves each path's second scale as it was.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 50}})).unwrap();
|
||||
assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((50.0, 100.0), (50.0, 150.0)));
|
||||
// A second scale the params give is set on each path, and the brush keeps its own.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 40, "scale_max": 120}})).unwrap();
|
||||
assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((40.0, 120.0), (40.0, 120.0)));
|
||||
let def = s.execute("brush.get", &json!({"name": "Stitches"})).unwrap();
|
||||
assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}");
|
||||
// A mode that is not one is refused, and nothing changes.
|
||||
let steps = undo_steps(&s);
|
||||
assert!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale_mode": "sideways"}})).is_err());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// Pattern Brush Options' Scale mode and second scale go through `brush.new`, `brush.options`
|
||||
/// and `brush.get`; a partial edit keeps the other fields, and Fixed leaves both out.
|
||||
#[test]
|
||||
fn pattern_brush_scale_mode_goes_through_the_brush_commands() {
|
||||
let mut s = session();
|
||||
let side = rect(&mut s, 0.0, 0.0, 40.0, 8.0);
|
||||
let params = json!({"scale": 50, "scale_mode": "tilt", "scale_max": 300});
|
||||
s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "params": params, "ids": [side.0]})).unwrap();
|
||||
let get = |s: &mut Session| s.execute("brush.get", &json!({"name": "Rail"})).unwrap();
|
||||
let def = get(&mut s);
|
||||
assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(300.0)));
|
||||
s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_max": 200, "spacing": 10}})).unwrap();
|
||||
let def = get(&mut s);
|
||||
assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(200.0)));
|
||||
s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "stylusWheel", "scale_max": 1e9}})).unwrap();
|
||||
let def = get(&mut s);
|
||||
assert_eq!((&def["scale_mode"], &def["scale_max"]), (&json!("stylusWheel"), &json!(10000.0)));
|
||||
s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": null, "scale_max": null}})).unwrap();
|
||||
let def = get(&mut s);
|
||||
assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}");
|
||||
assert!(s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "sideways"}})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -357,6 +357,48 @@ fn convert_to_oklch_answers_lightness_chroma_and_hue() {
|
||||
assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}");
|
||||
}
|
||||
|
||||
/// `color.parse` reads each notation into an RGB color, its hex and the alpha as a percentage (null
|
||||
/// when the text gives none), and answers an error for anything else.
|
||||
#[test]
|
||||
fn parse_reads_hex_with_alpha_and_css_colors() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
let mut parse = |text: &str| s.execute("color.parse", &json!({ "text": text }));
|
||||
for (text, opacity) in [
|
||||
("#33669980", json!(50.2)),
|
||||
("33669980", json!(50.2)),
|
||||
("#3698", json!(53.33)),
|
||||
("#336699", Value::Null),
|
||||
("#369", Value::Null),
|
||||
("rgb(51 102 153 / 50%)", json!(50.0)),
|
||||
("rgba(51, 102, 153, 0.25)", json!(25.0)),
|
||||
("rgb(20% 40% 60%)", Value::Null),
|
||||
("hsl(210 50% 40%)", Value::Null),
|
||||
("hsla(210deg, 50%, 40%, 1)", json!(100.0)),
|
||||
] {
|
||||
let r = parse(text).unwrap();
|
||||
assert_eq!(r["hex"], "#336699", "{text}: {r}");
|
||||
assert_eq!(r["opacity"], opacity, "{text}: {r}");
|
||||
let c: Color = serde_json::from_value(r["color"].clone()).unwrap();
|
||||
let Color::Rgb { r: red, g, b } = c else { panic!("{text}: {c:?}") };
|
||||
assert_eq!([red, g, b].map(|v| (v * 255.0).round() as u8), [0x33, 0x66, 0x99], "{text}");
|
||||
}
|
||||
let red = parse("oklch(62.8% 0.2577 29.23 / 0.5)").unwrap();
|
||||
assert_eq!((&red["hex"], &red["opacity"]), (&json!("#ff0000"), &json!(50.0)), "{red}");
|
||||
let message = "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters";
|
||||
let long = format!("rgb(1 2 3{})", " ".repeat(40));
|
||||
for bad in ["", "#12345", "#gggggg", "rgb(1, 2%, 3)", "rgb(1 2)", "oklch(0.5, 0.1, 30)", "cmyk 0 100 100 0", "red", long.as_str()] {
|
||||
let e = parse(bad).unwrap_err().to_string();
|
||||
assert!(e.ends_with(message), "{bad:?}: {e}");
|
||||
}
|
||||
assert!(parse_err(&mut s, json!({})).ends_with("missing `text`"));
|
||||
assert!(parse_err(&mut s, json!({"text": 5})).ends_with("`text` must be a string"));
|
||||
}
|
||||
|
||||
fn parse_err(s: &mut Session, p: Value) -> String {
|
||||
s.execute("color.parse", &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assign_profile_is_stored_and_undoable() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
|
||||
@@ -285,6 +285,89 @@ fn with_characters_selected_an_id_takes_the_opacity() {
|
||||
assert_eq!(node(&s, t), before, "the characters keep their paint");
|
||||
}
|
||||
|
||||
/// While the Type tool has characters selected, a null `id` or `ids` names no object: the paint goes
|
||||
/// to the selected characters only, as without the key.
|
||||
#[test]
|
||||
fn with_characters_selected_a_null_id_paints_the_characters() {
|
||||
let runs = |key: Option<&str>| {
|
||||
let mut s = session();
|
||||
let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hello"})).unwrap();
|
||||
let t = NodeId(r["id"].as_u64().unwrap());
|
||||
select(&mut s, &[t]);
|
||||
select_characters(&mut s, t);
|
||||
let mut p = json!({"color": "#ff0000"});
|
||||
if let Some(key) = key {
|
||||
p[key] = Value::Null;
|
||||
}
|
||||
s.execute("paint.setFill", &p).unwrap();
|
||||
match &node(&s, t).kind {
|
||||
NodeKind::Text(t) => t.runs.clone(),
|
||||
_ => panic!("not type"),
|
||||
}
|
||||
};
|
||||
let characters = runs(None);
|
||||
assert!(characters.len() > 1, "only the selected characters take the paint");
|
||||
for key in ["id", "ids"] {
|
||||
assert_eq!(runs(Some(key)), characters, "{key}: null");
|
||||
}
|
||||
}
|
||||
|
||||
/// An opacity for characters selected while the Type tool is typing is refused before the typing
|
||||
/// session ends: the session goes on, and no undo step is recorded.
|
||||
#[test]
|
||||
fn an_opacity_for_characters_leaves_the_typing_session_running() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("type", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap();
|
||||
}
|
||||
s.tool_text("Hello", v).unwrap();
|
||||
s.set_tool_option("select", &json!({"start": 0, "end": 2}));
|
||||
assert!(crate::cmd::typing_in_progress(&s));
|
||||
let undo = undo_labels(&s).len();
|
||||
let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err();
|
||||
assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}");
|
||||
assert!(crate::cmd::typing_in_progress(&s), "the typing session goes on");
|
||||
assert_eq!(undo_labels(&s).len(), undo, "no undo step");
|
||||
}
|
||||
|
||||
/// With an opacity alone, the reply counts only the objects that took it: a selected object without
|
||||
/// that fill item is left out, and one already at that opacity still counts. With a paint, every
|
||||
/// target counts.
|
||||
#[test]
|
||||
fn an_opacity_alone_counts_the_objects_that_took_it() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
|
||||
select(&mut s, &[a]);
|
||||
s.execute("appearance.removeItem", &json!({"index": 0})).unwrap();
|
||||
assert!(node(&s, a).appearance.fill().is_none());
|
||||
select(&mut s, &[a, b]);
|
||||
assert_eq!(s.execute("paint.setFill", &json!({"opacity": 40})).unwrap()["objects"], 1);
|
||||
assert_eq!(s.execute("paint.setFill", &json!({"opacity": 40})).unwrap()["objects"], 1, "already at 40%");
|
||||
assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap()["objects"], 2);
|
||||
}
|
||||
|
||||
/// With a layer targeted, `paint.proxies` reads the art the command edits: a locked object's fill
|
||||
/// row does not count, so the proxy answers null when the edit finds no fill to take the opacity.
|
||||
#[test]
|
||||
fn a_targeted_layers_proxy_leaves_out_locked_art() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
|
||||
select(&mut s, &[b]);
|
||||
s.execute("appearance.removeItem", &json!({"index": 0})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err();
|
||||
assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}");
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the unlocked fill counts");
|
||||
}
|
||||
|
||||
/// A type object whose characters take the paint is left alone beside a rectangle that takes the
|
||||
/// opacity, with no error; alone, it answers the characters error.
|
||||
#[test]
|
||||
@@ -373,6 +456,63 @@ fn an_object_in_a_symbol_instance_refuses_an_opacity() {
|
||||
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
|
||||
}
|
||||
|
||||
/// With an object selected in a dynamic symbol instance, a bad `target` is refused whether `id` and
|
||||
/// `ids` are left out or given as null, and leaves the document alone; a good one with a null `id`
|
||||
/// still paints the object.
|
||||
#[test]
|
||||
fn an_object_in_a_symbol_instance_refuses_a_bad_target() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0);
|
||||
select(&mut s, &[id]);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "One", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].clone();
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst, "path": []})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for p in [
|
||||
json!({"color": "#ff0000", "target": "content"}),
|
||||
json!({"color": "#ff0000", "target": "content", "id": null}),
|
||||
json!({"color": "#ff0000", "target": "content", "ids": null}),
|
||||
] {
|
||||
let e = s.execute("paint.setFill", &p).unwrap_err();
|
||||
assert!(e.to_string().contains("`target` must be"), "{p}: {e}");
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc, "{p}");
|
||||
}
|
||||
assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "target": "object", "id": null})).unwrap()["objects"], 1);
|
||||
assert_ne!(*s.doc().unwrap().doc, *doc);
|
||||
}
|
||||
|
||||
/// A bad `target` is refused when `id` or `ids` names an object, and a bad `target` or `aligned`
|
||||
/// while the Type tool has characters selected; each leaves the document alone. A good `target`
|
||||
/// with an `id` still paints the object.
|
||||
#[test]
|
||||
fn a_bad_target_is_refused_with_an_id_or_selected_characters() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
select(&mut s, &[r]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for cmd in ["paint.setFill", "paint.setStroke"] {
|
||||
for p in [
|
||||
json!({"color": "#ff0000", "target": "content", "id": r.0}),
|
||||
json!({"color": "#ff0000", "target": "content", "ids": [r.0]}),
|
||||
json!({"opacity": 40, "target": "content", "id": r.0}),
|
||||
json!({"opacity": 40, "target": "content", "ids": [r.0]}),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err();
|
||||
assert!(e.to_string().contains("`target` must be"), "{cmd} {p}: {e}");
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc, "{cmd} {p}");
|
||||
}
|
||||
}
|
||||
assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "target": "object", "id": r.0})).unwrap()["objects"], 1);
|
||||
assert_ne!(*s.doc().unwrap().doc, *doc);
|
||||
let t = text(&mut s);
|
||||
select(&mut s, &[t]);
|
||||
select_characters(&mut s, t);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for p in [json!({"color": "#ff0000", "target": "content"}), json!({"color": "#ff0000", "aligned": "yes"})] {
|
||||
assert!(s.execute("paint.setFill", &p).is_err(), "{p}");
|
||||
assert_eq!(*s.doc().unwrap().doc, *doc, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows
|
||||
/// it; the object's fill item and the other points stay as they were.
|
||||
#[test]
|
||||
|
||||
@@ -7269,6 +7269,27 @@ fn placed_plugin_commands_are_listed_in_their_menu() {
|
||||
assert!(listed(&s, &low(bee)).is_none());
|
||||
}
|
||||
|
||||
/// `plugin.info`'s `manifest` gives each command's context menus in its `menu`, for a command
|
||||
/// placed in another menu and for one listed only in context menus.
|
||||
#[test]
|
||||
fn plugin_info_gives_a_command_s_context_menus() {
|
||||
let mut s = session();
|
||||
let id = "test.engine.place.context";
|
||||
let commands = json!([
|
||||
{"id": "low", "label": "Low", "menu": {"path": ["Select"], "context": [{"menu": "canvas", "when": "selection"}]}},
|
||||
{"id": "tidy", "label": "Tidy", "menu": {"context": [{"menu": "layers", "when": "layerRow"}]}},
|
||||
{"id": "keep", "label": "Keep"}
|
||||
]);
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Ctx","api":2,"version":"1","kind":"filter","commands":{commands}}}"#);
|
||||
install_wat(&mut s, &tpl::returning(&manifest, r#"{"objects":[]}"#));
|
||||
let info = run(&mut s, "plugin.info", json!({"id": id}));
|
||||
let shown = &info["manifest"]["commands"];
|
||||
assert_eq!(shown[0]["menu"], json!({"path": ["Select"], "context": [{"menu": "canvas", "when": "selection"}]}), "{info}");
|
||||
assert_eq!(shown[1]["menu"], json!({"context": [{"menu": "layers", "when": "layerRow"}]}), "{info}");
|
||||
assert!(shown[2].get("menu").is_none(), "{info}");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A command run is journaled like any other, so an action records it with its parameters and
|
||||
/// plays it back.
|
||||
#[test]
|
||||
|
||||
@@ -394,6 +394,25 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() {
|
||||
assert_eq!(kept(&s), None);
|
||||
}
|
||||
|
||||
/// `app.redraw()` returns `undefined` and leaves the art and the undo history as they were.
|
||||
#[test]
|
||||
fn redraw_returns_and_changes_nothing() {
|
||||
let (mut s, _, top) = doc();
|
||||
let (art, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s));
|
||||
assert_eq!(log(&mut s, "vc.log(typeof app.redraw()); vc.log(app.redraw(1, 'x') === undefined);"), vec![json!("undefined"), json!(true)]);
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// In a run in the app, edits before and after the calls still end as one undo step.
|
||||
s.script_frames = true;
|
||||
let source = "var i = app.activeDocument.pageItems[0]; i.opacity = 40; app.redraw(); i.opacity = 30; app.redraw();";
|
||||
assert_eq!(s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap()["running"], true);
|
||||
let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap_or_else(|| panic!("the run did not end"));
|
||||
ended.unwrap();
|
||||
// The edit after the first call landed too: the opacity is below the 40% set before it.
|
||||
assert!(s.active().unwrap().doc.node(top).unwrap().opacity < 0.4);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// Assigning an item the opacity it reports, rounded to four decimals, changes nothing.
|
||||
#[test]
|
||||
fn assigning_the_reported_opacity_changes_nothing() {
|
||||
|
||||
@@ -1233,6 +1233,23 @@ fn color_management_policies_are_checked_and_kept() {
|
||||
assert_eq!(cms::active_settings(), cms::ColorSettings::default());
|
||||
}
|
||||
|
||||
/// `color.parse` takes `oklch()` only while the working RGB space is sRGB; a hex color still gives
|
||||
/// its numbers as the document's RGB numbers in another working space.
|
||||
#[test]
|
||||
fn color_parse_takes_oklch_only_in_an_srgb_working_space() {
|
||||
let _g = settings();
|
||||
let old = cms::active_settings();
|
||||
let mut s = session();
|
||||
s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap();
|
||||
let oklch = s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).map_err(|e| e.to_string());
|
||||
let hex = s.execute("color.parse", &json!({"text": "#33669980"})).map_err(|e| e.to_string());
|
||||
cms::set_active(&old).unwrap();
|
||||
assert!(oklch.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{oklch:?}");
|
||||
let hex = hex.unwrap();
|
||||
assert_eq!((&hex["hex"], &hex["opacity"]), (&json!("#336699"), &json!(50.2)));
|
||||
assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again");
|
||||
}
|
||||
|
||||
/// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in
|
||||
/// `Color Settings.json`.
|
||||
#[test]
|
||||
|
||||
@@ -857,6 +857,11 @@ fn structured_junk() {
|
||||
("node.move", json!({"id": 1, "parent": null, "index": 1000})),
|
||||
("layer.setProps", json!({"id": 1, "color": 1000})),
|
||||
("layer.newSublayer", json!({"parent": 2})),
|
||||
("color.parse", json!({"text": "rgb(1e308 -1e308 1e-400 / 1e308)"})),
|
||||
("color.parse", json!({"text": "hsl(1e308turn 1e308% -1e308%)"})),
|
||||
("color.parse", json!({"text": "oklch(1e308 1e308 -1e308rad / -1)"})),
|
||||
("color.parse", json!({"text": "#\u{1F600}\u{0}\u{FFFF}"})),
|
||||
("color.parse", json!({"text": "rgb(((((((((((("})),
|
||||
("text.create", json!({"x": 0, "y": 0, "text": "\u{0}\u{FFFF}\u{1F600}", "size": -1})),
|
||||
("text.create", json!({"x": 0, "y": 0, "text": "a", "size": 1e308, "area": {"width": -1, "height": 0}})),
|
||||
("text.setStyle", json!({"size": 0, "leading": -1, "tracking": 1e308})),
|
||||
|
||||
@@ -90,7 +90,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
|
||||
getIsFileOpen selection selection= toString typename",
|
||||
getIsFileOpen redraw selection selection= toString typename",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
|
||||
@@ -793,10 +793,11 @@ proptest! {
|
||||
}
|
||||
|
||||
/// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with
|
||||
/// control and bidirectional override characters, a `menu` of any shape naming any menu, junk
|
||||
/// parameters) at API level 1 or 2 parse to an error or to commands whose menu labels show no
|
||||
/// hidden character and that sit under Plug-ins, or at level 2 in one of the menus a manifest
|
||||
/// may name, with the plug-in's name; installing one and running each of its commands ends as an
|
||||
/// control and bidirectional override characters, a `menu` of any shape naming any menu or
|
||||
/// context menu, junk parameters) at API level 1 or 2 parse to an error or to commands whose
|
||||
/// menu labels show no hidden character and that sit under Plug-ins, or at level 2 in one of the
|
||||
/// menus a manifest may name, with the plug-in's name, and in at most the capped number of
|
||||
/// context menu items; installing one and running each of its commands ends as an
|
||||
/// error or an edit, never a panic, and the document then renders and exports.
|
||||
#[test]
|
||||
fn hostile_manifest_commands_never_crash(
|
||||
@@ -819,6 +820,11 @@ proptest! {
|
||||
Just(json!({"path": ["Select"], "after": "\u{202E}Inverse"})),
|
||||
arb_junk().prop_map(|j| json!({"path": j})),
|
||||
arb_junk().prop_map(|j| json!({"path": ["Select"], "after": j})),
|
||||
Just(json!({"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers", "when": "layerRow"}]})),
|
||||
Just(json!({"context": [{"menu": "canvas", "when": "layerRow"}]})),
|
||||
arb_junk().prop_map(|j| json!({"context": j})),
|
||||
arb_junk().prop_map(|j| json!({"context": [{"menu": "layers", "when": j}]})),
|
||||
arb_junk().prop_map(|j| json!({"path": ["Select"], "context": [j]})),
|
||||
arb_junk(),
|
||||
],
|
||||
prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()],
|
||||
@@ -860,6 +866,11 @@ proptest! {
|
||||
prop_assert!(api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&place.path), "{:?}", place);
|
||||
prop_assert!(placed.ends_with(')') && placed.len() > shown.len(), "a placed item names its plug-in: {}", placed);
|
||||
}
|
||||
prop_assert!(api >= 2 || c.context.is_empty(), "level 1 lists no context menu: {:?}", c.context);
|
||||
prop_assert!(c.context.iter().all(|p| p.menu == vectorcraft_plugins::ContextMenu::Layers || p.when != Some(vectorcraft_plugins::ContextWhen::LayerRow)));
|
||||
}
|
||||
for menu in [vectorcraft_plugins::ContextMenu::Canvas, vectorcraft_plugins::ContextMenu::Layers] {
|
||||
prop_assert!(man.context_commands(menu).count() <= vectorcraft_plugins::manifest::MAX_CONTEXT_COMMANDS);
|
||||
}
|
||||
}
|
||||
let mut s = rich_session();
|
||||
|
||||
@@ -1132,13 +1132,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.brushOptions",
|
||||
"Brush Options…",
|
||||
"",
|
||||
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options",
|
||||
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options",
|
||||
),
|
||||
(
|
||||
"ui.brushObjectOptions",
|
||||
"Options of Selected Object…",
|
||||
"",
|
||||
"{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush",
|
||||
"{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, scaleMax/scaleMode, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush",
|
||||
),
|
||||
(
|
||||
"ui.graphicStyleOptions",
|
||||
@@ -1615,7 +1615,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.colorWheel",
|
||||
"Color Wheel Options",
|
||||
"",
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: 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, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: 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 at or below the one asked for; 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; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); 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; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); 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 active document's RGB space (its assigned profile, else 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, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors
Line truncated
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: 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, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: 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 at or below the one asked for; 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; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); 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; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); 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,
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.savePdfDialog",
|
||||
|
||||
@@ -89,11 +89,15 @@ pub(crate) fn xmp(pdf: &[u8], xref: &Xref, root: (usize, usize), patch: &mut Pat
|
||||
let xml = data.checked_add(length).and_then(|e| obj.get(data..e)).ok_or_else(bad)?;
|
||||
let mut edits: Vec<(usize, usize, Vec<u8>)> = vec![];
|
||||
if let Some((version, _)) = pdfx_ids(standard).filter(|_| standard == Standard::PdfX4) {
|
||||
// Into the writer's description, whose namespaces declare the `pdf` and `xmpMM` prefixes.
|
||||
// The writer wraps its properties in one outer description. Declare `pdfxid` there with
|
||||
// the other namespaces, so validators can find the version property without attributes.
|
||||
let description = b"<rdf:Description";
|
||||
let open = find(xml, description, 0).ok_or_else(bad)? + description.len();
|
||||
let close = crate::lab_spot::rfind(xml, b"</rdf:Description>").ok_or_else(bad)?;
|
||||
edits.push((open, open, br#" xmlns:pdfxid="http://www.npes.org/pdfx/ns/id/""#.to_vec()));
|
||||
let trapped = if trapped { "True" } else { "False" };
|
||||
let props = format!(
|
||||
"<pdfxid:GTS_PDFXVersion xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\">{version}</pdfxid:GTS_PDFXVersion><pdf:Trapped>{trapped}</pdf:Trapped><xmpMM:VersionID>1</xmpMM:VersionID>"
|
||||
"<pdfxid:GTS_PDFXVersion>{version}</pdfxid:GTS_PDFXVersion><pdf:Trapped>{trapped}</pdf:Trapped><xmpMM:VersionID>1</xmpMM:VersionID>"
|
||||
);
|
||||
edits.push((close, close, props.into_bytes()));
|
||||
// When the packet has no `<xmp:MetadataDate>` element, this adds one after the writer's
|
||||
|
||||
@@ -120,7 +120,16 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() {
|
||||
// The metadata agrees with the header; PDF/X-4 names its standard there too.
|
||||
let xmp_version = if standard == Standard::PdfX4 { "1.6" } else { "1.3" };
|
||||
assert!(t.contains(&format!("<pdf:PDFVersion>{xmp_version}</pdf:PDFVersion>")), "{standard:?}");
|
||||
assert_eq!(t.contains("<pdfxid:GTS_PDFXVersion xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\">PDF/X-4<"), standard == Standard::PdfX4);
|
||||
let xmp = xmp_packet(&r.bytes);
|
||||
let (_, description) = xmp.rsplit_once("<rdf:Description").expect("an XMP description");
|
||||
let (attributes, _) = description.split_once('>').expect("the end of the opening tag");
|
||||
let is_pdfx4 = standard == Standard::PdfX4;
|
||||
// Validators expect the version property to inherit its namespace from the description.
|
||||
assert_eq!(attributes.contains(r#"xmlns:pdfxid="http://www.npes.org/pdfx/ns/id/""#), is_pdfx4, "{standard:?}: {attributes}");
|
||||
assert_eq!(xmp_value(&xmp, "pdfxid:GTS_PDFXVersion"), is_pdfx4.then_some("PDF/X-4"), "{standard:?}");
|
||||
// The edited packet is still well-formed XML: the namespace is declared once.
|
||||
assert_eq!(attributes.matches("xmlns:pdfxid=").count(), usize::from(is_pdfx4), "{standard:?}: {attributes}");
|
||||
assert!(craft_xml::Options::default().strict().parse(xmp.as_bytes()).is_ok(), "{standard:?}: {xmp}");
|
||||
assert_eq!(t.contains("<pdf:Trapped>False</pdf:Trapped>"), standard == Standard::PdfX4);
|
||||
assert!(!t.contains("/Encrypt"), "{standard:?}");
|
||||
// The file reads back.
|
||||
|
||||
@@ -64,7 +64,9 @@ pub mod worker;
|
||||
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime};
|
||||
pub use manifest::{
|
||||
Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime,
|
||||
};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, RunJob, Step, heavy_terms, keep_modules};
|
||||
#[doc(hidden)]
|
||||
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
|
||||
|
||||
+253
-11
@@ -54,6 +54,9 @@ pub const MENU_PLACES: &[&[&str]] = &[
|
||||
&["View"],
|
||||
];
|
||||
|
||||
/// Most commands of one plug-in that one context menu lists (`menu.context`).
|
||||
pub const MAX_CONTEXT_COMMANDS: usize = 8;
|
||||
|
||||
/// Where a command's `menu` places it: in the menu at `path` (one of [`MENU_PLACES`]), after the
|
||||
/// built-in item labeled `after` (1 to 64 printable characters), or at the end of that menu when
|
||||
/// `after` is left out or names no built-in item there.
|
||||
@@ -64,9 +67,119 @@ pub struct MenuPlace {
|
||||
pub after: Option<String>,
|
||||
}
|
||||
|
||||
/// A context menu a command's `menu.context` lists it in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ContextMenu {
|
||||
/// The canvas context menu, while objects are selected.
|
||||
Canvas,
|
||||
/// The menu of a layer, group or object row of the Layers panel.
|
||||
Layers,
|
||||
}
|
||||
|
||||
impl ContextMenu {
|
||||
/// Its name in a manifest.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
ContextMenu::Canvas => "canvas",
|
||||
ContextMenu::Layers => "layers",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When a context menu item can be chosen (`when`); without one it always can.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ContextWhen {
|
||||
/// One or more objects are selected (in the Layers panel: one or more rows are clicked).
|
||||
Selection,
|
||||
/// Exactly one object, which is not a layer, is selected or clicked.
|
||||
OneObject,
|
||||
/// One of the objects selected or clicked is a type object.
|
||||
TypeObject,
|
||||
/// Every row clicked in the Layers panel is a layer or sublayer (Layers panel only).
|
||||
LayerRow,
|
||||
}
|
||||
|
||||
impl ContextWhen {
|
||||
const ALL: [(&'static str, ContextWhen); 4] = [
|
||||
("selection", ContextWhen::Selection),
|
||||
("oneObject", ContextWhen::OneObject),
|
||||
("typeObject", ContextWhen::TypeObject),
|
||||
("layerRow", ContextWhen::LayerRow),
|
||||
];
|
||||
|
||||
/// The conditions context menu `menu` takes: every one in the Layers panel, all but
|
||||
/// `layerRow` on the canvas.
|
||||
fn allowed(menu: ContextMenu) -> impl Iterator<Item = (&'static str, ContextWhen)> {
|
||||
Self::ALL.into_iter().filter(move |(_, w)| menu == ContextMenu::Layers || *w != ContextWhen::LayerRow)
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of a command's `menu.context`: the context menu that lists it and when its item can
|
||||
/// be chosen.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct ContextPlace {
|
||||
pub menu: ContextMenu,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub when: Option<ContextWhen>,
|
||||
}
|
||||
|
||||
impl ContextPlace {
|
||||
/// Reads `menu.context`: a list of `{"menu": "canvas" | "layers", "when"?: condition}`, each
|
||||
/// menu at most once.
|
||||
fn read_list(v: &Value) -> std::result::Result<Vec<ContextPlace>, String> {
|
||||
let Some(list) = v.as_array() else {
|
||||
let key = "menu.context";
|
||||
return Err(format!("`{key}` must be a list"));
|
||||
};
|
||||
let mut out: Vec<ContextPlace> = Vec::with_capacity(list.len().min(2));
|
||||
for (i, entry) in list.iter().enumerate() {
|
||||
let Some(o) = entry.as_object() else {
|
||||
let key = format!("menu.context[{i}]");
|
||||
return Err(format!("`{key}` must be an object"));
|
||||
};
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "menu" | "when")) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(format!("unknown key `{k}`; the keys here are {}", "menu, when"));
|
||||
}
|
||||
let menu = match o.get("menu").and_then(Value::as_str) {
|
||||
Some("canvas") => ContextMenu::Canvas,
|
||||
Some("layers") => ContextMenu::Layers,
|
||||
_ => {
|
||||
let k = format!("menu.context[{i}].menu");
|
||||
return Err(format!("`{k}` must be one of {}", "\"canvas\", \"layers\""));
|
||||
}
|
||||
};
|
||||
let when = match o.get("when") {
|
||||
None => None,
|
||||
Some(w) => {
|
||||
let found = w.as_str().and_then(|w| ContextWhen::allowed(menu).find(|(name, _)| *name == w));
|
||||
match found {
|
||||
Some((_, when)) => Some(when),
|
||||
None => {
|
||||
let k = format!("menu.context[{i}].when");
|
||||
let names: Vec<String> = ContextWhen::allowed(menu).map(|(name, _)| format!("{name:?}")).collect();
|
||||
return Err(format!("`{k}` must be one of {}", names.join(", ")));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if out.iter().any(|p| p.menu == menu) {
|
||||
let (key, name) = ("menu.context", menu.name());
|
||||
return Err(format!("`{key}` names \"{name}\" twice"));
|
||||
}
|
||||
out.push(ContextPlace { menu, when });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl MenuPlace {
|
||||
/// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`.
|
||||
fn read(v: &Value) -> std::result::Result<MenuPlace, String> {
|
||||
/// Reads a command's `menu` value: `{"path"?: [label, …], "after"?: label, "context"?: [...]}`
|
||||
/// ([`ContextPlace::read_list`]). `path` may be left out only when `context` is given, and
|
||||
/// `after` only goes with `path`.
|
||||
fn read(v: &Value) -> std::result::Result<(Option<MenuPlace>, Vec<ContextPlace>), String> {
|
||||
let wrong_path = || {
|
||||
let k = "menu.path";
|
||||
let places: Vec<String> =
|
||||
@@ -77,9 +190,16 @@ impl MenuPlace {
|
||||
let key = "menu";
|
||||
return Err(format!("`{key}` must be an object"));
|
||||
};
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after")) {
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after" | "context")) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(format!("unknown key `{k}`; the keys here are {}", "path, after"));
|
||||
return Err(format!("unknown key `{k}`; the keys here are {}", "path, after, context"));
|
||||
}
|
||||
let context = match o.get("context") {
|
||||
Some(c) => ContextPlace::read_list(c)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
if o.get("context").is_some() && !o.contains_key("path") && !o.contains_key("after") {
|
||||
return Ok((None, context));
|
||||
}
|
||||
let path: Vec<&str> = match o.get("path").and_then(Value::as_array) {
|
||||
Some(path) => path.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(wrong_path)?,
|
||||
@@ -98,7 +218,7 @@ impl MenuPlace {
|
||||
}
|
||||
Some(_) => return Err(format!("`{key}` must be a string")),
|
||||
};
|
||||
Ok(MenuPlace { path, after })
|
||||
Ok((Some(MenuPlace { path, after }), context))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,7 +484,7 @@ pub struct Param {
|
||||
/// plug-in's name (Effect › Plug-ins for a live effect's), or in the menu its `menu` names, runs it
|
||||
/// as the command `plugin.<plug-in id>.<id>`, and calls the plug-in's `vc_run` with
|
||||
/// `_context.command` set to `id` and the parameters it declares.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
pub struct Command {
|
||||
/// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest.
|
||||
pub id: String,
|
||||
@@ -376,13 +496,45 @@ pub struct Command {
|
||||
pub params: Vec<(String, Param)>,
|
||||
/// The menu it is listed in instead of the plug-in's submenu (`menu`, read at
|
||||
/// [`crate::permissions::MENU_API`] and later).
|
||||
#[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")]
|
||||
#[serde(skip)]
|
||||
pub place: Option<MenuPlace>,
|
||||
/// The context menus that also list it (`menu.context`, read at
|
||||
/// [`crate::permissions::MENU_API`] and later), at most one entry per menu.
|
||||
#[serde(skip)]
|
||||
pub context: Vec<ContextPlace>,
|
||||
/// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them.
|
||||
#[serde(skip)]
|
||||
pub(crate) declared_menu: Vec<Value>,
|
||||
}
|
||||
|
||||
/// A command as its manifest gives it: `id`, `label`, `params` and, when it has a place or context
|
||||
/// menus, `menu` with its `path`, `after` and `context`.
|
||||
impl Serialize for Command {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
fn params<S: serde::Serializer>(p: &&[(String, Param)], s: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
params_as_object(p, s)
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Menu<'a> {
|
||||
#[serde(flatten)]
|
||||
place: Option<&'a MenuPlace>,
|
||||
#[serde(skip_serializing_if = "<[_]>::is_empty")]
|
||||
context: &'a [ContextPlace],
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Shown<'a> {
|
||||
id: &'a str,
|
||||
label: &'a str,
|
||||
#[serde(serialize_with = "params")]
|
||||
params: &'a [(String, Param)],
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
menu: Option<Menu<'a>>,
|
||||
}
|
||||
let menu = (self.place.is_some() || !self.context.is_empty()).then_some(Menu { place: self.place.as_ref(), context: &self.context });
|
||||
Shown { id: &self.id, label: &self.label, params: &self.params, menu }.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl Command {
|
||||
/// The label as menus and errors show it: control and bidirectional characters escaped, at
|
||||
/// most [`crate::permissions::MAX_SHOWN_NAME`] characters.
|
||||
@@ -612,7 +764,7 @@ impl Manifest {
|
||||
continue;
|
||||
}
|
||||
let name = command_name(i, &c.id);
|
||||
let place = match menus.as_slice() {
|
||||
let read = match menus.as_slice() {
|
||||
[] => continue,
|
||||
[menu] => MenuPlace::read(menu),
|
||||
_ => {
|
||||
@@ -620,11 +772,27 @@ impl Manifest {
|
||||
Err(format!("duplicate field `{key}`"))
|
||||
}
|
||||
};
|
||||
c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?);
|
||||
(c.place, c.context) = read.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?;
|
||||
}
|
||||
// Each context menu lists at most MAX_CONTEXT_COMMANDS of the plug-in's commands; the
|
||||
// error names the first command past that.
|
||||
for menu in [ContextMenu::Canvas, ContextMenu::Layers] {
|
||||
let mut listed = self.commands.iter().enumerate().filter(|(_, c)| c.context.iter().any(|p| p.menu == menu));
|
||||
if let Some((i, c)) = listed.nth(MAX_CONTEXT_COMMANDS) {
|
||||
let (name, key) = (command_name(i, &c.id), "menu.context");
|
||||
let e = format!("`{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu");
|
||||
return Err(Error::Manifest(format!("command {name}: {e}")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The commands context menu `menu` lists (`menu.context`), in manifest order, each with when
|
||||
/// its item can be chosen.
|
||||
pub fn context_commands(&self, menu: ContextMenu) -> impl Iterator<Item = (&Command, Option<ContextWhen>)> {
|
||||
self.commands.iter().filter_map(move |c| c.context.iter().find(|p| p.menu == menu).map(|p| (c, p.when)))
|
||||
}
|
||||
|
||||
/// Checks what the module declared: its id, name and text lengths, its extensions, a budget its
|
||||
/// kind may have (only a filter may be heavy), and each parameter and its dialog layout.
|
||||
fn validate(&self) -> Result<()> {
|
||||
@@ -1192,7 +1360,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
|
||||
let Some(label) = label else {
|
||||
return Err(named(&Some(id), &"missing field `label`"));
|
||||
};
|
||||
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, declared_menu: menu })
|
||||
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, context: Vec::new(), declared_menu: menu })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1772,7 +1940,9 @@ mod tests {
|
||||
assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none());
|
||||
let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap();
|
||||
assert_eq!(effect.commands.len(), 1);
|
||||
let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, declared_menu: Vec::new() }.shown_label();
|
||||
let label = |l: &str| {
|
||||
Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, context: Vec::new(), declared_menu: Vec::new() }.shown_label()
|
||||
};
|
||||
assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe");
|
||||
|
||||
let many: Vec<String> = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect();
|
||||
@@ -1887,6 +2057,78 @@ mod tests {
|
||||
assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`"));
|
||||
}
|
||||
|
||||
/// At API level 2 a command's `menu.context` lists it in the canvas and Layers panel context
|
||||
/// menus, each with an optional `when` from a fixed list, with or without a `path`. A context
|
||||
/// entry of the wrong shape, an unknown menu or condition, `layerRow` on the canvas, a menu
|
||||
/// named twice and more than [`MAX_CONTEXT_COMMANDS`] commands in one menu are refused, and the
|
||||
/// error names the command and the key. At level 1 the key is ignored.
|
||||
#[test]
|
||||
fn a_command_menu_context_lists_it_in_context_menus() {
|
||||
let with = |api: u32, menu: &str| {
|
||||
format!(r#"{{"id":"org.example.t","name":"Tidy","api":{api},"kind":"filter","commands":[{{"id":"tidy","label":"Tidy","menu":{menu}}}]}}"#)
|
||||
};
|
||||
let m = Manifest::parse(with(2, r#"{"context":[{"menu":"canvas","when":"typeObject"},{"menu":"layers"}]}"#).as_bytes()).unwrap();
|
||||
let c = &m.commands[0];
|
||||
assert_eq!(c.place, None, "no other menu: it stays in its plug-in's submenu");
|
||||
assert_eq!(
|
||||
c.context,
|
||||
vec![
|
||||
ContextPlace { menu: ContextMenu::Canvas, when: Some(ContextWhen::TypeObject) },
|
||||
ContextPlace { menu: ContextMenu::Layers, when: None }
|
||||
]
|
||||
);
|
||||
assert_eq!(c.menu_label(&m.name), "Tidy", "a context item is not renamed");
|
||||
assert_eq!(m.context_commands(ContextMenu::Layers).map(|(c, w)| (c.id.as_str(), w)).collect::<Vec<_>>(), [("tidy", None)]);
|
||||
let both = Manifest::parse(with(2, r#"{"path":["Select"],"context":[{"menu":"layers","when":"layerRow"}]}"#).as_bytes()).unwrap();
|
||||
assert_eq!(both.commands[0].place, Some(MenuPlace { path: &["Select"], after: None }));
|
||||
assert_eq!(both.commands[0].context, vec![ContextPlace { menu: ContextMenu::Layers, when: Some(ContextWhen::LayerRow) }]);
|
||||
// The manifest a plug-in's info gives carries the context menus, with or without a place.
|
||||
assert_eq!(
|
||||
serde_json::to_value(&both.commands[0]).unwrap()["menu"],
|
||||
json!({"path": ["Select"], "context": [{"menu": "layers", "when": "layerRow"}]})
|
||||
);
|
||||
assert_eq!(serde_json::to_value(c).unwrap()["menu"], json!({"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers"}]}));
|
||||
let plain = Manifest::parse(with(2, r#"{"context":[]}"#).as_bytes()).unwrap();
|
||||
assert!(serde_json::to_value(&plain.commands[0]).unwrap().get("menu").is_none(), "no place and no context menu: no `menu`");
|
||||
assert!(Manifest::parse(with(2, r#"{"context":[]}"#).as_bytes()).unwrap().commands[0].context.is_empty());
|
||||
assert!(Manifest::parse(with(1, r#"{"context":[{"menu":"sky"}]}"#).as_bytes()).unwrap().commands[0].context.is_empty(), "ignored at level 1");
|
||||
|
||||
for (menu, says) in [
|
||||
(r#"{"context":"canvas"}"#, "`menu.context` must be a list"),
|
||||
(r#"{"context":["canvas"]}"#, "`menu.context[0]` must be an object"),
|
||||
(r#"{"context":[{"menu":"canvas","if":"selection"}]}"#, "unknown key `if`"),
|
||||
(r#"{"context":[{"menu":"Canvas"}]}"#, "`menu.context[0].menu` must be one of \"canvas\", \"layers\""),
|
||||
(r#"{"context":[{}]}"#, "`menu.context[0].menu` must be one of"),
|
||||
(r#"{"context":[{"menu":"layers"},{"menu":"canvas","when":"always"}]}"#, "`menu.context[1].when` must be one of"),
|
||||
(
|
||||
r#"{"context":[{"menu":"canvas","when":"layerRow"}]}"#,
|
||||
"`menu.context[0].when` must be one of \"selection\", \"oneObject\", \"typeObject\"",
|
||||
),
|
||||
(r#"{"context":[{"menu":"canvas","when":1}]}"#, "`menu.context[0].when` must be one of"),
|
||||
(r#"{"context":[{"menu":"canvas"},{"menu":"canvas"}]}"#, "`menu.context` names \"canvas\" twice"),
|
||||
(r#"{"after":"Inverse","context":[{"menu":"canvas"}]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["File"],"context":[{"menu":"canvas"}]}"#, "`menu.path` must be one of"),
|
||||
] {
|
||||
let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains("command `tidy`") && e.contains(says), "{menu}: {e}");
|
||||
}
|
||||
|
||||
let listed = |n: usize, menu: &str| {
|
||||
let commands: Vec<String> =
|
||||
(0..n).map(|i| format!(r#"{{"id":"c{i}","label":"C{i}","menu":{{"context":[{{"menu":"{menu}"}}]}}}}"#)).collect();
|
||||
format!(r#"{{"id":"a","name":"x","api":2,"kind":"filter","commands":[{}]}}"#, commands.join(","))
|
||||
};
|
||||
for menu in ["canvas", "layers"] {
|
||||
assert_eq!(
|
||||
Manifest::parse(listed(MAX_CONTEXT_COMMANDS, menu).as_bytes()).unwrap().context_commands(ContextMenu::Canvas).count(),
|
||||
if menu == "canvas" { MAX_CONTEXT_COMMANDS } else { 0 }
|
||||
);
|
||||
let e = Manifest::parse(listed(MAX_CONTEXT_COMMANDS + 1, menu).as_bytes()).unwrap_err().to_string();
|
||||
let past = format!("command `c{MAX_CONTEXT_COMMANDS}`");
|
||||
assert!(e.contains(&past) && e.contains("`menu.context`: a plug-in may put at most 8 commands in each context menu"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_and_number_lists_resolve_like_the_other_types() {
|
||||
let m = Manifest::parse(
|
||||
|
||||
@@ -756,7 +756,14 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b
|
||||
NodeKind::Blend { .. } => {
|
||||
let b = n.reach_bounds_with(symbols)?;
|
||||
let a = live_content_reach(symbols, n);
|
||||
vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_blend_effect_bounds(symbols, n))
|
||||
vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_live_effect_bounds(symbols, n))
|
||||
}
|
||||
// A radial or mirror repeat rotates or reflects each copy before applying the source's
|
||||
// geometry effects.
|
||||
NodeKind::Repeat(_) => {
|
||||
let b = n.visual_bounds_with(symbols)?;
|
||||
let a = live_content_reach(symbols, n);
|
||||
vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_live_effect_bounds(symbols, n))
|
||||
}
|
||||
_ => {
|
||||
let b = n.visual_bounds_with(symbols)?;
|
||||
@@ -841,7 +848,7 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) ->
|
||||
/// (Revolve builds no art from type).
|
||||
fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let b = match &n.kind {
|
||||
NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_blend_effect_bounds(symbols, n)),
|
||||
NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_live_effect_bounds(symbols, n)),
|
||||
_ => n.visual_bounds_with(symbols),
|
||||
}?;
|
||||
Some(match &n.kind {
|
||||
@@ -850,13 +857,15 @@ fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A rotated blend's effect-bearing content, measured after spine placement. Geometry effects
|
||||
/// run on the placed shapes, so their reach on the original keys need not cover what they paint.
|
||||
/// Effect-free blends keep the quick rail envelope without evaluating their steps.
|
||||
fn placed_blend_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let NodeKind::Blend { spec, .. } = &n.kind else { return None };
|
||||
if spec.orientation != vectorcraft_doc::BlendOrientation::AlignToPath {
|
||||
return None;
|
||||
/// A radial or mirror repeat's copies or a spine-aligned blend's steps, measured after they are
|
||||
/// rotated or reflected. Geometry effects run on the placed shapes, so their reach on the source
|
||||
/// need not cover what they paint.
|
||||
/// Without effects, the renderer keeps the quick bounds without evaluating the copies or steps.
|
||||
fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
match &n.kind {
|
||||
NodeKind::Blend { spec, .. } if spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath => {}
|
||||
NodeKind::Repeat(r) if matches!(r.kind, vectorcraft_doc::RepeatKind::Radial { .. } | vectorcraft_doc::RepeatKind::Mirror { .. }) => {}
|
||||
_ => return None,
|
||||
}
|
||||
let mut has_effects = false;
|
||||
n.walk(&mut |c| {
|
||||
|
||||
@@ -171,6 +171,62 @@ fn moving_a_shadowed_object_changes_where_its_shadow_falls() {
|
||||
assert!(a.x1 > 86.0 && a.y1 > 70.0, "the shadow, before and after: {a:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_a_radial_repeat_redraws_the_effects_on_its_rotated_copies() {
|
||||
for effected in [false, true] {
|
||||
let mut old = Document::new(110.0, 80.0);
|
||||
let source_id = old.alloc_id();
|
||||
let mut source = Node::path(
|
||||
source_id,
|
||||
shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
if effected {
|
||||
source.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "distort.transform".into(),
|
||||
params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}),
|
||||
visible: true,
|
||||
});
|
||||
}
|
||||
let repeat = vectorcraft_doc::RepeatSpec::radial(vec![Arc::new(source)], 4, Some(12.0));
|
||||
let id = old.alloc_id();
|
||||
old.insert(Some(old.layers[0].id), 0, Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat))).unwrap();
|
||||
let mut moved = old.clone();
|
||||
moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false);
|
||||
// A partial redraw must reproduce the whole frame, both on the move and on Undo.
|
||||
area(redraw(&old, &moved));
|
||||
area(redraw(&moved, &old));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_a_slanted_mirror_repeat_redraws_the_effects_on_its_reflected_copy() {
|
||||
for effected in [false, true] {
|
||||
let mut old = Document::new(110.0, 80.0);
|
||||
let source_id = old.alloc_id();
|
||||
let mut source = Node::path(
|
||||
source_id,
|
||||
shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
if effected {
|
||||
source.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "distort.transform".into(),
|
||||
params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}),
|
||||
visible: true,
|
||||
});
|
||||
}
|
||||
let repeat = vectorcraft_doc::RepeatSpec::mirror(vec![Arc::new(source)], 45.0, 6.0);
|
||||
let id = old.alloc_id();
|
||||
old.insert(Some(old.layers[0].id), 0, Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat))).unwrap();
|
||||
let mut moved = old.clone();
|
||||
moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false);
|
||||
// A partial redraw must reproduce the whole frame, both on the move and on Undo.
|
||||
area(redraw(&old, &moved));
|
||||
area(redraw(&moved, &old));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_removing_and_restacking_change_those_objects() {
|
||||
let (old, [loose, _, _, _, other]) = document();
|
||||
|
||||
@@ -262,6 +262,9 @@ fn distance_overlays(cx: &ToolContext, to: DistanceTo) -> Vec<Overlay> {
|
||||
/// it snaps to the original too.
|
||||
pub(crate) struct MoveSnap {
|
||||
bounds: Option<Rect>,
|
||||
/// The selection's geometric bounds, which Smart Guides line up with the other art's geometric
|
||||
/// bounds and space evenly between them, whether Use Preview Bounds is on or off (#6436).
|
||||
edges: Option<Rect>,
|
||||
targets: Option<Targets>,
|
||||
points: Option<Targets>,
|
||||
/// The targets and points for a copy, gathered with the others before the previews move the
|
||||
@@ -300,6 +303,7 @@ impl MoveSnap {
|
||||
let points = |exclude: &[NodeId]| if cx.snap_to_grid { None } else { Targets::snap_to_point(cx, exclude) };
|
||||
Self {
|
||||
bounds: selection_bounds(cx),
|
||||
edges: guides.then(|| cx.doc.bounds_of(&cx.selection.objects, false)).flatten(),
|
||||
targets: guides.then(|| for_move(cx, &cx.selection.objects)),
|
||||
points: points(&cx.selection.objects),
|
||||
copy_targets: guides.then(|| for_move(cx, &[])),
|
||||
@@ -312,7 +316,7 @@ impl MoveSnap {
|
||||
/// Snap to Grid and Snap to Pixel alone, for a move whose box is `bounds`: the grid lands an
|
||||
/// edge of the box on a gridline, and pixels put its top-left on whole pixels.
|
||||
pub(crate) fn grid_only(bounds: Option<Rect>) -> Self {
|
||||
Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false }
|
||||
Self { bounds, edges: None, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false }
|
||||
}
|
||||
|
||||
/// The ruler guides stopped showing since the move began (View › Hide Guides, or Trim View,
|
||||
@@ -353,7 +357,7 @@ impl MoveSnap {
|
||||
// The grabbed anchor landed on a path or a crossing, which a ruler guide does not pull
|
||||
// it off.
|
||||
let mut on_path = false;
|
||||
if let (Some(t), Some(b)) = (targets, self.bounds) {
|
||||
if let (Some(t), Some(b)) = (targets, self.edges) {
|
||||
// The point the selection was grabbed by, near another object's anchor or centre,
|
||||
// lands on it, rather than the bounds lining up a little beside it (#955).
|
||||
if t.has_point_near(start + d, cx.snap_tol()) {
|
||||
@@ -434,7 +438,7 @@ impl MoveSnap {
|
||||
d = q - start;
|
||||
guides = ov;
|
||||
}
|
||||
if let (Some(t), Some(b)) = (targets, self.bounds) {
|
||||
if let (Some(t), Some(b)) = (targets, self.edges) {
|
||||
if t.has_point_near(start + d, cx.snap_tol()) {
|
||||
let (q, ov) = t.snap_point_along(start + d, u, cx.snap_tol());
|
||||
d = q - start;
|
||||
|
||||
@@ -1255,6 +1255,42 @@ fn an_alt_copy_snaps_to_the_original_left_behind() {
|
||||
assert_eq!(dx(&t.pointer(&c, &ev(PointerKind::Drag, 253.0, 150.0))), 103.0);
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, Smart Guides line up the moved selection's geometric bounds with
|
||||
/// the other art's, as they do with it off: an edge lands exactly on the other path's edge, and the
|
||||
/// edge of a stroke does not pull it there (#6436).
|
||||
#[test]
|
||||
fn a_move_lines_up_geometric_edges_with_use_preview_bounds_on() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Node};
|
||||
// An artboard whose edges and center are out of reach, and two rectangles stroked 20 pt.
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut add = |r: Rect| {
|
||||
let id = d.alloc_id();
|
||||
let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0);
|
||||
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap();
|
||||
id
|
||||
};
|
||||
let a = add(Rect::new(100.0, 100.0, 200.0, 200.0));
|
||||
add(Rect::new(300.0, 100.0, 400.0, 200.0));
|
||||
let s = Selection { objects: vec![a], ..Default::default() };
|
||||
let p = paint();
|
||||
for preview in [false, true] {
|
||||
let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) };
|
||||
let dragged = |to: f64| {
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0));
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0));
|
||||
let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") };
|
||||
(v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap())
|
||||
};
|
||||
// The right edge, 1 pt short of the other rectangle's left edge (x = 300), lands on it.
|
||||
assert_eq!(dragged(249.0), (100.0, 0.0), "preview {preview}");
|
||||
// 9 pt short, it stays where it is dragged, though the edge of its stroke is 1 pt past there.
|
||||
assert_eq!(dragged(241.0), (91.0, 0.0), "preview {preview}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Smart Guides › Snap to Last Location: a move that comes within Snapping Tolerance of where it
|
||||
/// began goes back there, labeled "last location", a Shift move too; farther out, with the option
|
||||
/// or Smart Guides off, it stays where it is dragged, and an Alt copy snaps as it does with the
|
||||
|
||||
@@ -440,7 +440,8 @@ impl Tool for BrushPaintTool {
|
||||
}
|
||||
/// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus
|
||||
/// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values
|
||||
/// differ, or an Art brush whose width is on it with two different widths.
|
||||
/// differ, an Art brush whose width is on it with two different widths, or a Pattern brush
|
||||
/// whose scale is on it with two different scales.
|
||||
fn reads_wheel(&self, cx: &ToolContext) -> bool {
|
||||
use vectorcraft_brush::{BrushKind, Variation};
|
||||
let wheel = |mode: Variation| mode == Variation::StylusWheel;
|
||||
@@ -449,7 +450,8 @@ impl Tool for BrushPaintTool {
|
||||
BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0),
|
||||
BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b),
|
||||
BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1,
|
||||
BrushKind::Pattern(_) | BrushKind::Bristle(_) => false,
|
||||
BrushKind::Pattern(p) => p.scale_mode.is_some_and(wheel) && p.scale_range().0 != p.scale_range().1,
|
||||
BrushKind::Bristle(_) => false,
|
||||
}
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
@@ -775,7 +777,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() {
|
||||
use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation};
|
||||
use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, PatternBrush, Scatter, Variation};
|
||||
let wheel = Variation::StylusWheel;
|
||||
let calligraphic =
|
||||
|modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() });
|
||||
@@ -783,6 +785,7 @@ mod tests {
|
||||
BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() })
|
||||
};
|
||||
let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() });
|
||||
let pattern = |scale_mode, scale_max| BrushKind::Pattern(PatternBrush { scale_mode, scale_max: Some(scale_max), ..PatternBrush::default() });
|
||||
let library = [
|
||||
Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) },
|
||||
Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) },
|
||||
@@ -792,6 +795,9 @@ mod tests {
|
||||
Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) },
|
||||
Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) },
|
||||
Brush { name: "Flat".into(), kind: art(None, 200.0) },
|
||||
Brush { name: "Tiles".into(), kind: pattern(Some(wheel), 200.0) },
|
||||
Brush { name: "Even tiles".into(), kind: pattern(Some(wheel), 100.0) },
|
||||
Brush { name: "Fixed tiles".into(), kind: pattern(None, 200.0) },
|
||||
];
|
||||
let (mut d, _) = doc_with_rect();
|
||||
d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap());
|
||||
@@ -808,6 +814,9 @@ mod tests {
|
||||
("Taper", true),
|
||||
("Even taper", false),
|
||||
("Flat", false),
|
||||
("Tiles", true),
|
||||
("Even tiles", false),
|
||||
("Fixed tiles", false),
|
||||
("Deleted", false),
|
||||
];
|
||||
for (name, varies) in brushes {
|
||||
|
||||
@@ -395,7 +395,7 @@ fn compass(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<Can
|
||||
return None;
|
||||
}
|
||||
let mut turn = space.view.rotation;
|
||||
let rect = RotateView::compass_rect(ui, space.view.rect);
|
||||
let rect = RotateView::compass_rect(ui, clear_of_scroll_bars(app, ui, space.view.rect));
|
||||
RotateView::new(tl!("Rotate View"), Bind::bound(&mut turn), false).show_at(ui, rect);
|
||||
(turn != space.view.rotation).then(|| {
|
||||
let mut view = space.view;
|
||||
@@ -404,6 +404,17 @@ fn compass(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<Can
|
||||
})
|
||||
}
|
||||
|
||||
/// `rect` without the strip the vertical scroll bar takes along its right edge (the bar's thickness and its margin,
|
||||
/// the sizes `CanvasScrollbars` draws with), in the screen modes that show the scroll bars.
|
||||
fn clear_of_scroll_bars(app: &VectorcraftApp, ui: &Ui, rect: egui::Rect) -> egui::Rect {
|
||||
if app.ui.screen_mode >= 2 {
|
||||
return rect;
|
||||
}
|
||||
let env = Env::of(ui);
|
||||
let strip = env.tokens.size.icon.md + env.tokens.space.gap.tight;
|
||||
egui::Rect::from_min_max(rect.min, egui::pos2((rect.right() - strip).max(rect.left()), rect.bottom()))
|
||||
}
|
||||
|
||||
/// The scroll bars along the right and bottom edges (Normal and Full Screen with Menu Bar): the view
|
||||
/// a thumb drag or page press moved.
|
||||
fn scroll_bars(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<CanvasView> {
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::json;
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
|
||||
use super::BodyKind;
|
||||
use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key};
|
||||
use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key, snapped_rect};
|
||||
use crate::doc_windows::Win;
|
||||
use crate::state::View;
|
||||
use crate::{CacheKey, VectorcraftApp};
|
||||
@@ -141,6 +141,7 @@ impl PaneSource {
|
||||
pub(super) fn new(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, cv: &CanvasView) -> Option<PaneSource> {
|
||||
let env = Env::of_root(ctx);
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let device_ppp = ppp;
|
||||
let space = cv.rect;
|
||||
let v = crate::doc_windows::view(app, w).copied()?;
|
||||
let st = app.session.documents().get(w.0)?;
|
||||
@@ -165,7 +166,12 @@ impl PaneSource {
|
||||
Some([x0, y0, x1, y1]) => {
|
||||
egui::Rect::from_two_pos(cv.to_screen(Point::new(x0 as f64, y0 as f64)), cv.to_screen(Point::new(x1 as f64, y1 as f64)))
|
||||
}
|
||||
None => space,
|
||||
// The frame's own pixel size, centered on the pane and on whole device pixels, so each
|
||||
// of its pixels covers one device pixel.
|
||||
None => {
|
||||
let size = egui::vec2(pw as f32 / ppp, ph as f32 / ppp);
|
||||
snapped_rect(space.center() - size / 2.0, size, device_ppp)
|
||||
}
|
||||
};
|
||||
let frame = PaneFrame {
|
||||
key: PaneKey { slot: (st.uid, w.1) },
|
||||
|
||||
@@ -313,6 +313,18 @@ pub(super) fn frame_ppp(size: egui::Vec2, ppp: f32, max_side: usize) -> f32 {
|
||||
if longest.round() <= max { ppp } else { ppp * (max / longest) }
|
||||
}
|
||||
|
||||
/// Where a frame drawn `size` points across from `min` goes on a display of `device_ppp` pixels a
|
||||
/// point: `min` moved to the nearest device pixel, the size unchanged. A canvas whose corner falls
|
||||
/// between device pixels would otherwise draw every pixel of the frame across two device pixels,
|
||||
/// and each edge in the art would show as a soft double line.
|
||||
pub(super) fn snapped_rect(min: egui::Pos2, size: egui::Vec2, device_ppp: f32) -> egui::Rect {
|
||||
if !(device_ppp.is_finite() && device_ppp > 0.0) {
|
||||
return egui::Rect::from_min_size(min, size);
|
||||
}
|
||||
let snap = |c: f32| (c * device_ppp).round() / device_ppp;
|
||||
egui::Rect::from_min_size(pos2(snap(min.x), snap(min.y)), size)
|
||||
}
|
||||
|
||||
/// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view
|
||||
/// included. None when the view is degenerate, or when a side of the region is more than
|
||||
/// `max_side` pixels, the largest texture side the display supports.
|
||||
@@ -975,7 +987,8 @@ fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, view: &CanvasV
|
||||
let old = CanvasView::new(old_rect, Point::new(k.cx, k.cy), k.zoom).rotation(rotation);
|
||||
let a = view.to_screen(old.to_doc(old_rect.min));
|
||||
let b = view.to_screen(old.to_doc(old_rect.max));
|
||||
painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
let placed = snapped_rect(a, b - a, painter.pixels_per_point());
|
||||
painter.image(tex.id(), placed, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
// The view turned after the last frame was rendered, and the worker renders the frame at
|
||||
// the new angle. Until it arrives, the last frame is drawn turned into this view: each
|
||||
|
||||
@@ -1191,6 +1191,45 @@ fn the_art_renders_within_the_largest_texture_side() {
|
||||
assert_eq!(pixel_region(&view, 1024), None, "more than the display's largest texture");
|
||||
}
|
||||
|
||||
/// On a display of 2 pixels a point, a canvas whose corner falls between device pixels still draws
|
||||
/// its art's frame on whole device pixels at its own size, so each frame pixel covers one device
|
||||
/// pixel and a stroke's edges stay sharp instead of spreading over two device pixels.
|
||||
#[test]
|
||||
fn the_art_lands_on_whole_device_pixels() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width":400,"height":300})).unwrap();
|
||||
app.canvas.worker_started = true; // every frame on this thread
|
||||
let ctx = crate::testing::ui_context();
|
||||
ctx.set_pixels_per_point(2.0);
|
||||
let mut shapes = vec![];
|
||||
// The first frame sets the pixels a point, the second draws at them.
|
||||
for _ in 0..2 {
|
||||
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(pos2(31.3, 19.7), vec2(800.3, 600.35))), ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui));
|
||||
out.textures_delta.clear();
|
||||
shapes = flat_shapes(out.shapes);
|
||||
}
|
||||
let ppp = ctx.pixels_per_point();
|
||||
assert_eq!(ppp, 2.0);
|
||||
let rect = app.canvas_view().unwrap().rect;
|
||||
let off_grid = |c: f32| ((c * ppp) - (c * ppp).round()).abs() > 0.01;
|
||||
assert!(off_grid(rect.min.x) || off_grid(rect.min.y), "the canvas {rect:?} starts between device pixels");
|
||||
let tex = app.canvas.texture.as_ref().expect("a rendered frame");
|
||||
let (tid, size) = (tex.id(), tex.size());
|
||||
let drawn = shapes
|
||||
.iter()
|
||||
.find_map(|s| match s {
|
||||
Shape::Mesh(m) if m.texture_id == tid => Some(m.calc_bounds()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the frame is drawn");
|
||||
for (c, what) in [(drawn.min.x, "left"), (drawn.min.y, "top")] {
|
||||
assert!(!off_grid(c), "the frame's {what} edge {c} is not on a device pixel");
|
||||
}
|
||||
assert!((drawn.width() * ppp - size[0] as f32).abs() < 0.01, "{} device pixels across for {} frame pixels", drawn.width() * ppp, size[0]);
|
||||
assert!((drawn.height() * ppp - size[1] as f32).abs() < 0.01, "{} device pixels down for {} frame pixels", drawn.height() * ppp, size[1]);
|
||||
}
|
||||
|
||||
/// `rgb` as the display transform `t` shows it.
|
||||
fn convert8(t: &craft::color_ui::display::DisplayTransform, rgb: [u8; 3]) -> [u8; 3] {
|
||||
let mut px = [rgb[0], rgb[1], rgb[2], 255];
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::cell::RefCell;
|
||||
use craft::behavior::IconId;
|
||||
use craft::menu::MenuBarUi;
|
||||
use craft::ui::buttons::{Button, IconButton, ToggleButton};
|
||||
use craft::ui::contract::{Bind, BodyCx, Props, Show, ShowContainer};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props, Show, ShowContainer};
|
||||
use craft::ui::display::Picture;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::primitives::IconSpec;
|
||||
@@ -114,17 +114,20 @@ fn leading(ui: &mut Ui, app: &mut VectorcraftApp) {
|
||||
}
|
||||
|
||||
/// The end of the bar: each ranked control in a row of its own, which the fitted title bar gives up whole, lowest rank
|
||||
/// first, before the menus narrow.
|
||||
/// first, before the menus narrow. The controls are `space.gap.item` apart, the gap between neighboring controls in a
|
||||
/// bar.
|
||||
fn trailing(ui: &mut Ui, app: &mut VectorcraftApp) {
|
||||
let safe = vectorcraft_plugins::safe_mode::active();
|
||||
for t in Trailing::SHOWN.into_iter().filter(|t| safe || *t != Trailing::Safe) {
|
||||
match t.rank() {
|
||||
Some(rank) => {
|
||||
Row::new().fit_rank(rank).show(ui, |ui, _| t.show(app, ui));
|
||||
Row::new().gap(Gap::Item).show(ui, |ui, _| {
|
||||
for t in Trailing::SHOWN.into_iter().filter(|t| safe || *t != Trailing::Safe) {
|
||||
match t.rank() {
|
||||
Some(rank) => {
|
||||
Row::new().fit_rank(rank).show(ui, |ui, _| t.show(app, ui));
|
||||
}
|
||||
None => t.show(app, ui),
|
||||
}
|
||||
None => t.show(app, ui),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The application bar, the body of the shell's title bar: brand mark, Home and menus, then Discord,
|
||||
|
||||
@@ -120,8 +120,15 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| {
|
||||
if let Some(i) =
|
||||
Select::new(tl!("Artboard"), Bind::given(cur), &boards).look(SelectLook::Filled).enabled(nab > 0).show(ui).events.committed().copied()
|
||||
// With no document the navigator shows a dash, as the info readout does.
|
||||
if let Some(i) = Select::new(tl!("Artboard"), Bind::given(cur), &boards)
|
||||
.placeholder("\u{2013}")
|
||||
.look(SelectLook::Filled)
|
||||
.enabled(nab > 0)
|
||||
.show(ui)
|
||||
.events
|
||||
.committed()
|
||||
.copied()
|
||||
{
|
||||
go = Some(json!(i));
|
||||
}
|
||||
@@ -264,6 +271,15 @@ mod tests {
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_no_document_the_artboard_navigator_shows_a_dash() {
|
||||
let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let mut panel = Panel::new(app, status_bar);
|
||||
panel.room(egui::vec2(1200.0, 300.0));
|
||||
panel.frame();
|
||||
assert_eq!(panel.value_role("Artboard", Role::COMBO_BOX).as_deref(), Some("\u{2013}"), "the empty navigator reads as a dash");
|
||||
}
|
||||
}
|
||||
|
||||
/// What the bar shows as work in progress: the running script, then background jobs, opens and places. The first
|
||||
|
||||
@@ -473,6 +473,28 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() {
|
||||
assert!(widest.zip(narrowest).is_some_and(|(w, n)| n >= w - 0.5), "the search keeps its width until it goes: {search_widths:?}");
|
||||
}
|
||||
|
||||
/// The app bar's right-hand controls stand at least `space.gap.item` apart, the gap between neighboring controls in a
|
||||
/// bar, so a hovered control's highlight does not touch the one beside it.
|
||||
#[test]
|
||||
fn the_app_bar_keeps_its_right_hand_controls_an_item_gap_apart() {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
let gap = Rc::new(std::cell::Cell::new(0.0_f32));
|
||||
let read = Rc::clone(&gap);
|
||||
let mut bar = Shown::new(app, egui::vec2(1600.0, 600.0), move |app, ui| {
|
||||
read.set(craft::ui::runtime::env::Env::of(ui).tokens.space.gap.item);
|
||||
app.ui(ui);
|
||||
});
|
||||
bar.frame(Vec::new()).frame(Vec::new());
|
||||
assert!(gap.get() > 0.0, "the item gap is read from the theme");
|
||||
let controls = ["Discord", "Search commands", "Choose a workspace"];
|
||||
let rects: Vec<egui::Rect> = controls.iter().map(|c| bar.starting(c).unwrap_or_else(|| panic!("{c} shows")).rect).collect();
|
||||
for pair in rects.windows(2) {
|
||||
let between = pair[1].left() - pair[0].right();
|
||||
assert!(between >= gap.get() - 0.5, "neighboring controls {pair:?} are {between} apart, under the item gap {}", gap.get());
|
||||
}
|
||||
}
|
||||
|
||||
/// A text the status bar painted, with where it lies.
|
||||
#[derive(Debug)]
|
||||
struct StatusText {
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
//! `widthMax` (the width at the heaviest pen pressure, upright or at 180°, %), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and
|
||||
//! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`,
|
||||
//! `overlap` (bend on each run between sharp corners).
|
||||
//! Pattern: `scale`, `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`,
|
||||
//! Pattern: `scale`, `scaleMax` (the scale at the heaviest pen pressure, upright, at 180° or at
|
||||
//! the wheel's far end, %), `scaleMode` (`fixed` | `pressure` | `tilt` | `bearing` | `rotation` |
|
||||
//! `stylusWheel`), `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`,
|
||||
//! `flipAcross`, and the tiles `outerCornerTile`, `sideTile`, `innerCornerTile`, `startTile` and
|
||||
//! `endTile` (`original`: the art the brush draws there | `none` | `pattern:<name>` | for a
|
||||
//! corner `autoCentered` | `autoBetween` | `autoSliced` | `autoOverlap`: a tile made from the side
|
||||
@@ -41,7 +43,7 @@ use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use craft::ui::runtime::requests::EyedropperRequest;
|
||||
use craft::ui::text::NumberField;
|
||||
use craft::ui::value_drag::{Slider, SliderScale};
|
||||
use craft::ui::value_drag::Slider;
|
||||
use egui::{Color32, ColorImage, Response, Ui};
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation};
|
||||
@@ -225,6 +227,8 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map<String, Value>) {
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
f.insert("scale".into(), json!(p.scale));
|
||||
f.insert("scaleMode".into(), json!(p.scale_mode.unwrap_or_default().id()));
|
||||
f.insert("scaleMax".into(), json!(p.scale_range().1));
|
||||
f.insert("spacing".into(), json!(p.spacing));
|
||||
f.insert("fit".into(), json!(id_of(&p.fit)));
|
||||
f.insert("flipAlong".into(), json!(p.flip_along));
|
||||
@@ -284,6 +288,66 @@ fn art_width_mode(f: &DialogFields) -> Variation {
|
||||
Variation::parse(&text(f, "widthMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed)
|
||||
}
|
||||
|
||||
/// How a pattern brush's scale varies: Fixed, or with the pen's pressure, tilt, bearing, rotation
|
||||
/// or wheel.
|
||||
fn pattern_scale_mode(f: &DialogFields) -> Variation {
|
||||
Variation::parse(&text(f, "scaleMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed)
|
||||
}
|
||||
|
||||
/// The second value (`max_key`, the definition's `def_max`) of a value that follows the pen (`key`,
|
||||
/// the same in the definition), for `brush.options` params. `null` in Options of Selected Object
|
||||
/// when the path it opened with has no second value and the second value has not been changed from
|
||||
/// the value it opened with, so each selected path keeps its own.
|
||||
fn second_value(f: &DialogFields, (key, max_key, def_max): (&str, &str, &str), range: (f64, f64)) -> Value {
|
||||
let v = clamped(f, max_key, range);
|
||||
let def = json_field(f, "__def");
|
||||
let opened = def.and_then(|def| def.get(key)).and_then(Value::as_f64);
|
||||
let unset = def.and_then(|def| def.get(def_max)).is_none_or(Value::is_null);
|
||||
let object = f.bool(super::brush_options::OBJECT).unwrap_or(false);
|
||||
if object && unset && opened == Some(v) { Value::Null } else { json!(v) }
|
||||
}
|
||||
|
||||
/// The modes an art brush's width and a pattern brush's scale offer, in menu order.
|
||||
const PEN_SIZE_MODES: [Variation; 6] =
|
||||
[Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel];
|
||||
|
||||
/// A value that can follow the pen (an art brush's Width, a pattern brush's Scale): its field and
|
||||
/// the fields of its second value and its [`PEN_SIZE_MODES`] menu.
|
||||
struct PenSize {
|
||||
key: &'static str,
|
||||
max_key: &'static str,
|
||||
mode_key: &'static str,
|
||||
/// The row's label and the name of its slider.
|
||||
label: &'static str,
|
||||
/// The names of the second value's field and of the menu.
|
||||
max_label: &'static str,
|
||||
mode_label: &'static str,
|
||||
range: (f64, f64),
|
||||
mode: fn(&DialogFields) -> Variation,
|
||||
}
|
||||
|
||||
/// The row of `size`: a slider, the second value (live only for a mode that follows the pen) and
|
||||
/// how the value varies.
|
||||
fn pen_size_row(size: PenSize) -> Param {
|
||||
let PenSize { key, max_key, mode_key, label, max_label, mode_label, range, mode } = size;
|
||||
Param::custom(key, label, move |ui, f, _| {
|
||||
let mode = mode(f);
|
||||
let entries = variation_entries(&PEN_SIZE_MODES);
|
||||
Row::new()
|
||||
.show(ui, |ui, _| {
|
||||
let slid = Slider::new(Bind::given(clamped(f, key, range)), range.0..=range.1).step(1.0).label(label).id_salt(key).show(ui);
|
||||
if let Some(value) = slid.events.landed() {
|
||||
// The slider quantizes new edits; Cancel restores the exact opening value.
|
||||
f.set(key, *value);
|
||||
}
|
||||
number_cell(ui, f, max_key, max_label, range, UnitKind::Percent, mode.follows_pen());
|
||||
id_select(ui, f, mode_key, mode_label, &entries, mode.id().to_string());
|
||||
})
|
||||
.output
|
||||
})
|
||||
.companions([max_key, mode_key])
|
||||
}
|
||||
|
||||
/// `brush.options` params from the fields.
|
||||
pub(super) fn params(f: &DialogFields) -> Value {
|
||||
let flag = |key: &str| f.bool(key).unwrap_or(false);
|
||||
@@ -313,7 +377,7 @@ pub(super) fn params(f: &DialogFields) -> Value {
|
||||
json!({
|
||||
"width": clamped(f, "width", ArtBrush::WIDTH_RANGE),
|
||||
"width_mode": if pen { json!(mode.id()) } else { Value::Null },
|
||||
"width_max": if pen { json!(clamped(f, "widthMax", ArtBrush::WIDTH_RANGE)) } else { Value::Null },
|
||||
"width_max": if pen { second_value(f, ("width", "widthMax", "width_max"), ArtBrush::WIDTH_RANGE) } else { Value::Null },
|
||||
"scale": serde_json::to_value(scale).unwrap_or_default(),
|
||||
"direction": id_of(&parse_field::<Direction>(f, "direction")),
|
||||
"flip_along": flag("flipAlong"),
|
||||
@@ -322,8 +386,12 @@ pub(super) fn params(f: &DialogFields) -> Value {
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
let mode = pattern_scale_mode(f);
|
||||
let pen = mode.follows_pen();
|
||||
let mut p = json!({
|
||||
"scale": clamped(f, "scale", PatternBrush::SCALE_RANGE),
|
||||
"scale_mode": if pen { json!(mode.id()) } else { Value::Null },
|
||||
"scale_max": if pen { second_value(f, ("scale", "scaleMax", "scale_max"), PatternBrush::SCALE_RANGE) } else { Value::Null },
|
||||
"spacing": clamped(f, "spacing", PatternBrush::SPACING_RANGE),
|
||||
"fit": id_of(&parse_field::<PatternFit>(f, "fit")),
|
||||
"flip_along": flag("flipAlong"),
|
||||
@@ -500,26 +568,16 @@ fn check(key: &str, label: &'static str) -> Param {
|
||||
|
||||
fn art_rows(object: bool) -> Vec<Param> {
|
||||
// Width, then the second width (only when the width follows the pen) and how it varies.
|
||||
let range = ArtBrush::WIDTH_RANGE;
|
||||
let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel];
|
||||
let width = Param::custom("width", tl!("Width"), move |ui, f, _| {
|
||||
let mode = art_width_mode(f);
|
||||
let entries = variation_entries(&modes);
|
||||
Row::new()
|
||||
.show(ui, |ui, _| {
|
||||
let slid =
|
||||
Slider::new(Bind::given(clamped(f, "width", range)), range.0..=range.1).step(1.0).label(tl!("Width")).id_salt("width").show(ui);
|
||||
if let Some(value) = slid.events.landed() {
|
||||
// The slider quantizes new edits; Cancel restores the exact opening width.
|
||||
f.set("width", *value);
|
||||
}
|
||||
number_cell(ui, f, "widthMax", tl!("Width"), range, UnitKind::Percent, mode.follows_pen());
|
||||
id_select(ui, f, "widthMode", tl!("Width"), &entries, mode.id().to_string());
|
||||
})
|
||||
.output
|
||||
})
|
||||
.companions(["widthMax", "widthMode"]);
|
||||
let mut rows = vec![width];
|
||||
let mut rows = vec![pen_size_row(PenSize {
|
||||
key: "width",
|
||||
max_key: "widthMax",
|
||||
mode_key: "widthMode",
|
||||
label: tl!("Width"),
|
||||
max_label: tl!("Width: Maximum"),
|
||||
mode_label: tl!("Width: Mode"),
|
||||
range: ArtBrush::WIDTH_RANGE,
|
||||
mode: art_width_mode,
|
||||
})];
|
||||
// A path sets its own width, flips, overlap and colorization, not how the art scales or runs.
|
||||
if !object {
|
||||
let scales = vec![
|
||||
@@ -558,8 +616,17 @@ fn direction_row() -> Param {
|
||||
}
|
||||
|
||||
fn pattern_rows(object: bool) -> Vec<Param> {
|
||||
let (lo, hi) = PatternBrush::SCALE_RANGE;
|
||||
let mut rows = vec![Param::new("scale", tl!("Scale"), ParamKind::range(lo, hi, 100.0, SliderScale::Linear)).unit(UnitKind::Percent)];
|
||||
// Scale, then the second scale (only when the scale follows the pen) and how it varies.
|
||||
let mut rows = vec![pen_size_row(PenSize {
|
||||
key: "scale",
|
||||
max_key: "scaleMax",
|
||||
mode_key: "scaleMode",
|
||||
label: tl!("Scale"),
|
||||
max_label: tl!("Scale: Maximum"),
|
||||
mode_label: tl!("Scale: Mode"),
|
||||
range: PatternBrush::SCALE_RANGE,
|
||||
mode: pattern_scale_mode,
|
||||
})];
|
||||
let (lo, hi) = PatternBrush::SPACING_RANGE;
|
||||
rows.push(Param::number("spacing", tl!("Spacing"), 0.0, 1.0, 0).bounds(Some(lo), Some(hi)).unit(UnitKind::Percent));
|
||||
// The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization.
|
||||
|
||||
@@ -188,7 +188,7 @@ fn canceled_art_width_drag_restores_the_opening_width() {
|
||||
let initial = fields_of(&panel.app()).number("width").unwrap();
|
||||
assert_eq!(initial, 100.25, "Cancel must preserve a valid fractional stored width");
|
||||
let mode = fields_of(&panel.app()).text("widthMode").map(str::to_owned);
|
||||
panel.click_role("Width", Role::COMBO_BOX);
|
||||
panel.click_role("Width: Mode", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
assert_eq!(fields_of(&panel.app()).text("widthMode").map(str::to_owned), mode);
|
||||
@@ -216,6 +216,56 @@ fn canceled_art_width_drag_restores_the_opening_width() {
|
||||
assert_eq!(panel.app().run("brush.get", json!({"name": "Arrow"})).unwrap(), original);
|
||||
}
|
||||
|
||||
/// Pattern Brush Options' Scale row: a held drag ended with Escape and a mode menu closed with
|
||||
/// Escape leave the open dialog's fields as they opened, and Cancel leaves the brush as it was; a
|
||||
/// released drag is kept by OK.
|
||||
#[test]
|
||||
fn canceled_pattern_scale_edits_do_not_reach_the_brush() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::Role;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
let mut app = app();
|
||||
app.run("brush.options", json!({"name": "Diamonds", "params": {"scale": 100.25}})).unwrap();
|
||||
let original = app.run("brush.get", json!({"name": "Diamonds"})).unwrap();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, draw_hosted_options);
|
||||
panel.room(egui::vec2(1000.0, 1000.0));
|
||||
open(&mut panel.app(), "Diamonds");
|
||||
panel.frame();
|
||||
let initial = fields_of(&panel.app()).number("scale").unwrap();
|
||||
assert_eq!(initial, 100.25, "Cancel must preserve a valid fractional stored scale");
|
||||
let mode = fields_of(&panel.app()).text("scaleMode").map(str::to_owned);
|
||||
panel.click_role("Scale: Mode", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
assert!(is_open(&panel.app()));
|
||||
assert_eq!(fields_of(&panel.app()).text("scaleMode").map(str::to_owned), mode);
|
||||
panel.drag_hold_role("Scale", Role::SLIDER, egui::vec2(40.0, 0.0));
|
||||
assert_ne!(fields_of(&panel.app()).number("scale"), Some(initial), "the held drag previews another scale");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.release();
|
||||
assert!(is_open(&panel.app()));
|
||||
assert_eq!(fields_of(&panel.app()).number("scale"), Some(initial), "the canceled drag restores the opening scale");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap(), original);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
|
||||
open(&mut panel.app(), "Diamonds");
|
||||
panel.frame();
|
||||
panel.drag_hold_role("Scale", Role::SLIDER, egui::vec2(40.0, 0.0));
|
||||
panel.release();
|
||||
let accepted = fields_of(&panel.app()).number("scale").unwrap();
|
||||
assert_ne!(accepted, initial);
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap()["scale"], accepted);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap(), original);
|
||||
}
|
||||
|
||||
/// What a step of the table expects at a JSON pointer of the saved brush.
|
||||
enum Expect {
|
||||
Is(Value),
|
||||
@@ -410,6 +460,70 @@ fn ok_redraws_the_strokes_painted_with_the_brush() {
|
||||
assert!((drawn_height(&app, id) - before).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The names screen readers read in the open dialogs, from the access tree of an app frame drawn
|
||||
/// once the dialog has settled.
|
||||
fn access_names(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
crate::dialogs::tests::settle(app);
|
||||
let out = crate::dialogs::tests::frame(app, vec![]);
|
||||
let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
|
||||
nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// Pattern Brush Options' Scale menu: Pressure, Tilt, Bearing, Rotation and Stylus Wheel each take
|
||||
/// a second scale, a stroke drawn without the pen's input is half way between the two, and the
|
||||
/// dialog shows the mode set when it opens again; Fixed drops the second scale.
|
||||
#[test]
|
||||
fn pattern_options_scale_follows_the_pen() {
|
||||
let mut app = app();
|
||||
let (id, before) = brushed(&mut app, "Diamonds");
|
||||
open(&mut app, "Diamonds");
|
||||
let f = fields_of(&app);
|
||||
assert_eq!((f.text("scaleMode"), f.number("scaleMax")), (Some("fixed"), Some(100.0)));
|
||||
// Screen readers name the second scale and the menu after the Scale row.
|
||||
let names = access_names(&mut app);
|
||||
for name in ["Scale: Maximum", "Scale: Mode"] {
|
||||
assert!(names.iter().any(|n| n == name), "{name} in {names:?}");
|
||||
}
|
||||
cancel(&mut app);
|
||||
for mode in ["pressure", "tilt", "bearing", "rotation", "stylusWheel"] {
|
||||
open(&mut app, "Diamonds");
|
||||
set(&mut app, json!({"scaleMode": mode, "scaleMax": 300}));
|
||||
confirm(&mut app).unwrap_or_else(|error| panic!("{mode}: {error}"));
|
||||
let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap();
|
||||
assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(100.0), &json!(mode), &json!(300.0)), "{mode}");
|
||||
// A stroke drawn without the pen's input is half way: 200 %.
|
||||
let after = drawn_height(&app, id);
|
||||
assert!((after - 2.0 * before).abs() < 0.01 * before, "{mode}: {before} then {after}");
|
||||
open(&mut app, "Diamonds");
|
||||
let f = fields_of(&app);
|
||||
assert_eq!((f.text("scaleMode"), f.number("scaleMax")), (Some(mode), Some(300.0)), "{mode}");
|
||||
cancel(&mut app);
|
||||
}
|
||||
// A second scale past the range is kept within it.
|
||||
open(&mut app, "Diamonds");
|
||||
set(&mut app, json!({"scaleMode": "pressure", "scaleMax": 1e9}));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap()["scale_max"], json!(10000.0));
|
||||
// Fixed drops the second scale, and the stroke draws as it did.
|
||||
open(&mut app, "Diamonds");
|
||||
set(&mut app, json!({"scaleMode": "fixed"}));
|
||||
confirm(&mut app).unwrap();
|
||||
let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap();
|
||||
assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}");
|
||||
assert!((drawn_height(&app, id) - before).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Art Brush Options names its second width and its menu after the Width row.
|
||||
#[test]
|
||||
fn art_options_name_the_second_width_and_its_menu() {
|
||||
let mut app = app();
|
||||
open(&mut app, "Tapered Stroke");
|
||||
let names = access_names(&mut app);
|
||||
for name in ["Width: Maximum", "Width: Mode"] {
|
||||
assert!(names.iter().any(|n| n == name), "{name} in {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Art Brush Options draws each Direction segment as an arrow icon named by its tooltip, so the
|
||||
/// accessibility tree reads the direction instead of an arrow glyph.
|
||||
#[test]
|
||||
@@ -904,6 +1018,46 @@ fn options_of_selected_object_set_one_paths_art_brush_settings() {
|
||||
assert_eq!(own_options(&app, a), json!({"width": 50.0}));
|
||||
}
|
||||
|
||||
/// Options of Selected Object for a pattern brush sets one path's Scale mode and second scale; the
|
||||
/// brush and the other path keep theirs.
|
||||
#[test]
|
||||
fn options_of_selected_object_set_one_paths_pattern_scale_mode() {
|
||||
let mut app = app();
|
||||
let a = brushed_line(&mut app, 50.0, "Diamonds");
|
||||
let b = brushed_line(&mut app, 100.0, "Diamonds");
|
||||
select(&mut app, &[a]);
|
||||
app.run("ui.brushObjectOptions", json!({})).unwrap();
|
||||
set(&mut app, json!({"scaleMode": "tilt", "scaleMax": 250}));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(own_options(&app, a), json!({"scale_mode": "tilt", "scale_max": 250.0}));
|
||||
assert_eq!(own_options(&app, b), json!({}));
|
||||
let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap();
|
||||
assert!(def.get("scale_mode").is_none(), "{def}");
|
||||
// Opened again, it shows the path's own mode and second scale.
|
||||
app.run("ui.brushObjectOptions", json!({})).unwrap();
|
||||
let f = fields_of(&app);
|
||||
assert_eq!((f.text("scaleMode"), f.number("scaleMax")), (Some("tilt"), Some(250.0)));
|
||||
cancel(&mut app);
|
||||
// With paths of different scales selected, choosing a mode alone leaves each path's scale and
|
||||
// second scale its own: the first path's scale is not given to the second path as its second
|
||||
// scale.
|
||||
app.run("brush.objectOptions", json!({"ids": [a], "params": {"scale": 50, "scale_mode": null, "scale_max": null}})).unwrap();
|
||||
app.run("brush.objectOptions", json!({"ids": [b], "params": {"scale": 80}})).unwrap();
|
||||
select(&mut app, &[a, b]);
|
||||
app.run("ui.brushObjectOptions", json!({})).unwrap();
|
||||
set(&mut app, json!({"scaleMode": "pressure"}));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(own_options(&app, a), json!({"scale": 50.0, "scale_mode": "pressure"}));
|
||||
assert_eq!(own_options(&app, b), json!({"scale": 80.0, "scale_mode": "pressure"}));
|
||||
// A changed Scale alone keeps each path's own second scale: its old scale.
|
||||
select(&mut app, &[a, b]);
|
||||
app.run("ui.brushObjectOptions", json!({})).unwrap();
|
||||
set(&mut app, json!({"scale": 60}));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(own_options(&app, a), json!({"scale": 60.0, "scale_mode": "pressure", "scale_max": 50.0}));
|
||||
assert_eq!(own_options(&app, b), json!({"scale": 60.0, "scale_mode": "pressure", "scale_max": 80.0}));
|
||||
}
|
||||
|
||||
/// Options of Selected Object shows a scatter path's hue, saturation and brightness jitter, and OK
|
||||
/// sets them on that path only.
|
||||
#[test]
|
||||
|
||||
@@ -87,8 +87,11 @@ fn dialog<'a>(relative: bool, lengths: LengthUnits) -> ParamDialog<'a> {
|
||||
Param::number("radius", tl!("Radius:"), 0.0, 1.0, 3).length(lengths).bounds(Some(0.0), None)
|
||||
};
|
||||
let radii = vec![("relative".to_owned(), tl!("Relative").into()), ("absolute".to_owned(), tl!("Absolute").into())];
|
||||
let params =
|
||||
vec![Param::new("kind", tl!("Corner:"), ParamKind::radio(kinds, None)), Param::new("radii", "", ParamKind::radio(radii, None)), radius];
|
||||
let params = vec![
|
||||
Param::new("kind", tl!("Corner:"), ParamKind::radio(kinds, None)),
|
||||
Param::new("radii", "", ParamKind::radio(radii, None)).options_in_row(),
|
||||
radius,
|
||||
];
|
||||
ParamDialog::new(KIND, tl!("Corners"), params)
|
||||
}
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ fn sized_row(key: &str, label: Label, default: f64, relative: bool, lengths: Len
|
||||
/// the flag's JSON values, which `form::json_of` writes back as a bool.
|
||||
pub(super) fn relative_radio(label: impl Into<Label>, default: bool) -> Param {
|
||||
let options = vec![("true".to_owned(), lbl!("Relative")), ("false".to_owned(), lbl!("Absolute"))];
|
||||
Param::new("relative", label, ParamKind::radio(options, Some(default.to_string())))
|
||||
Param::new("relative", label, ParamKind::radio(options, Some(default.to_string()))).options_in_row()
|
||||
}
|
||||
|
||||
/// Whether the pair's rows are shares of the object's size.
|
||||
@@ -71,14 +71,16 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec<Param> {
|
||||
let lengths = cx.lengths;
|
||||
vec![
|
||||
Param::custom("transform", lbl!("Transform"), move |ui, fields, _| transform_each::rows(ui, fields, lengths, ScaleLink::None))
|
||||
.companions(["scaleH", "scaleV", "moveH", "moveV", "rotate"]),
|
||||
.companions(["scaleH", "scaleV", "moveH", "moveV", "rotate"])
|
||||
.full_width(),
|
||||
Param::section(lbl!("Options")),
|
||||
Param::new("objects", lbl!("Transform Objects"), ParamKind::bool(true)),
|
||||
Param::new("patterns", lbl!("Transform Patterns"), ParamKind::bool(false)),
|
||||
Param::new("strokes", lbl!("Scale Strokes & Effects"), ParamKind::bool(false)),
|
||||
Param::new("copies", lbl!("Copies:"), ParamKind::int(Some(0), Some(1000), 0)),
|
||||
Param::custom("__reflect", lbl!("Reflect"), |ui, fields, _| transform_each::reflect_checks(ui, fields))
|
||||
.companions(["reflectX", "reflectY", "random"]),
|
||||
Param::new("reflectX", lbl!("Reflect X"), ParamKind::bool(false)),
|
||||
Param::new("reflectY", lbl!("Reflect Y"), ParamKind::bool(false)),
|
||||
Param::new("random", lbl!("Random"), ParamKind::bool(false)),
|
||||
Param::custom("__reference", lbl!("Reference Point"), |ui, fields, _| transform_each::reference_point(ui, fields)).companions(["reference"]),
|
||||
]
|
||||
}
|
||||
@@ -102,7 +104,8 @@ pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
|
||||
"points",
|
||||
Label::from(crate::i18n::tr_ctx(crate::i18n::current(), "effect", "Points").to_string()),
|
||||
ParamKind::radio(points, None),
|
||||
),
|
||||
)
|
||||
.options_in_row(),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -185,12 +188,13 @@ pub(super) fn drop_shadow(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
|
||||
.map(|p| if matches!(p.key.as_str(), "opacity" | "x" | "y" | "blur") { p.step_arrows(StepArrows::Leading) } else { p });
|
||||
rows.chain([
|
||||
Param::new("shade", Label::Empty, ParamKind::radio(shades, None)),
|
||||
Param::new("color", lbl!("Color"), ParamKind::color(None)).enabled_when("shade", "color"),
|
||||
Param::new("color", lbl!("Color"), ParamKind::color(None)).enabled_when("shade", "color").under_option("color"),
|
||||
Param::number("darkness", lbl!("Darkness"), 100.0, 1.0, 0)
|
||||
.bounds(Some(0.0), Some(100.0))
|
||||
.unit(UnitKind::Percent)
|
||||
.step_arrows(StepArrows::Leading)
|
||||
.enabled_when("shade", "darkness"),
|
||||
.enabled_when("shade", "darkness")
|
||||
.under_option("darkness"),
|
||||
])
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -20,13 +20,13 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Background, ColorMode, Unit};
|
||||
use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI};
|
||||
|
||||
use craft::behavior::{IconId, Mixed};
|
||||
use craft::behavior::{ColumnWidth, IconId, Mixed};
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::{Checkbox, Segmented};
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::contract::{Bind, Entry, Gap, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::layout_components::{Grid, Row};
|
||||
use craft::ui::patterns::form_dialogs::{
|
||||
CardCx, CardSource, DetailsCx, DocumentCard, DocumentSettings, HostedNewDocument, NewDocumentDialog, Orientation, PresetCategory,
|
||||
};
|
||||
@@ -35,6 +35,7 @@ use craft::ui::pickers::Select;
|
||||
use craft::ui::popover::Popover;
|
||||
use craft::ui::runtime::env::{Label, LengthUnits, UnitKind};
|
||||
use craft::ui::sections::Section;
|
||||
use craft::ui::style::TypeRole;
|
||||
use craft::ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField};
|
||||
|
||||
use super::host::open_held;
|
||||
@@ -296,8 +297,8 @@ impl DocumentSettings for VcNewDocument {
|
||||
}
|
||||
});
|
||||
});
|
||||
// Host viewports below the desktop main window's 800-point minimum need this row to wrap.
|
||||
Row::new().wrap(ui.ctx().content_rect().width() < 800.0).show(ui, |ui, _| {
|
||||
// The row wraps whenever its fields do not fit the column, so Artboards is never cut off at its right edge.
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths));
|
||||
Field::new(orientation.clone()).show(ui, |ui, _| {
|
||||
let entries = [
|
||||
@@ -354,17 +355,24 @@ impl DocumentSettings for VcNewDocument {
|
||||
|
||||
Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s));
|
||||
|
||||
let more = Button::new(text(tl!("More Settings"))).id_salt("more-settings").show(ui);
|
||||
let mut more_open = memory.more_open != clicked(&more);
|
||||
Popover::new(text(tl!("More Settings")), Bind::bound(&mut more_open)).opened_by(&more).show(ui, |ui, _| more_settings(ui, s, lengths));
|
||||
memory.more_open = more_open;
|
||||
|
||||
let manage = Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").show(ui);
|
||||
let mut profiles_open = memory.profiles_open != clicked(&manage);
|
||||
Popover::new(text(tl!("Manage Profiles")), Bind::bound(&mut profiles_open))
|
||||
.opened_by(&manage)
|
||||
.show(ui, |ui, _| manage_profiles(ui, &setup, &mut action));
|
||||
memory.profiles_open = profiles_open;
|
||||
// The two buttons side by side, the item gap apart.
|
||||
let (mut more, mut manage) = (None, None);
|
||||
Row::new().gap(Gap::Item).wrap(true).show(ui, |ui, _| {
|
||||
more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").show(ui));
|
||||
manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").show(ui));
|
||||
});
|
||||
if let Some(more) = &more {
|
||||
let mut more_open = memory.more_open != clicked(more);
|
||||
Popover::new(text(tl!("More Settings")), Bind::bound(&mut more_open)).opened_by(more).show(ui, |ui, _| more_settings(ui, s, lengths));
|
||||
memory.more_open = more_open;
|
||||
}
|
||||
if let Some(manage) = &manage {
|
||||
let mut profiles_open = memory.profiles_open != clicked(manage);
|
||||
Popover::new(text(tl!("Manage Profiles")), Bind::bound(&mut profiles_open))
|
||||
.opened_by(manage)
|
||||
.show(ui, |ui, _| manage_profiles(ui, &setup, &mut action));
|
||||
memory.profiles_open = profiles_open;
|
||||
}
|
||||
|
||||
// Drafts stay in their controls until committed: ending the preset or choosing units cannot be undone by
|
||||
// restoring only a scalar value. Units and orientation only change how the page shows; other edits end the preset.
|
||||
@@ -475,6 +483,10 @@ fn advanced(ui: &mut egui::Ui, s: &mut DocSettings) {
|
||||
/// More Settings' pop-up: the artboard layout, spacing and columns. All three are off with one
|
||||
/// artboard, Columns also for the row and column layouts; columns stay within the artboards.
|
||||
fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) {
|
||||
crate::panels::popover_body(ui, |ui| more_settings_rows(ui, s, lengths));
|
||||
}
|
||||
|
||||
fn more_settings_rows(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) {
|
||||
let several = s.artboards > 1;
|
||||
let grid = matches!(s.layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn);
|
||||
let (layout, spacing, columns, right_to_left) =
|
||||
@@ -531,22 +543,26 @@ fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) {
|
||||
/// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a
|
||||
/// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`.
|
||||
fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option<String>) {
|
||||
Text::new(text(tl!("NEW DOCUMENT PROFILES"))).show(ui);
|
||||
for (name, customized) in &setup.profiles {
|
||||
ui.push_id(name, |ui| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new(text(tl!(name))).show(ui);
|
||||
if clicked(&Button::new(text(tl!("Edit"))).id_salt("edit").enabled(setup.has_profile_folder).show(ui)) {
|
||||
crate::panels::popover_body(ui, |ui| {
|
||||
Text::new(text(tl!("NEW DOCUMENT PROFILES"))).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui);
|
||||
// The names in one column and the Edit and Reset buttons in columns of their own, so the buttons line up.
|
||||
Grid::new(&PROFILE_COLUMNS).gap(Gap::Item).show(ui, |ui, _| {
|
||||
for (name, customized) in &setup.profiles {
|
||||
Text::new(text(tl!(name))).id_salt(("profile", name)).show(ui);
|
||||
if clicked(&Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder).show(ui)) {
|
||||
*action = Some(format!("{EDIT_PROFILE}:{name}"));
|
||||
}
|
||||
if clicked(&Button::new(text(tl!("Reset"))).id_salt("reset").enabled(*customized).show(ui)) {
|
||||
if clicked(&Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(*customized).show(ui)) {
|
||||
*action = Some(format!("{RESET_PROFILE}:{name}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The columns of Manage Profiles' rows: the profile's name, Edit and Reset.
|
||||
const PROFILE_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content];
|
||||
|
||||
/// The category of the settings New Document opens on: the most recent, else Print.
|
||||
fn first_category(app: &VectorcraftApp) -> &'static str {
|
||||
if app.session.prefs.recent_new_docs.is_empty() { "Print" } else { "Recent" }
|
||||
@@ -1009,7 +1025,8 @@ mod tests {
|
||||
};
|
||||
let landscape = bounds("Landscape", egui::accesskit::Role::RadioButton);
|
||||
let artboards = bounds("Artboards", egui::accesskit::Role::SpinButton);
|
||||
assert!(landscape.x1 <= artboards.x0, "Landscape {landscape:?} stays left of Artboards {artboards:?}");
|
||||
// Artboards follows Landscape on its line, or wraps below it when the column has no room for it.
|
||||
assert!(landscape.x1 <= artboards.x0 || landscape.y1 <= artboards.y0, "Landscape {landscape:?} stays clear of Artboards {artboards:?}");
|
||||
let group = bounds("Orientation", egui::accesskit::Role::RadioGroup);
|
||||
let mut drawn = Vec::new();
|
||||
out.shapes.iter().for_each(|s| texts(&s.shape, &mut drawn));
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
//! ([`crate::plugin_runs`]). A filter or live effect with commands of its own is a submenu named
|
||||
//! after it, holding its item and then its commands; a command with parameters opens the same dialog
|
||||
//! for them ([`open_command`]). A command whose manifest names another menu is listed in that menu
|
||||
//! instead ([`place_commands`]).
|
||||
//! instead ([`place_commands`]), and one whose manifest lists context menus is also listed there
|
||||
//! ([`context_commands`]).
|
||||
//! Object › Plug-ins starts with Apply Last Filter and Last Filter…, which run the filter that last
|
||||
//! ran again with the same parameters or open its dialog with them, and a filter's dialog opens with
|
||||
//! the parameters it last ran with in the session ([`LastFilters`]).
|
||||
@@ -50,7 +51,7 @@ use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use egui::Ui;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_engine::cmd::plugin::InstallApproval;
|
||||
use vectorcraft_plugins::{Budget, Kind, Manifest, Plugin, permissions, registry};
|
||||
use vectorcraft_plugins::{Budget, ContextMenu, ContextWhen, Kind, Manifest, Plugin, permissions, registry};
|
||||
|
||||
use super::form;
|
||||
use super::preview::LivePreview;
|
||||
@@ -199,6 +200,79 @@ fn leave_out(items: &mut [Node], placed: &std::collections::HashSet<String>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does condition `when` of a context menu item hold for objects `ids` of `doc` (the selection on
|
||||
/// the canvas, the clicked rows in the Layers panel)? `selection`: one or more; `oneObject`: one,
|
||||
/// which is not a layer; `typeObject`: one of them is a type object; `layerRow`: each is a layer or
|
||||
/// sublayer. Without a condition the item can always be chosen.
|
||||
pub fn context_holds(doc: &vectorcraft_doc::Document, ids: &[u64], when: Option<ContextWhen>) -> bool {
|
||||
let nodes = || ids.iter().filter_map(|id| doc.node(vectorcraft_doc::NodeId(*id)));
|
||||
match when {
|
||||
None => true,
|
||||
Some(ContextWhen::Selection) => !ids.is_empty(),
|
||||
Some(ContextWhen::OneObject) => ids.len() == 1 && nodes().count() == 1 && nodes().all(|n| !n.is_layer()),
|
||||
Some(ContextWhen::TypeObject) => nodes().any(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Text(_))),
|
||||
Some(ContextWhen::LayerRow) => !ids.is_empty() && nodes().count() == ids.len() && nodes().all(|n| n.is_layer()),
|
||||
}
|
||||
}
|
||||
|
||||
/// One plug-in command of a context menu: its label (with an ellipsis when it has parameters), its
|
||||
/// command id and whether its condition holds.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ContextCommand {
|
||||
pub label: &'static str,
|
||||
pub command: &'static str,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// The plug-in commands context menu `menu` lists for objects `ids` of `doc`
|
||||
/// ([`vectorcraft_plugins::Command::context`]): for each filter or live effect, in plug-in id
|
||||
/// order, its name as it is and its commands in manifest order, each enabled only while its `when`
|
||||
/// holds ([`context_holds`]).
|
||||
pub fn context_commands(menu: ContextMenu, doc: &vectorcraft_doc::Document, ids: &[u64]) -> Vec<(&'static str, Vec<ContextCommand>)> {
|
||||
registry::list()
|
||||
.iter()
|
||||
.filter(|p| matches!(p.manifest().kind, Kind::Filter | Kind::Effect))
|
||||
.filter_map(|p| {
|
||||
let m = p.manifest();
|
||||
let commands: Vec<ContextCommand> = m
|
||||
.context_commands(menu)
|
||||
.map(|(c, when)| ContextCommand {
|
||||
label: label(&c.shown_label(), !c.params.is_empty()),
|
||||
command: registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &c.id)),
|
||||
enabled: context_holds(doc, ids, when),
|
||||
})
|
||||
.collect();
|
||||
let name = registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME));
|
||||
(!commands.is_empty()).then_some((name, commands))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The canvas context menu's Plug-ins submenu for the selection `ids`: a submenu per plug-in that
|
||||
/// lists commands there, named after it, each item running its command on `ids`. `None` when no
|
||||
/// installed plug-in lists a command there.
|
||||
pub fn canvas_submenu(doc: &vectorcraft_doc::Document, ids: &[u64]) -> Option<Node> {
|
||||
let groups: Vec<Node> = context_commands(ContextMenu::Canvas, doc, ids)
|
||||
.into_iter()
|
||||
.map(|(name, commands)| {
|
||||
let items =
|
||||
commands.into_iter().map(|command| cp(command.label, command.command, json!({ "ids": ids })).enabled(command.enabled)).collect();
|
||||
sub(name, items)
|
||||
})
|
||||
.collect();
|
||||
(!groups.is_empty()).then_some(sub("Plug-ins", groups))
|
||||
}
|
||||
|
||||
/// Can the canvas context menu's item for plug-in command `id` with `p` be chosen? Only an item
|
||||
/// that carries `ids` ([`canvas_submenu`]) has a condition; every other item can.
|
||||
pub fn canvas_item_enabled(app: &VectorcraftApp, id: &str, p: &Value) -> bool {
|
||||
let Some(ids) = p.get("ids").and_then(Value::as_array) else { return true };
|
||||
let Some((_, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return true };
|
||||
let Some(place) = c.context.iter().find(|p| p.menu == ContextMenu::Canvas) else { return true };
|
||||
let ids: Vec<u64> = ids.iter().filter_map(Value::as_u64).collect();
|
||||
app.session.active().is_some_and(|st| context_holds(&st.doc, &ids, place.when))
|
||||
}
|
||||
|
||||
/// Object › Plug-ins: the installed object filters (each with its commands, if it has any) and
|
||||
/// generators, then Edit Generated Art…, Install Plug-in…, Reload Plug-ins and Plug-ins That Didn't
|
||||
/// Load… ([`super::failed_plugins`]).
|
||||
@@ -275,6 +349,11 @@ pub(crate) enum Opened {
|
||||
/// Whether the last preview failed.
|
||||
refused: bool,
|
||||
params: Arc<[Param]>,
|
||||
/// The objects a context menu opened a command's dialog for, which its runs are given.
|
||||
ids: Option<Value>,
|
||||
/// The uid of the document a command's dialog opened on, the only one it runs on; `None`
|
||||
/// for a filter's own dialog, which runs on the active document.
|
||||
doc: Option<u64>,
|
||||
},
|
||||
/// A generator's parameters: for new generated art (`edit` is `None`), or for drawing the
|
||||
/// generated art object `edit` names again.
|
||||
@@ -298,6 +377,16 @@ impl PluginDialog {
|
||||
pub(crate) fn opens_picked(&self) -> bool {
|
||||
matches!(&self.kind, Opened::Import { open, .. } if open["picked"] == true)
|
||||
}
|
||||
|
||||
/// The plug-in command a command's dialog runs and the objects it runs on, if a context menu
|
||||
/// gave them; `None` for any other dialog.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn runs_command(&self) -> Option<(&str, Option<&Value>)> {
|
||||
match &self.kind {
|
||||
Opened::Filter { command: Some(c), ids, .. } => Some((c.as_str(), ids.as_ref())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Opened {
|
||||
@@ -320,6 +409,25 @@ impl Opened {
|
||||
other => registry::get(other.plugin()).is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the dialog is a command's opened on a document that is not the active one.
|
||||
fn elsewhere(&self, app: &VectorcraftApp) -> bool {
|
||||
match self {
|
||||
Opened::Filter { doc: Some(uid), .. } => app.session.active().is_none_or(|st| st.uid != *uid),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rolls back the filter dialog's shown preview, unless another document is the active one,
|
||||
/// whose edit in progress it leaves alone.
|
||||
fn roll_back(self, app: &mut VectorcraftApp) {
|
||||
let elsewhere = self.elsewhere(app);
|
||||
if let Opened::Filter { preview, .. } = self
|
||||
&& !elsewhere
|
||||
{
|
||||
preview.cancel(app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a hosted plug-in dialog looks.
|
||||
@@ -385,9 +493,7 @@ fn close_open(app: &mut VectorcraftApp) {
|
||||
if let (Some(ctx), Some(dialogs)) = (app.ui_ctx.clone(), app.dialogs()) {
|
||||
dialogs.with(|host| host.cancel_by_id(&ctx, old.id));
|
||||
}
|
||||
if let Opened::Filter { preview, .. } = old.kind {
|
||||
preview.cancel(app);
|
||||
}
|
||||
old.kind.roll_back(app);
|
||||
}
|
||||
|
||||
/// Object › Plug-ins' first items: Apply Last Filter, which runs the filter that last ran again with
|
||||
@@ -608,15 +714,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
/// Opens the dialog of filter `plugin`, or of its command `command`, with `m` the manifest it runs
|
||||
/// with, headed `heading`: the rows at `values`, with a live Preview for a light filter. Where
|
||||
/// filters run in workers (the web build) the dialog has no Preview: a preview would run the plug-in
|
||||
/// on the page.
|
||||
/// on the page. A command's dialog runs on its objects when given, and only on its document
|
||||
/// ([`CommandRun`]).
|
||||
fn open_filter(
|
||||
app: &mut VectorcraftApp,
|
||||
plugin: &Plugin,
|
||||
m: Manifest,
|
||||
command: Option<String>,
|
||||
command: Option<CommandRun>,
|
||||
heading: String,
|
||||
values: Map<String, Value>,
|
||||
) -> Result<(), String> {
|
||||
let (command, ids, doc) = match command {
|
||||
Some(c) => (Some(c.id), c.ids, Some(c.doc)),
|
||||
None => (None, None, None),
|
||||
};
|
||||
let own = plugin.manifest();
|
||||
let heavy = own.budget == Budget::Heavy;
|
||||
let light = !heavy && !crate::plugin_runs::in_workers(app);
|
||||
@@ -632,33 +743,50 @@ fn open_filter(
|
||||
previewing: light,
|
||||
refused: false,
|
||||
params,
|
||||
ids,
|
||||
doc,
|
||||
};
|
||||
app.plugin_dialog = Some(PluginDialog { id, kind });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens the dialog of plug-in command `id` (`plugin.<plug-in id>.<command id>`), given no params,
|
||||
/// when it has parameters and a document is open: its rows at their defaults with a live Preview, and
|
||||
/// OK keeps the run as one undo step. False for any other command, which then runs as it was given.
|
||||
pub fn open_command(app: &mut VectorcraftApp, id: &str) -> bool {
|
||||
let Some((plugin, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return false };
|
||||
if c.params.is_empty() || app.session.active().is_none() {
|
||||
/// The plug-in command a filter dialog runs: its id, the objects a context menu gave it, and the
|
||||
/// uid of the document the dialog opened on, the only one it runs on.
|
||||
struct CommandRun {
|
||||
id: String,
|
||||
ids: Option<Value>,
|
||||
doc: u64,
|
||||
}
|
||||
|
||||
/// Opens the dialog of plug-in command `id` (`plugin.<plug-in id>.<command id>`), given no params
|
||||
/// or only `ids` (a context menu's objects), when it has parameters and a document is open: its
|
||||
/// rows at their defaults with a live Preview, and OK keeps the run on those objects as one undo
|
||||
/// step. The dialog runs only on the document that was active when it opened. False for any other
|
||||
/// command or params, which then run as they were given.
|
||||
pub fn open_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool {
|
||||
let only_ids = (p.is_null() || p.as_object().is_some_and(|o| o.keys().all(|k| k == "ids"))) && p.get("ids").is_none_or(Value::is_array);
|
||||
if !only_ids {
|
||||
return false;
|
||||
}
|
||||
let Some((plugin, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return false };
|
||||
let Some(doc) = app.session.active().map(|st| st.uid).filter(|_| !c.params.is_empty()) else { return false };
|
||||
let ids = p.get("ids").cloned();
|
||||
let m = plugin.manifest().for_command(&c);
|
||||
let defaults = m.defaults();
|
||||
if let Err(e) = open_filter(app, &plugin, m, Some(id.to_string()), c.shown_label().to_string(), defaults) {
|
||||
let run = CommandRun { id: id.to_string(), ids, doc };
|
||||
if let Err(e) = open_filter(app, &plugin, m, Some(run), c.shown_label().to_string(), defaults) {
|
||||
app.status(e);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The command a filter dialog runs and its params: `plugin.run` for the filter's own dialog, else
|
||||
/// its plug-in command.
|
||||
fn command(plugin: &str, command: Option<&str>, values: Map<String, Value>) -> (String, Value) {
|
||||
match command {
|
||||
None => (CMD.to_string(), json!({"id": plugin, "params": values})),
|
||||
Some(c) => (c.to_string(), json!({"params": values})),
|
||||
/// its plug-in command, given objects `ids` when a context menu opened it.
|
||||
fn command(plugin: &str, command: Option<&str>, ids: Option<&Value>, values: Map<String, Value>) -> (String, Value) {
|
||||
match (command, ids) {
|
||||
(None, _) => (CMD.to_string(), json!({"id": plugin, "params": values})),
|
||||
(Some(c), Some(ids)) => (c.to_string(), json!({"ids": ids, "params": values})),
|
||||
(Some(c), None) => (c.to_string(), json!({"params": values})),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -824,10 +952,14 @@ fn import_with(app: &mut VectorcraftApp, open: Value, values: Map<String, Value>
|
||||
/// no preview, and a light one that runs in the background ([`in_background`]) with Preview off or a
|
||||
/// failed preview, start in the background ([`run`]). On the web the filter or its command always
|
||||
/// starts in a worker. A preview still shown when Preview was just turned off, or one that failed, is
|
||||
/// rolled back first.
|
||||
/// rolled back first. A command's dialog answered while another document is the active one changes
|
||||
/// no document.
|
||||
fn confirm_filter(app: &mut VectorcraftApp, kind: Opened, values: Map<String, Value>) -> Result<Value, String> {
|
||||
let Opened::Filter { plugin, command: own, preview, light, previewing, refused, .. } = kind else { return Ok(Value::Null) };
|
||||
let (cmd, p) = command(&plugin, own.as_deref(), values);
|
||||
if kind.elsewhere(app) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let Opened::Filter { plugin, command: own, preview, light, previewing, refused, ids, .. } = kind else { return Ok(Value::Null) };
|
||||
let (cmd, p) = command(&plugin, own.as_deref(), ids.as_ref(), values);
|
||||
let kept = light && previewing && app.session.in_interaction() && !refused;
|
||||
match registry::get(&plugin) {
|
||||
// On the web, with no Preview, the filter or its command always runs in a worker; a command
|
||||
@@ -878,17 +1010,17 @@ fn pump_dialog(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if let Some(link) = help {
|
||||
form::open_help(app, &link);
|
||||
}
|
||||
if open.kind.gone() {
|
||||
// A command's dialog closes once its command is gone, or once another document is the
|
||||
// active one, whose edit in progress it leaves alone.
|
||||
if open.kind.gone() || open.kind.elsewhere(app) {
|
||||
dialogs.with(|host| host.cancel_by_id(ctx, id));
|
||||
if let Opened::Filter { preview, .. } = open.kind {
|
||||
preview.cancel(app);
|
||||
}
|
||||
open.kind.roll_back(app);
|
||||
return;
|
||||
}
|
||||
if let Opened::Filter { plugin, command: own, label, preview, previewing, refused, light, .. } = &mut open.kind {
|
||||
if let Opened::Filter { plugin, command: own, label, preview, previewing, refused, light, ids, .. } = &mut open.kind {
|
||||
*previewing = on;
|
||||
if *light {
|
||||
let (cmd, p) = command(plugin, own.as_deref(), values);
|
||||
let (cmd, p) = command(plugin, own.as_deref(), ids.as_ref(), values);
|
||||
if let Some(answer) = preview.run(app, on, label, &cmd, &p) {
|
||||
*refused = answer.is_err();
|
||||
}
|
||||
@@ -900,9 +1032,7 @@ fn pump_dialog(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// The dialog is closed: answered, or cancelled from outside.
|
||||
let answer = dialogs.with(|host| host.take_by_id::<HostedParamDialog>(id));
|
||||
let Some(DialogResult::Ok(result)) = answer else {
|
||||
if let Opened::Filter { preview, .. } = open.kind {
|
||||
preview.cancel(app);
|
||||
}
|
||||
open.kind.roll_back(app);
|
||||
return;
|
||||
};
|
||||
let values = form::json_of(¶ms, &result.fields);
|
||||
|
||||
@@ -706,7 +706,10 @@ fn sections(lists: &Lists) -> Vec<PrintSection> {
|
||||
flag("collate", tl!("Collate")).enabled_when_in("copies", counts),
|
||||
flag("reverse", tl!("Reverse Order")),
|
||||
Param::new("artboards", tl!("Artboards"), ParamKind::radio(artboards, None)),
|
||||
Param::new("range", tl!("Range:"), ParamKind::text("")).hint("1-3, 5").enabled_when("artboards", PrintArtboards::Range.id()),
|
||||
Param::new("range", tl!("Range:"), ParamKind::text(""))
|
||||
.hint("1-3, 5")
|
||||
.enabled_when("artboards", PrintArtboards::Range.id())
|
||||
.under_option(PrintArtboards::Range.id()),
|
||||
flag("skipBlank", tl!("Skip Blank Artboards")).enabled_when_in("artboards", [PrintArtboards::All.id(), PrintArtboards::Range.id()]),
|
||||
Param::section(tl!("Media")),
|
||||
pick::<Media>("media", tl!("Size:")),
|
||||
|
||||
@@ -46,7 +46,8 @@ fn scope_label(scope: &str) -> Label {
|
||||
|
||||
/// Open the dialog on the images and placed documents `ids` (default: the selected ones).
|
||||
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let document = app.session.active().ok_or("no document open")?.uid;
|
||||
let st = app.session.active().ok_or("no document open")?;
|
||||
let document = (st.uid, st.reverts);
|
||||
let ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(v) => v.as_array().cloned().ok_or_else(|| format!("`ids` must be an array of object ids, not {v}"))?,
|
||||
None => crate::panels::links::selected_ids(app).into_iter().map(Value::from).collect(),
|
||||
@@ -86,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The relink rule: one `links.relink` call with the answer's parameters, and the status it earns.
|
||||
fn relink(app: &mut VectorcraftApp, (document, params): &(u64, Value)) -> Result<(), String> {
|
||||
if app.session.active().is_none_or(|st| st.uid != *document) {
|
||||
let reason = tl!("Relink can only change links in the document where it was opened.");
|
||||
/// The relink rule: one `links.relink` call with the answer's parameters, and the status it earns. OK is refused in
|
||||
/// another document, and in the opening document after File > Revert has replaced its content.
|
||||
fn relink(app: &mut VectorcraftApp, ((document, reverts), params): &((u64, u64), Value)) -> Result<(), String> {
|
||||
let refusal = match app.session.active() {
|
||||
Some(st) if st.uid == *document && st.reverts == *reverts => None,
|
||||
Some(st) if st.uid == *document => Some(tl!("The document was reverted. Reopen this dialog to continue.")),
|
||||
_ => Some(tl!("Relink can only change links in the document where it was opened.")),
|
||||
};
|
||||
if let Some(reason) = refusal {
|
||||
app.status(reason);
|
||||
return Err(reason.to_owned());
|
||||
}
|
||||
@@ -122,8 +128,8 @@ impl ItemSource<usize> for Names<'_> {}
|
||||
/// app (`HoldsOk`); with Each Link Separately it stays open until every link has a file.
|
||||
pub(crate) struct RelinkDialog {
|
||||
id: DialogId,
|
||||
/// The document that owns the link IDs.
|
||||
document: u64,
|
||||
/// The document that owns the link IDs: its uid and revert count.
|
||||
document: (u64, u64),
|
||||
ids: Vec<Value>,
|
||||
links: Vec<Value>,
|
||||
scope: String,
|
||||
@@ -135,7 +141,7 @@ pub(crate) struct RelinkDialog {
|
||||
}
|
||||
|
||||
impl RelinkDialog {
|
||||
fn new(document: u64, ids: Vec<Value>, links: Vec<Value>) -> Self {
|
||||
fn new(document: (u64, u64), ids: Vec<Value>, links: Vec<Value>) -> Self {
|
||||
RelinkDialog {
|
||||
id: dialog_id(KEY),
|
||||
document,
|
||||
@@ -194,7 +200,7 @@ impl RelinkDialog {
|
||||
}
|
||||
|
||||
impl HoldsOk for RelinkDialog {
|
||||
type Answer = (u64, Value);
|
||||
type Answer = ((u64, u64), Value);
|
||||
|
||||
fn held_ok(self) -> Self {
|
||||
self
|
||||
@@ -451,6 +457,82 @@ mod tests {
|
||||
check_relink_stays_in_opening_drawing(true);
|
||||
}
|
||||
|
||||
/// Opens Relink on a saved document's linked image and chooses a replacement (in `path`, or from the file picker
|
||||
/// with `native_picker`) around File > Revert, then presses OK: the restored image keeps its link, no undo step is
|
||||
/// recorded and the status line reports the revert. Reopened on the restored document, Relink relinks again.
|
||||
fn check_relink_refused_after_file_revert(native_picker: bool) {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
let (mut app, dir) = setup(if native_picker { "revert-picker" } else { "revert-path" }, &["photo.png"]);
|
||||
let picker = scripted(&mut app);
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
|
||||
let original = dir.join("photo.png").to_string_lossy().into_owned();
|
||||
let id = place(&mut app, &dir.join("photo.png"));
|
||||
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
|
||||
let chosen = new_file(&dir, "replacement.png");
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(900.0, 700.0));
|
||||
panel.app().run("ui.relinkDialog", json!({"ids": [id]})).unwrap();
|
||||
panel.frame();
|
||||
if native_picker {
|
||||
panel.click("Relink…");
|
||||
assert_eq!(picker.requests().len(), 1);
|
||||
} else {
|
||||
let dialog = relink_dialog(&panel.app()).id;
|
||||
answer_dialog(&mut panel.app(), dialog, &[("path", json!(chosen))], false);
|
||||
}
|
||||
panel.app().run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
|
||||
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
assert_eq!(link_path(&panel.app(), id), original, "the same id names the restored image");
|
||||
let undo = panel.app().session.active().unwrap().history.undo.len();
|
||||
if native_picker {
|
||||
picker.answer(&[&chosen]);
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
} else {
|
||||
panel.click("Relink…");
|
||||
panel.frame();
|
||||
}
|
||||
{
|
||||
let app = panel.app();
|
||||
assert_eq!(link_path(&app, id), original, "OK leaves the restored image's link unchanged");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
|
||||
let dialog = relink_dialog(&app).id;
|
||||
assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_))));
|
||||
}
|
||||
|
||||
let ctx = ctx(&panel.app());
|
||||
let dialogs = panel.app().dialogs().expect("a window");
|
||||
let dialog = relink_dialog(&panel.app()).id;
|
||||
dialogs.with(|host| host.cancel_by_id(&ctx, dialog));
|
||||
panel.frame();
|
||||
assert!(open_dialogs(&panel.app()).is_empty());
|
||||
panel.app().run("ui.relinkDialog", json!({"ids": [id]})).unwrap();
|
||||
panel.frame();
|
||||
let dialog = relink_dialog(&panel.app()).id;
|
||||
answer_dialog(&mut panel.app(), dialog, &[("path", json!(chosen))], false);
|
||||
panel.click("Relink…");
|
||||
panel.frame();
|
||||
let app = panel.app();
|
||||
assert!(open_dialogs(&app).is_empty());
|
||||
assert_eq!(link_path(&app, id), chosen, "reopened, Relink relinks the restored image");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
|
||||
drop(app);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relink_is_refused_after_file_revert_for_a_path_confirmation() {
|
||||
check_relink_refused_after_file_revert(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relink_is_refused_after_file_revert_when_the_file_picker_answers() {
|
||||
check_relink_refused_after_file_revert(true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_popup_cancel_preserves_selected_instances_and_enter_relinks_all() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
@@ -445,6 +445,15 @@ pub(crate) fn reference_point(ui: &mut Ui, fields: &mut DialogFields) -> Respons
|
||||
shown.response
|
||||
}
|
||||
|
||||
/// The reference point picker with its name beside it, for a full-width row that draws no label of its own.
|
||||
fn labelled_reference_point(ui: &mut Ui, fields: &mut DialogFields) -> Response {
|
||||
let shown = Row::new().show(ui, |ui, _| {
|
||||
reference_point(ui, fields);
|
||||
Text::new(tl!("Reference Point")).show(ui);
|
||||
});
|
||||
shown.output
|
||||
}
|
||||
|
||||
/// The dialog's rows: Scale, Move and Rotate in one row, then the options.
|
||||
fn dialog_params(lengths: LengthUnits) -> Vec<Param> {
|
||||
vec![
|
||||
@@ -464,7 +473,7 @@ fn dialog_params(lengths: LengthUnits) -> Vec<Param> {
|
||||
Ok(())
|
||||
})
|
||||
.full_width(),
|
||||
Param::custom("reference", tl!("Reference Point"), |ui, f, _| reference_point(ui, f))
|
||||
Param::custom("reference", tl!("Reference Point"), |ui, f, _| labelled_reference_point(ui, f))
|
||||
.on_set(|f, key, value| {
|
||||
let at = value.as_i64().filter(|at| (0..=8).contains(at)).ok_or_else(|| FieldRefusal::Rejects(&value).message(key))?;
|
||||
f.set(key, at);
|
||||
|
||||
@@ -39,7 +39,6 @@ pub(crate) enum Owner {
|
||||
/// A pick asked for and not yet answered.
|
||||
struct Waiting {
|
||||
ticket: PickId,
|
||||
owner: Owner,
|
||||
/// The file service is writing bytes that the caller already prepared.
|
||||
saving: bool,
|
||||
/// The active drawing's UID and Revert counter when asked, if the request is document-owned.
|
||||
@@ -168,7 +167,7 @@ fn start(
|
||||
Owner::Free => None,
|
||||
};
|
||||
let (scope, automated) = (ScopeHandle::capture(), app.automation_asked());
|
||||
app.file_asks.waiting.push(Waiting { ticket, owner, saving, doc, scope, automated, current, then: Box::new(then) });
|
||||
app.file_asks.waiting.push(Waiting { ticket, saving, doc, scope, automated, current, then: Box::new(then) });
|
||||
json!({ "pending": "fileDialog" })
|
||||
}
|
||||
|
||||
|
||||
@@ -2693,6 +2693,9 @@ font-technology Variable Променливи
|
||||
Only Web Colors Само уеб цветове
|
||||
Opacity Непрозрачност
|
||||
Show Opacity Показване на непрозрачността
|
||||
Show Hex Field Показване на шестнадесетичното поле
|
||||
Hex or CSS color Шестнадесетичен или CSS цвят
|
||||
Parse Color Разчитане на цвят
|
||||
Opacity & Mask Define Knockout Shape Непрозрачността и маската определят формата на изрязване
|
||||
Opacity Mask Маска за непрозрачност
|
||||
Opacity Mask Info Информация за маската за непрозрачност
|
||||
@@ -5021,6 +5024,7 @@ axis Both И двете
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` трябва да бъде шестнадесетичен цвят (#rgb, #rgba, #rrggbb или #rrggbbaa) или CSS цвят rgb(), hsl() или oklch() с най-много 48 знака
|
||||
@msg the Color Picker is not open Палитрата с цвят не е отворена
|
||||
@msg the screen color sampler is already open инструментът за вземане на цвят от екрана вече е отворен
|
||||
@msg this system has no screen color sampler тази система няма инструмент за вземане на цвят от екрана
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -508,6 +508,9 @@
|
||||
Fill Color Boja ispune
|
||||
Opacity Neprozirnost
|
||||
Show Opacity Prikaži neprozirnost
|
||||
Show Hex Field Prikaži hex polje
|
||||
Hex or CSS color Hex ili CSS boja
|
||||
Parse Color Raščlani boju
|
||||
Stroke Color Boja poteza
|
||||
Fill Gradient Gradijent ispune
|
||||
Stroke Gradient Gradijent poteza
|
||||
@@ -5282,6 +5285,7 @@ imageTrace Outline Obris
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` mora biti hex boja (#rgb, #rgba, #rrggbb ili #rrggbbaa) ili CSS boja rgb(), hsl() ili oklch() od najviše 48 znakova
|
||||
@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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3212,6 +3212,9 @@ digits Malayalam Malaiàlam
|
||||
Only Web Colors Només colors web
|
||||
Opacity Opacitat
|
||||
Show Opacity Mostra l’opacitat
|
||||
Show Hex Field Mostra el camp hex
|
||||
Hex or CSS color Color hex o CSS
|
||||
Parse Color Analitza el color
|
||||
Opacity & Mask Define Knockout Shape L’opacitat i la màscara defineixen la forma d’exclusió
|
||||
Opacity Mask Màscara d’opacitat
|
||||
Opacity Mask Info Informació de la màscara d’opacitat
|
||||
@@ -6216,6 +6219,7 @@ digits Malayalam Malaiàlam
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` ha de ser un color hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un color CSS rgb(), hsl() o oklch() de 48 caràcters com a màxim
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -522,6 +522,9 @@
|
||||
Fill Color Barva výplně
|
||||
Opacity Krytí
|
||||
Show Opacity Zobrazit krytí
|
||||
Show Hex Field Zobrazit pole hex
|
||||
Hex or CSS color Barva hex nebo CSS
|
||||
Parse Color Analyzovat barvu
|
||||
Stroke Color Barva tahu
|
||||
Fill Gradient Přechod výplně
|
||||
Stroke Gradient Přechod tahu
|
||||
@@ -5578,6 +5581,7 @@ liquify-list-end {0}, {1} {0} a {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` musí být barva hex (#rgb, #rgba, #rrggbb nebo #rrggbbaa) nebo barva CSS rgb(), hsl() nebo oklch() o nejvýše 48 znacích
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3323,6 +3323,9 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
Fill Color Fyldfarve
|
||||
Opacity Opacitet
|
||||
Show Opacity Vis opacitet
|
||||
Show Hex Field Vis hex-felt
|
||||
Hex or CSS color Hex- eller CSS-farve
|
||||
Parse Color Fortolk farve
|
||||
Stroke Color Stregfarve
|
||||
Fill Gradient Fyldgradient
|
||||
Stroke Gradient Streggradient
|
||||
@@ -9286,6 +9289,7 @@ variable-list-end {0}, {1} {0} og {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` skal være en hex-farve (#rgb, #rgba, #rrggbb eller #rrggbbaa) eller en CSS-farve rgb(), hsl() eller oklch() på højst 48 tegn
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2606,6 +2606,9 @@ file-filter Templates Vorlagen
|
||||
Only Web Colors Nur Webfarben
|
||||
Opacity Deckkraft
|
||||
Show Opacity Deckkraft einblenden
|
||||
Show Hex Field Hex-Feld einblenden
|
||||
Hex or CSS color Hex- oder CSS-Farbe
|
||||
Parse Color Farbe auswerten
|
||||
Opacity & Mask Define Knockout Shape Deckkraft und Maske definieren Aussparungsform
|
||||
Opacity Mask Deckkraftmaske
|
||||
Opacity Mask Info Informationen zur Deckkraftmaske
|
||||
@@ -5156,6 +5159,7 @@ liquify-list-end {0}, {1} {0} und {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` muss eine Hex-Farbe (#rgb, #rgba, #rrggbb oder #rrggbbaa) oder eine CSS-Farbe rgb(), hsl() oder oklch() mit höchstens 48 Zeichen sein
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2161,6 +2161,9 @@ font-technology Variable Μεταβλητές
|
||||
Only Web Colors Μόνο χρώματα ιστού
|
||||
Opacity Αδιαφάνεια
|
||||
Show Opacity Εμφάνιση αδιαφάνειας
|
||||
Show Hex Field Εμφάνιση πεδίου Hex
|
||||
Hex or CSS color Χρώμα Hex ή CSS
|
||||
Parse Color Ανάλυση χρώματος
|
||||
Opacity Mask Μάσκα αδιαφάνειας
|
||||
Opacity: Αδιαφάνεια:
|
||||
Open Άνοιγμα
|
||||
@@ -7086,6 +7089,7 @@ effect Points Σημεία
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters Το `text` πρέπει να είναι χρώμα Hex (#rgb, #rgba, #rrggbb ή #rrggbbaa) ή χρώμα CSS rgb(), hsl() ή oklch() με έως 48 χαρακτήρες
|
||||
@msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1}
|
||||
@msg choose a destination folder επιλέξτε φάκελο προορισμού
|
||||
@msg choose a source folder επιλέξτε φάκελο προέλευσης
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2646,6 +2646,9 @@ font-technology Variable Variables
|
||||
Only Web Colors Solo colores web
|
||||
Opacity Opacidad
|
||||
Show Opacity Mostrar opacidad
|
||||
Show Hex Field Mostrar campo hex
|
||||
Hex or CSS color Color hex o CSS
|
||||
Parse Color Analizar color
|
||||
Opacity & Mask Define Knockout Shape La opacidad y la máscara definen la forma de exclusión
|
||||
Opacity Mask Máscara de opacidad
|
||||
Opacity Mask Info Información de máscara de opacidad
|
||||
@@ -5266,6 +5269,7 @@ liquify-list-end {0}, {1} {0}, {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` debe ser un color hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un color CSS rgb(), hsl() u oklch() de 48 caracteres como máximo
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -519,6 +519,9 @@
|
||||
Fill Color Täyttöväri
|
||||
Opacity Peittävyys
|
||||
Show Opacity Näytä peittävyys
|
||||
Show Hex Field Näytä heksakenttä
|
||||
Hex or CSS color Heksa- tai CSS-väri
|
||||
Parse Color Jäsennä väri
|
||||
Stroke Color Viivan väri
|
||||
Fill Gradient Täytön liukuväri
|
||||
Stroke Gradient Viivan liukuväri
|
||||
@@ -7091,6 +7094,7 @@ mark-style Japanese Japanilainen
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` on oltava heksaväri (#rgb, #rgba, #rrggbb tai #rrggbbaa) tai CSS-väri rgb(), hsl() tai oklch(), enintään 48 merkkiä
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2634,6 +2634,9 @@ font-technology Variable Variables
|
||||
Only Web Colors Couleurs Web uniquement
|
||||
Opacity Opacité
|
||||
Show Opacity Afficher l’opacité
|
||||
Show Hex Field Afficher le champ hex
|
||||
Hex or CSS color Couleur hex ou CSS
|
||||
Parse Color Analyser la couleur
|
||||
Opacity & Mask Define Knockout Shape L’opacité et le masque définissent la forme de masquage
|
||||
Opacity Mask Masque d’opacité
|
||||
Opacity Mask Info Infos sur le masque d’opacité
|
||||
@@ -5223,6 +5226,7 @@ liquify-list-end {0}, {1} {0} et {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` doit être une couleur hex (#rgb, #rgba, #rrggbb ou #rrggbbaa) ou une couleur CSS rgb(), hsl() ou oklch() d’au plus 48 caractères
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2637,6 +2637,9 @@
|
||||
Only Web Colors માત્ર વેબ રંગો
|
||||
Opacity અપારદર્શકતા
|
||||
Show Opacity અપારદર્શકતા બતાવો
|
||||
Show Hex Field Hex ફીલ્ડ બતાવો
|
||||
Hex or CSS color Hex અથવા CSS રંગ
|
||||
Parse Color રંગ પાર્સ કરો
|
||||
Opacity & Mask Define Knockout Shape અપારદર્શકતા અને માસ્ક નૉકઆઉટ આકાર વ્યાખ્યાયિત કરે છે
|
||||
Opacity Mask Info અપારદર્શકતા માસ્ક માહિતી
|
||||
Opacity Mask Options અપારદર્શકતા માસ્ક વિકલ્પો
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -3747,6 +3747,9 @@ arrowhead Feather पंख
|
||||
Only Web Colors केवल वेब रंग
|
||||
Opacity ओपेसिटी
|
||||
Show Opacity ओपेसिटी दिखाएँ
|
||||
Show Hex Field हेक्स फ़ील्ड दिखाएँ
|
||||
Hex or CSS color हेक्स या CSS रंग
|
||||
Parse Color रंग पार्स करें
|
||||
Opacity & Mask Define Knockout Shape ओपेसिटी एंड मास्क डिफ़ाइन नॉकआउट शेप
|
||||
Opacity Mask ओपेसिटी मास्क
|
||||
Opacity Mask Info ओपेसिटी मास्क की जानकारी
|
||||
@@ -7192,6 +7195,7 @@ arrowhead Feather पंख
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` एक हेक्स रंग (#rgb, #rgba, #rrggbb या #rrggbbaa) या अधिकतम 48 वर्णों का CSS rgb(), hsl() या oklch() रंग होना चाहिए
|
||||
@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` खाली है
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3123,6 +3123,9 @@ file-filter Templates Sablonok
|
||||
Only Web Colors Csak webes színek
|
||||
Opacity Átlátszatlanság
|
||||
Show Opacity Átlátszatlanság megjelenítése
|
||||
Show Hex Field Hex mező megjelenítése
|
||||
Hex or CSS color Hex vagy CSS szín
|
||||
Parse Color Szín értelmezése
|
||||
Opacity & Mask Define Knockout Shape Az átlátszatlanság és a maszk adja a kiütés alakját
|
||||
Opacity Mask Átlátszósági maszk
|
||||
Opacity Mask Info Átlátszósági maszk adatai
|
||||
@@ -5598,6 +5601,7 @@ imageTrace Outline Körvonal
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text`: hex szín (#rgb, #rgba, #rrggbb vagy #rrggbbaa) vagy legfeljebb 48 karakteres CSS rgb(), hsl() vagy oklch() szín kell
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1197,6 +1197,9 @@
|
||||
Fill Color Warna isian
|
||||
Opacity Opasitas
|
||||
Show Opacity Tampilkan opasitas
|
||||
Show Hex Field Tampilkan bidang hex
|
||||
Hex or CSS color Warna hex atau CSS
|
||||
Parse Color Urai warna
|
||||
Stroke Color Warna stroke
|
||||
Fill Gradient Gradien isian
|
||||
Stroke Gradient Gradien stroke
|
||||
@@ -7069,6 +7072,7 @@ mark-style Japanese Jepang
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` harus berupa warna hex (#rgb, #rgba, #rrggbb, atau #rrggbbaa) atau warna CSS rgb(), hsl(), atau oklch() dengan paling banyak 48 karakter
|
||||
@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
|
||||
@@ -9196,6 +9200,12 @@ file-filter Applications Aplikasi
|
||||
@msg the layer effects of {n} layers weren't drawn efek lapisan dari {n} lapisan tidak digambar
|
||||
@msg the vector masks of 1 layer weren't applied masker vektor dari 1 lapisan tidak diterapkan
|
||||
@msg the vector masks of {n} layers weren't applied masker vektor dari {n} lapisan tidak diterapkan
|
||||
@msg `opacity` must be a number from 0 to 100 `opacity` harus berupa angka dari 0 sampai 100
|
||||
@msg `opacity` must be true or false `opacity` harus true atau false
|
||||
@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke karakter teks tidak memiliki opasitas sendiri: tambahkan isian atau guratan dengan Tambahkan isian baru atau Tambahkan guratan baru di panel Tampilan
|
||||
@msg an object selected in a symbol instance has no fill or stroke opacity of its own objek yang dipilih dalam instans simbol tidak memiliki opasitas isian atau guratan sendiri
|
||||
@msg no target has that fill or stroke to take the opacity tidak ada target yang memiliki isian atau guratan itu untuk menerima opasitas
|
||||
@msg give color, none, swatch, gradient or opacity berikan color, none, swatch, gradient, atau opacity
|
||||
@msg the knockout of 1 layer wasn't applied knockout dari 1 lapisan tidak diterapkan
|
||||
@msg the knockout of {n} layers wasn't applied knockout dari {n} lapisan tidak diterapkan
|
||||
@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 lapisan tidak disertakan (lapisan tersembunyi dan lapisan yang dikliping padanya)
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2691,6 +2691,9 @@ file-filter Templates Modelli
|
||||
Only Web Colors Solo colori web
|
||||
Opacity Opacità
|
||||
Show Opacity Mostra opacità
|
||||
Show Hex Field Mostra campo hex
|
||||
Hex or CSS color Colore hex o CSS
|
||||
Parse Color Analizza colore
|
||||
Opacity & Mask Define Knockout Shape Opacità e maschera definiscono la forma di foratura
|
||||
Opacity Mask Maschera di opacità
|
||||
Opacity Mask Info Informazioni maschera di opacità
|
||||
@@ -5294,6 +5297,7 @@ liquify-list-end {0}, {1} {0} e {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` deve essere un colore hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un colore CSS rgb(), hsl() o oklch() di al massimo 48 caratteri
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -587,6 +587,9 @@ digits Malayalam マラヤーラム数字
|
||||
Make Sides Equal 辺の長さをそろえる
|
||||
Opacity 不透明度
|
||||
Show Opacity 不透明度を表示
|
||||
Show Hex Field 16 進フィールドを表示
|
||||
Hex or CSS color 16 進または CSS カラー
|
||||
Parse Color カラーを解析
|
||||
Pie End Angle: 扇形の終了角度:
|
||||
Pie Start Angle: 扇形の開始角度:
|
||||
Stroke Color カラー (線)
|
||||
@@ -5715,6 +5718,7 @@ variable-list-end {0}, {1} {0}、{1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` には 16 進カラー (#rgb、#rgba、#rrggbb、#rrggbbaa) または 48 文字以内の CSS の rgb()、hsl()、oklch() カラーを指定してください
|
||||
@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 を指定してください
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2656,6 +2656,9 @@
|
||||
Fill Color შევსების ფერი
|
||||
Opacity გაუმჭვირვალობა
|
||||
Show Opacity გაუმჭვირვალობის ჩვენება
|
||||
Show Hex Field Hex ველის ჩვენება
|
||||
Hex or CSS color Hex ან CSS ფერი
|
||||
Parse Color ფერის გარჩევა
|
||||
Stroke Color კონტურის ფერი
|
||||
Fill Gradient შევსების გრადიენტი
|
||||
Stroke Gradient კონტურის გრადიენტი
|
||||
@@ -8879,6 +8882,7 @@ liquify-list-end {0}, {1} {0} და {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` უნდა იყოს hex ფერი (#rgb, #rgba, #rrggbb ან #rrggbbaa) ან CSS ფერი rgb(), hsl() ან oklch(), არაუმეტეს 48 სიმბოლოსი
|
||||
@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 გადახლართვა
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -580,6 +580,9 @@ digits Malayalam 말라얄람어
|
||||
Make Sides Equal 변 길이 같게
|
||||
Opacity 불투명도
|
||||
Show Opacity 불투명도 표시
|
||||
Show Hex Field 16진수 필드 표시
|
||||
Hex or CSS color 16진수 또는 CSS 색상
|
||||
Parse Color 색상 구문 분석
|
||||
Pie End Angle: 파이 끝 각도:
|
||||
Pie Start Angle: 파이 시작 각도:
|
||||
Stroke Color 선 색상
|
||||
@@ -5644,6 +5647,7 @@ variable-list-end {0}, {1} {0} 및 {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text`은(는) 16진수 색상(#rgb, #rgba, #rrggbb 또는 #rrggbbaa)이거나 최대 48자의 CSS rgb(), hsl() 또는 oklch() 색상이어야 합니다
|
||||
@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여야 합니다
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1182,6 +1182,9 @@ liquify-list-end {0}, {1} {0} en {1}
|
||||
Fill Color Vulkleur
|
||||
Opacity Dekking
|
||||
Show Opacity Dekking tonen
|
||||
Show Hex Field Hexveld tonen
|
||||
Hex or CSS color Hex- of CSS-kleur
|
||||
Parse Color Kleur ontleden
|
||||
Stroke Color Contourkleur
|
||||
Fill Gradient Vulverloop
|
||||
Stroke Gradient Contourverloop
|
||||
@@ -9075,6 +9078,7 @@ mark-style Japanese Japans
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` moet een hexkleur (#rgb, #rgba, #rrggbb of #rrggbbaa) of een CSS-kleur rgb(), hsl() of oklch() van ten hoogste 48 tekens zijn
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -481,6 +481,9 @@
|
||||
Fill Color Kolor wypełnienia
|
||||
Opacity Krycie
|
||||
Show Opacity Pokaż krycie
|
||||
Show Hex Field Pokaż pole hex
|
||||
Hex or CSS color Kolor hex lub CSS
|
||||
Parse Color Analizuj kolor
|
||||
Stroke Color Kolor obrysu
|
||||
Fill Gradient Gradient wypełnienia
|
||||
Stroke Gradient Gradient obrysu
|
||||
@@ -5395,6 +5398,7 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` musi być kolorem hex (#rgb, #rgba, #rrggbb lub #rrggbbaa) albo kolorem CSS rgb(), hsl() lub oklch() o długości najwyżej 48 znaków
|
||||
@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ę
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2157,6 +2157,9 @@ antiAlias Sharp Nítido
|
||||
Only Web Colors Apenas Cores da Web
|
||||
Opacity Opacidade
|
||||
Show Opacity Mostrar Opacidade
|
||||
Show Hex Field Mostrar Campo Hex
|
||||
Hex or CSS color Cor hex ou CSS
|
||||
Parse Color Interpretar Cor
|
||||
Opacity & Mask Define Knockout Shape Opacidade e Máscara Definem Forma de Isolamento
|
||||
Opacity Mask Máscara de Opacidade
|
||||
Opacity Mask Info Informações da Máscara de Opacidade
|
||||
@@ -7030,6 +7033,7 @@ mark-style Japanese Japonesas
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` deve ser uma cor hex (#rgb, #rgba, #rrggbb ou #rrggbbaa) ou uma cor CSS rgb(), hsl() ou oklch() de no máximo 48 caracteres
|
||||
@msg the image can't be read as a texture a imagem não pode ser lida como textura
|
||||
|
||||
# User Interface › Accent Color
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2675,6 +2675,9 @@ file-filter Templates Шаблоны
|
||||
Only Web Colors Только web-цвета
|
||||
Opacity Непрозрачность
|
||||
Show Opacity Показать непрозрачность
|
||||
Show Hex Field Показать поле hex
|
||||
Hex or CSS color Цвет hex или CSS
|
||||
Parse Color Разобрать цвет
|
||||
Opacity & Mask Define Knockout Shape Непрозрачность и маска определяют форму вырезания
|
||||
Opacity Mask Непрозрачная маска
|
||||
Opacity Mask Info Сведения о непрозрачной маске
|
||||
@@ -5291,6 +5294,7 @@ liquify-list-end {0}, {1} {0} и {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` должно быть цветом hex (#rgb, #rgba, #rrggbb или #rrggbbaa) или цветом CSS rgb(), hsl() или oklch() длиной не более 48 символов
|
||||
@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}` — встроенная рабочая среда; выберите другое имя
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2574,6 +2574,9 @@ font-technology Variable Variabla
|
||||
Only Web Colors Endast webbfärger
|
||||
Opacity Opacitet
|
||||
Show Opacity Visa opacitet
|
||||
Show Hex Field Visa hexfält
|
||||
Hex or CSS color Hex- eller CSS-färg
|
||||
Parse Color Tolka färg
|
||||
Opacity & Mask Define Knockout Shape Opacitet och mask definierar utsparningsform
|
||||
Opacity Mask Opacitetsmask
|
||||
Opacity Mask Info Info om opacitetsmask
|
||||
@@ -7072,6 +7075,7 @@ theme Appearance Utseende
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` måste vara en hexfärg (#rgb, #rgba, #rrggbb eller #rrggbbaa) eller en CSS-färg rgb(), hsl() eller oklch() på högst 48 tecken
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2410,6 +2410,9 @@ font-technology Variable Değişken
|
||||
Only Web Colors Yalnızca Web Renkleri
|
||||
Opacity Opaklık
|
||||
Show Opacity Opaklığı Göster
|
||||
Show Hex Field Hex Alanını Göster
|
||||
Hex or CSS color Hex veya CSS rengi
|
||||
Parse Color Rengi Ayrıştır
|
||||
Opacity & Mask Define Knockout Shape Opaklık ve Maske Tanımlama Nakavt Şekli
|
||||
Opacity Mask Opaklık Maskesi
|
||||
Opacity Mask Info Opaklık Maskesi Bilgisi
|
||||
@@ -4985,6 +4988,7 @@ liquify-list-end {0}, {1} {0} ve {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` bir hex rengi (#rgb, #rgba, #rrggbb veya #rrggbbaa) ya da en fazla 48 karakterlik bir CSS rgb(), hsl() veya oklch() rengi olmalıdır
|
||||
@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ç
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2683,6 +2683,9 @@ file-filter Templates Шаблони
|
||||
Only Web Colors Тільки web-кольору
|
||||
Opacity Непрозорість
|
||||
Show Opacity Показати непрозорість
|
||||
Show Hex Field Показати поле hex
|
||||
Hex or CSS color Колір hex або CSS
|
||||
Parse Color Розібрати колір
|
||||
Opacity & Mask Define Knockout Shape Непрозорість та маска визначають форму вирізування
|
||||
Opacity Mask Маска непрозорості
|
||||
Opacity Mask Info Відомості про маску непрозорості
|
||||
@@ -5278,6 +5281,7 @@ liquify-list-end {0}, {1} {0} і {1}
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` має бути кольором hex (#rgb, #rgba, #rrggbb або #rrggbbaa) або кольором CSS rgb(), hsl() або oklch() довжиною не більше 48 символів
|
||||
@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}` - вбудоване робоче середовище; виберіть інше ім’я
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2948,6 +2948,9 @@ digits Hindi Hindi
|
||||
Only Web Colors Chỉ màu web
|
||||
Opacity Độ mờ
|
||||
Show Opacity Hiện độ mờ
|
||||
Show Hex Field Hiện trường hex
|
||||
Hex or CSS color Màu hex hoặc CSS
|
||||
Parse Color Phân tích màu
|
||||
Opacity & Mask Define Knockout Shape Độ mờ & Mặt nạ xác định hình dạng Knockout
|
||||
Opacity Mask Mặt nạ độ mờ
|
||||
Opacity Mask Info Thông tin mặt nạ độ mờ
|
||||
@@ -5266,6 +5269,7 @@ theme Appearance Giao diện
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` phải là màu hex (#rgb, #rgba, #rrggbb hoặc #rrggbbaa) hoặc màu CSS rgb(), hsl() hoặc oklch() dài tối đa 48 ký tự
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2536,6 +2536,9 @@ file-filter Templates 模板
|
||||
Only Web Colors 仅 Web 颜色
|
||||
Opacity 不透明度
|
||||
Show Opacity 显示不透明度
|
||||
Show Hex Field 显示十六进制字段
|
||||
Hex or CSS color 十六进制或 CSS 颜色
|
||||
Parse Color 解析颜色
|
||||
Opacity & Mask Define Knockout Shape 不透明度与蒙版定义挖空形状
|
||||
Opacity Mask 不透明度蒙版
|
||||
Opacity Mask Info 不透明度蒙版信息
|
||||
@@ -5383,6 +5386,7 @@ imageTrace Outline 轮廓
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` 必须是十六进制颜色 (#rgb、#rgba、#rrggbb 或 #rrggbbaa),或不超过 48 个字符的 CSS rgb()、hsl() 或 oklch() 颜色
|
||||
@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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2718,6 +2718,7 @@ file-filter Templates 範本
|
||||
@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 `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` 必須是十六進位顏色 (#rgb、#rgba、#rrggbb 或 #rrggbbaa),或不超過 48 個字元的 CSS rgb()、hsl() 或 oklch() 顏色
|
||||
@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
|
||||
@@ -3991,6 +3992,9 @@ liquify-list-end {0}, {1} {0}和{1}
|
||||
Only Web Colors 僅限網頁色彩
|
||||
Opacity 不透明度
|
||||
Show Opacity 顯示不透明度
|
||||
Show Hex Field 顯示十六進位欄位
|
||||
Hex or CSS color 十六進位或 CSS 顏色
|
||||
Parse Color 剖析顏色
|
||||
Opacity & Mask Define Knockout Shape 不透明度與遮色片定義挖空形狀
|
||||
Opacity Mask 不透明度遮色片
|
||||
Opacity Mask Info 不透明度遮色片資訊
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4,7 +4,8 @@ use super::{Sep, Value, VectorcraftApp, c, cp, heading, json, sub};
|
||||
use craft::menu::{Node, tidy};
|
||||
|
||||
/// The canvas context menu (right-click): what applies to the selection, or to the view when
|
||||
/// nothing is selected. Commands that can't run now are left out rather than greyed out.
|
||||
/// nothing is selected. Commands that can't run now are left out rather than greyed out; a plug-in
|
||||
/// command whose `when` fails for the selection is greyed out in the Plug-ins submenu.
|
||||
pub fn context_items(app: &VectorcraftApp) -> Vec<Node> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
@@ -140,6 +141,11 @@ pub fn context_items(app: &VectorcraftApp) -> Vec<Node> {
|
||||
Sep,
|
||||
c("Export Selection…", "file.exportSelection"),
|
||||
]);
|
||||
// The commands plug-in manifests list here (`menu.context`), each run on the selection.
|
||||
let ids: Vec<u64> = st.selection.objects.iter().map(|id| id.0).collect();
|
||||
if let Some(plugins) = crate::dialogs::plugin::canvas_submenu(&st.doc, &ids) {
|
||||
v.extend([Sep, plugins]);
|
||||
}
|
||||
}
|
||||
[spelling, prune(app, v)].concat()
|
||||
}
|
||||
|
||||
@@ -4,10 +4,11 @@ use super::{Value, VectorcraftApp, json};
|
||||
/// What a menu click runs: items whose label ends with "…" and that carry default params open a
|
||||
/// generic parameter dialog (fields = the defaults) instead of running immediately. A script of the
|
||||
/// Scripts folder runs, whatever its name ends with, and so does a proof setup saved in the Proof
|
||||
/// Setups folder.
|
||||
/// Setups folder. A plug-in command's item runs its command, which opens the plug-in's own dialog.
|
||||
pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) {
|
||||
let dialog = label.ends_with('…')
|
||||
&& p.as_object().is_some_and(|o| !o.is_empty())
|
||||
&& !vectorcraft_engine::cmd::plugin::is_command_id(id)
|
||||
&& !matches!(
|
||||
id,
|
||||
"effect.dialog"
|
||||
@@ -115,8 +116,9 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A plug-in command with parameters asks for them, from its menu item or its shortcut.
|
||||
if p.as_object().is_none_or(|o| o.is_empty()) && crate::dialogs::plugin::open_command(app, id) {
|
||||
// A plug-in command with parameters asks for them, from its menu item, its shortcut or a
|
||||
// context menu (which gives only `ids`).
|
||||
if crate::dialogs::plugin::open_command(app, id, &p) {
|
||||
return;
|
||||
}
|
||||
if open_view_dialog(app, id, &p) || open_object_dialog(app, id, &p) {
|
||||
|
||||
@@ -173,7 +173,9 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool {
|
||||
/// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden
|
||||
/// ([`east_asian_hidden`]).
|
||||
pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option<bool>)> {
|
||||
let en = enabled(app, id) && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p));
|
||||
let en = enabled(app, id)
|
||||
&& (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p))
|
||||
&& (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p));
|
||||
if (!en && hidden_when_disabled(id)) || swapped_out(app, id) || east_asian_hidden(app, id) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1133,13 +1133,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.brushOptions",
|
||||
"Brush Options…",
|
||||
"",
|
||||
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options",
|
||||
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options",
|
||||
),
|
||||
(
|
||||
"ui.brushObjectOptions",
|
||||
"Options of Selected Object…",
|
||||
"",
|
||||
"{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush",
|
||||
"{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, scaleMax/scaleMode, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush",
|
||||
),
|
||||
(
|
||||
"ui.graphicStyleOptions",
|
||||
@@ -1616,7 +1616,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.colorWheel",
|
||||
"Color Wheel Options",
|
||||
"",
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: 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, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: 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 at or below the one asked for; 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; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); 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; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); 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 active document's RGB space (its assigned profile, else 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, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors
Line truncated
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: 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, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: 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 at or below the one asked for; 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; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); 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; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); 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,
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.savePdfDialog",
|
||||
|
||||
@@ -65,7 +65,8 @@ use craft::theme::variant::Tone;
|
||||
use craft::ui::buttons::{IconButton, Link, PopupMark};
|
||||
use craft::ui::choice::{Radio, RadioGroup, SwatchSpacing};
|
||||
use craft::ui::contract::{
|
||||
Bind, CaptionColumn, CommandSet as _, Entry, LabelScheme, ListDrag, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, Trigger,
|
||||
Bind, CaptionColumn, CommandSet as _, Entry, Gap, LabelScheme, ListDrag, Pad, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing,
|
||||
Trigger,
|
||||
};
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
@@ -1068,11 +1069,28 @@ pub(crate) fn option_link(label: impl Into<Label>) -> Link {
|
||||
/// The empty state of a panel with nothing to show: `icon` over the title and the message,
|
||||
/// centred in the panel.
|
||||
pub(crate) fn empty_state(ui: &mut Ui, icon: &'static str, title: &str, body: &str) {
|
||||
Notice::new(Tone::Neutral, body.to_owned())
|
||||
.layout(NoticeLayout::Centred)
|
||||
.title(title.to_owned())
|
||||
.icon(NoticeIcon::Custom(IconSpec::svg(IconId::new(icon))))
|
||||
.show(ui);
|
||||
notice_frame(ui, |ui| {
|
||||
Notice::new(Tone::Neutral, body.to_owned())
|
||||
.layout(NoticeLayout::Centred)
|
||||
.title(title.to_owned())
|
||||
.icon(NoticeIcon::Custom(IconSpec::svg(IconId::new(icon))))
|
||||
.show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// Shows a panel's centred notice inside the roomy pad, so that it keeps its distance from the tab strip, the panel's
|
||||
/// edges and the controls above it.
|
||||
pub(crate) fn notice_frame<R>(ui: &mut Ui, mut body: impl FnMut(&mut Ui) -> R) -> Option<R> {
|
||||
let mut out = None;
|
||||
Stack::new().fill_width().pad(Pad::Roomy).show(ui, |ui, _| out = Some(body(ui)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The body of a popover holding a form: the regular pad around it and the stack gap between its rows.
|
||||
pub(crate) fn popover_body<R>(ui: &mut Ui, mut body: impl FnMut(&mut Ui) -> R) -> Option<R> {
|
||||
let mut out = None;
|
||||
Stack::new().pad(Pad::Regular).gap(Gap::Stack).show(ui, |ui, _| out = Some(body(ui)));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1215,6 +1233,8 @@ mod tests_color_wheel_gamut;
|
||||
#[cfg(test)]
|
||||
mod tests_color_wheel_harmony;
|
||||
#[cfg(test)]
|
||||
mod tests_color_wheel_hex;
|
||||
#[cfg(test)]
|
||||
mod tests_color_wheel_opacity;
|
||||
#[cfg(test)]
|
||||
mod tests_color_wheel_vision;
|
||||
|
||||
@@ -1315,3 +1315,30 @@ fn artboard_options_groups_are_a_section_gap_apart() {
|
||||
assert!((gap - row).abs() < 0.01, "{upper} to {lower}: {gap} apart, the row gap is {row}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The list fills the panel above its footer, so the footer's buttons sit at the bottom of the panel and follow its
|
||||
/// height, as the Layers panel's do, and a list longer than the panel scrolls above them (#6085).
|
||||
#[test]
|
||||
fn the_list_fills_the_panel_and_the_bottom_bar_follows_its_height() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 200, "height": 150, "artboards": 36})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
// The bottom of the footer's New Artboard button in a panel `h` points tall.
|
||||
let bar_bottom = |panel: &mut Panel, h: f32| {
|
||||
panel.room(egui::vec2(300.0, h));
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
panel.rect("New Artboard").bottom()
|
||||
};
|
||||
let short = bar_bottom(&mut panel, 300.0);
|
||||
assert!(short <= 300.0, "the buttons end inside a 300 pt panel, not below it: {short}");
|
||||
assert!(short > 300.0 - 40.0, "the buttons sit at the bottom of a 300 pt panel: {short}");
|
||||
// The 36th row lies at or below the footer: the rows overflow the panel and scroll above it.
|
||||
let footer_top = panel.rect("New Artboard").top();
|
||||
let hidden = !panel.shows("Artboard 36") || panel.rect("Artboard 36").top() >= footer_top;
|
||||
assert!(hidden, "the 36 rows overflow a 300 pt panel and scroll above the buttons at {footer_top}");
|
||||
let tall = bar_bottom(&mut panel, 700.0);
|
||||
assert!(tall <= 700.0, "the buttons end inside a 700 pt panel: {tall}");
|
||||
assert!(tall - short > 350.0, "the buttons follow the panel's height: {short} -> {tall}");
|
||||
}
|
||||
@@ -27,6 +27,13 @@
|
||||
//! selected, for an object selected in a symbol instance, and when the fill or stroke item it
|
||||
//! would set is on type characters or missing.
|
||||
//!
|
||||
//! Panel menu › Show Hex Field adds a field under the wheel or the box that shows the color's six
|
||||
//! hex digits, and two more when the opacity that Show Opacity sets rounds to less than `ff`. It
|
||||
//! takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color
|
||||
//! (`color.parse`). A typed color is applied in the same way as a pick, and an alpha sets the
|
||||
//! opacity that Show Opacity sets, whether or not that row shows. Where that row is gray, only the
|
||||
//! color is applied.
|
||||
//!
|
||||
//! Panel menu › Show Contrast adds a row under the wheel or the box with the WCAG 2 contrast ratio
|
||||
//! (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>) of the color against the color drawn
|
||||
//! behind the selection, or against a color pinned with Contrast Background › Current Color, and
|
||||
@@ -52,8 +59,8 @@
|
||||
//! preferences too.
|
||||
//!
|
||||
//! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule,
|
||||
//! Show Opacity, the contrast settings, Show Color Vision Preview and Show Document Colors are kept
|
||||
//! with the preferences (`ui.colorWheel`).
|
||||
//! Show Opacity, Show Hex Field, the contrast settings, Show Color Vision Preview and Show Document
|
||||
//! Colors are kept with the preferences (`ui.colorWheel`).
|
||||
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
@@ -68,13 +75,14 @@ use craft::color_ui::ui::{ChannelRow, ChannelUnit, ColorArea, ColorStrip, ColorW
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::theme::{ColorModel, HsbModel, ModelValues, RgbModel, Srgba};
|
||||
use craft::ui::choice::{Swatch, SwatchSpacing, SwatchTable};
|
||||
use craft::ui::contract::{ActivateOn, Bind, EditResponse, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{ActivateOn, Bind, EditResponse, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::layout::CellAlign;
|
||||
use craft::ui::layout_components::{Grid, Row, Stack};
|
||||
use craft::ui::menu::PanelRow;
|
||||
use craft::ui::runtime::commands::{CommandState, CommandStates};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::text::TextField;
|
||||
use egui::Ui;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -192,6 +200,9 @@ pub struct Settings {
|
||||
/// Show Opacity: the opacity row under the wheel or the box.
|
||||
#[serde(deserialize_with = "deserialize_flag")]
|
||||
pub opacity: bool,
|
||||
/// Show Hex Field: the field for a hex or CSS color under the wheel or the box.
|
||||
#[serde(deserialize_with = "deserialize_flag")]
|
||||
pub hex_field: bool,
|
||||
/// Show Contrast: the contrast row under the wheel or the box.
|
||||
#[serde(deserialize_with = "deserialize_flag")]
|
||||
pub contrast: bool,
|
||||
@@ -255,6 +266,7 @@ impl Default for Settings {
|
||||
harmony: false,
|
||||
harmony_rule: Harmony::Complementary,
|
||||
opacity: false,
|
||||
hex_field: false,
|
||||
contrast: false,
|
||||
contrast_for: Category::default(),
|
||||
contrast_background: None,
|
||||
@@ -329,14 +341,14 @@ 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?, sliders?, gamut?, harmony?, harmonyRule?, opacity?, contrast?,
|
||||
/// contrastFor?, contrastBackground?, vision?, documentColors?}`: show the wheel or the box, pick
|
||||
/// the box's channel, show OKLCH Sliders, HSL Sliders or neither, show or hide the out-of-gamut
|
||||
/// shading, show the colors of a harmony rule on the wheel, check or uncheck Show Opacity, set the
|
||||
/// contrast row, its category and its pinned background (`contrastBackground: null` unpins it),
|
||||
/// and show or hide the color vision row and the Show Document Colors row. Keys left out keep
|
||||
/// their values, and so do the other keys when null; params that are not an object, another key
|
||||
/// or a value off the list are an error and change nothing.
|
||||
/// `ui.colorWheel {view?, channel?, sliders?, gamut?, harmony?, harmonyRule?, opacity?, hexField?,
|
||||
/// contrast?, contrastFor?, contrastBackground?, vision?, documentColors?}`: show the wheel or the
|
||||
/// box, pick the box's channel, show OKLCH Sliders, HSL Sliders or neither, show or hide the
|
||||
/// out-of-gamut shading, show the colors of a harmony rule on the wheel, check or uncheck Show
|
||||
/// Opacity and Show Hex Field, set the contrast row, its category and its pinned background
|
||||
/// (`contrastBackground: null` unpins it), and show or hide the color vision row and the Show
|
||||
/// Document Colors row. Keys left out keep their values, and so do the other keys when null; 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> {
|
||||
@@ -347,7 +359,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri
|
||||
/// 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; 12] = [
|
||||
const KEYS: [&str; 13] = [
|
||||
"view",
|
||||
"channel",
|
||||
"sliders",
|
||||
@@ -355,6 +367,7 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S
|
||||
"harmony",
|
||||
"harmonyRule",
|
||||
"opacity",
|
||||
"hexField",
|
||||
"contrast",
|
||||
"contrastFor",
|
||||
"contrastBackground",
|
||||
@@ -412,6 +425,9 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S
|
||||
if let Some(on) = crate::menus::opt_bool(p, "opacity")? {
|
||||
set.opacity = on;
|
||||
}
|
||||
if let Some(on) = crate::menus::opt_bool(p, "hexField")? {
|
||||
set.hex_field = on;
|
||||
}
|
||||
match p.get("contrast") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(v) => {
|
||||
@@ -518,6 +534,7 @@ fn items(set: &Settings, srgb: bool, current: Option<Color>) -> Vec<Item> {
|
||||
));
|
||||
}
|
||||
out.push(item("opacity".into(), tl!("Show Opacity"), set.opacity, true, json!({ "opacity": !set.opacity })));
|
||||
out.push(item("hexField".into(), tl!("Show Hex Field"), set.hex_field, true, json!({ "hexField": !set.hex_field })));
|
||||
out.push(item("contrast".into(), tl!("Show Contrast"), set.contrast, true, json!({ "contrast": !set.contrast })));
|
||||
for c in Category::ALL {
|
||||
out.push(item(category_row_id(c), category_name(c), set.contrast_for == c, true, json!({ "contrastFor": c.id() })));
|
||||
@@ -539,8 +556,8 @@ fn items(set: &Settings, srgb: bool, current: Option<Color>) -> Vec<Item> {
|
||||
|
||||
/// The panel menu: Wheel View and Box View, and Box Channel while the box shows; Show Out-of-Gamut
|
||||
/// Colors; HSL Sliders and OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; Show
|
||||
/// Opacity; Show Contrast, Contrast For and Contrast Background; Show Color Vision Preview; and
|
||||
/// Show Document Colors.
|
||||
/// Opacity and Show Hex Field; Show Contrast, Contrast For and Contrast Background; Show Color
|
||||
/// Vision Preview; and Show Document Colors.
|
||||
pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
|
||||
let command = |row: String| PanelRow::Command(CommandRef::new(row_id(&row)));
|
||||
let mut rows = vec![command("view.wheel".into()), command("view.box".into())];
|
||||
@@ -551,7 +568,7 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
|
||||
rows.push(PanelRow::Separator);
|
||||
rows.extend(["gamut", "sliders.hsl", "sliders.oklch", "harmony"].map(|row| command(row.into())));
|
||||
rows.push(PanelRow::Submenu(Label::from(tl!("Harmony Rule").to_string()), harmony_rules().map(|rule| command(rule_row_id(rule))).collect()));
|
||||
rows.extend(["opacity", "contrast"].map(|row| command(row.into())));
|
||||
rows.extend(["opacity", "hexField", "contrast"].map(|row| command(row.into())));
|
||||
rows.push(PanelRow::Submenu(
|
||||
Label::from(tl!("Contrast For").to_string()),
|
||||
Category::ALL.into_iter().map(|c| command(category_row_id(c))).collect(),
|
||||
@@ -1082,7 +1099,11 @@ pub(crate) fn stored(cms: &Cms, hsb: [f32; 3], was: Option<&Color>, cmyk_doc: bo
|
||||
/// [`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);
|
||||
stored_rgb(cms, Color::rgb(r, g, b), was, cmyk_doc)
|
||||
}
|
||||
|
||||
/// [`stored`] for the RGB color `rgb` in the working RGB space.
|
||||
fn stored_rgb(cms: &Cms, rgb: Color, was: Option<&Color>, cmyk_doc: bool) -> Color {
|
||||
let cmyk = || {
|
||||
let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
|
||||
Color::cmyk(c, m, y, k)
|
||||
@@ -1201,7 +1222,9 @@ impl Remembered {
|
||||
}
|
||||
|
||||
/// What a pick needs to become a color of the target: the target, the color settings, Alt (`behind`),
|
||||
/// the document's color mode and the HSB the panel showed.
|
||||
/// the document's color mode and the HSB the panel showed. `drawn` is the HSB the wheel or the box
|
||||
/// was drawn with when the hex field's text changed the color in the same frame: the pick then
|
||||
/// sets only the components it moved.
|
||||
struct Pick<'a> {
|
||||
tgt: &'a Target,
|
||||
color: Option<Color>,
|
||||
@@ -1209,6 +1232,26 @@ struct Pick<'a> {
|
||||
behind: bool,
|
||||
cmyk_doc: bool,
|
||||
shown: [f32; 3],
|
||||
drawn: Option<[f32; 3]>,
|
||||
}
|
||||
|
||||
/// The values `hsb` gives in `model`, the widgets' HSB or RGB.
|
||||
fn values_in(model: &'static str, hsb: [f32; 3]) -> ModelValues {
|
||||
if model == HsbModel.id() { hsb_values(hsb) } else { rgb_values(hsb) }
|
||||
}
|
||||
|
||||
/// The widget values `v` with each component left as the widget was drawn with `drawn` taken from
|
||||
/// `now` instead: a pick read after the hex field's text sets only the components it moved, on the
|
||||
/// color the text left.
|
||||
fn rebased(v: ModelValues, drawn: [f32; 3], now: [f32; 3]) -> ModelValues {
|
||||
let (was, now) = (values_in(v.model, drawn), values_in(v.model, now));
|
||||
let mut out = v;
|
||||
for (i, slot) in out.values.iter_mut().enumerate().take(3) {
|
||||
if (v.values[i] - was.values[i]).abs() <= 1e-3 {
|
||||
*slot = now.values[i];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Pick<'_> {
|
||||
@@ -1243,8 +1286,32 @@ impl Pick<'_> {
|
||||
|
||||
/// Apply the picks a wheel, field or strip edit carries.
|
||||
fn edits(&self, app: &mut VectorcraftApp, panel: &mut WheelUi, edit: &EditResponse<ModelValues>) {
|
||||
apply_edits(app, edit, EditPath::Preview, |app, v, phase| self.hsb(app, panel, picked_hsb(v, self.shown), phase));
|
||||
apply_edits(app, edit, EditPath::Preview, |app, v, phase| {
|
||||
let v = match self.drawn {
|
||||
Some(drawn) => rebased(*v, drawn, self.shown),
|
||||
None => *v,
|
||||
};
|
||||
self.hsb(app, panel, picked_hsb(&v, self.shown), phase);
|
||||
});
|
||||
}
|
||||
|
||||
/// Apply what the wheel or the box reported in the frame.
|
||||
fn picked(&self, app: &mut VectorcraftApp, panel: &mut WheelUi, picked: Picked) {
|
||||
if let Some(hsb) = picked.marker {
|
||||
self.hsb(app, panel, hsb, Live::Released);
|
||||
}
|
||||
for edit in &picked.edits {
|
||||
self.edits(app, panel, edit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the wheel or the box reported in a frame: the color of a harmony marker clicked, and the
|
||||
/// edits of the wheel, the field and the strip. They are applied after the hex field's text.
|
||||
#[derive(Default)]
|
||||
struct Picked {
|
||||
marker: Option<[f32; 3]>,
|
||||
edits: Vec<EditResponse<ModelValues>>,
|
||||
}
|
||||
|
||||
/// The colors of the track of OKLCH row `i`, from the cache while the other two components are
|
||||
@@ -1286,6 +1353,9 @@ fn oklch_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &P
|
||||
// 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 };
|
||||
let marks = [(max_c / CHROMA_FULL * 100.0).clamp(0.0, 100.0)];
|
||||
// The components the rows applied in this frame: a value typed in one row's field and committed
|
||||
// by a click on another row keeps both.
|
||||
let mut now = lch;
|
||||
// The rows read dim and take no edit without a colour to edit.
|
||||
Stack::new().enabled(enabled).show(ui, |ui, _| {
|
||||
for (i, &(letter, ref name, max, unit)) in rows.iter().enumerate() {
|
||||
@@ -1299,8 +1369,8 @@ fn oklch_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &P
|
||||
}
|
||||
if let Some(edit) = row.show(ui) {
|
||||
apply_edits(app, &edit, EditPath::Preview, |app, v, phase| {
|
||||
let lch = oklch_with(lch, i, *v);
|
||||
cx.rows(app, panel, oklab::from_oklch(lch[0], lch[1], lch[2]).0, phase, Remembered::Oklch(lch));
|
||||
now = oklch_with(now, i, *v);
|
||||
cx.rows(app, panel, oklab::from_oklch(now[0], now[1], now[2]).0, phase, Remembered::Oklch(now));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1327,6 +1397,8 @@ fn hsl_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pic
|
||||
("L", hsl_name(tl!("Lightness")), 100.0, ChannelUnit::Percent),
|
||||
];
|
||||
let shown = [f64::from(hsl[0]), f64::from(hsl[1]) * 100.0, f64::from(hsl[2]) * 100.0];
|
||||
// The components the rows applied in this frame, as for the OKLCH rows.
|
||||
let mut now = hsl;
|
||||
// The rows read dim and take no edit without a colour to edit.
|
||||
Stack::new().enabled(enabled).show(ui, |ui, _| {
|
||||
for (i, &(letter, ref name, max, unit)) in rows.iter().enumerate() {
|
||||
@@ -1338,8 +1410,8 @@ fn hsl_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pic
|
||||
}
|
||||
if let Some(edit) = row.show(ui) {
|
||||
apply_edits(app, &edit, EditPath::Preview, |app, v, phase| {
|
||||
let hsl = hsl_with(hsl, i, *v);
|
||||
cx.rows(app, panel, hsl_to_rgb(hsl), phase, Remembered::Hsl(hsl));
|
||||
now = hsl_with(now, i, *v);
|
||||
cx.rows(app, panel, hsl_to_rgb(now), phase, Remembered::Hsl(now));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1415,11 +1487,13 @@ fn end_opacity_drag(app: &mut VectorcraftApp, panel: &mut WheelUi) {
|
||||
|
||||
/// The Show Opacity row: a slider whose track shows `color` through `cms` from clear to solid over
|
||||
/// the transparency checkerboard, and a percent field. Gray when [`shown_opacity`] finds nothing
|
||||
/// to set.
|
||||
fn opacity_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, tgt: &Target, color: &Color, cms: &Cms) {
|
||||
/// to set. Returns the row's edit when it has events, for [`apply_opacity_edit`] after the hex
|
||||
/// field's text.
|
||||
fn opacity_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, tgt: &Target, color: &Color, cms: &Cms) -> Option<EditResponse<f64>> {
|
||||
let (o, live) = shown_opacity(app, tgt);
|
||||
let [r, g, b] = cms.display_rgb(color).map(|v| v.clamp(0.0, 1.0));
|
||||
let track = vec![Srgba::new(r, g, b, 0.0), Srgba::new(r, g, b, 1.0)];
|
||||
let mut out = None;
|
||||
// The row reads dim and takes no edit with nothing it can set.
|
||||
Stack::new().enabled(live).show(ui, |ui, _| {
|
||||
let rule = super::whole_steps(0.0..=100.0);
|
||||
@@ -1427,25 +1501,133 @@ fn opacity_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, tgt:
|
||||
.unit(ChannelUnit::Percent)
|
||||
.track(track.clone())
|
||||
.checker(true);
|
||||
if let Some(edit) = row.show(ui)
|
||||
&& live
|
||||
{
|
||||
apply_edits(app, &edit, EditPath::Preview, |app, v, phase| {
|
||||
apply_opacity(app, tgt, (*v / 100.0) as f32, phase);
|
||||
panel.opacity_live = phase == Live::Dragging;
|
||||
});
|
||||
}
|
||||
out = row.show(ui).filter(|edit| live && edit.events.iter().next().is_some());
|
||||
});
|
||||
// A drag whose row turned gray reports no release.
|
||||
if !live {
|
||||
end_opacity_drag(app, panel);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Apply the Show Opacity row's `edit` to `tgt`.
|
||||
fn apply_opacity_edit(app: &mut VectorcraftApp, panel: &mut WheelUi, tgt: &Target, edit: &EditResponse<f64>) {
|
||||
apply_edits(app, edit, EditPath::Preview, |app, v, phase| {
|
||||
apply_opacity(app, tgt, (*v / 100.0) as f32, phase);
|
||||
panel.opacity_live = phase == Live::Dragging;
|
||||
});
|
||||
}
|
||||
|
||||
/// The six hex digits of a color's working RGB components (`E67828`).
|
||||
fn hex_digits(c: &Color) -> String {
|
||||
let [r, g, b] = super::color::working_rgb(c).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
format!("{r:02X}{g:02X}{b:02X}")
|
||||
}
|
||||
|
||||
/// The text the hex field shows for `color` and the opacity `o` the row of Show Opacity edits
|
||||
/// (`None` when it has nothing to edit): six hex digits of the document's RGB numbers, and two more
|
||||
/// when the opacity rounds to less than `ff`. Empty without a solid color.
|
||||
pub(crate) fn hex_text(color: Option<&Color>, o: Option<f32>) -> String {
|
||||
let Some(c) = color else { return String::new() };
|
||||
let mut text = hex_digits(c);
|
||||
let alpha = o.map(|o| (o.clamp(0.0, 1.0) * 255.0).round() as u8).filter(|a| *a < 255);
|
||||
if let Some(a) = alpha {
|
||||
text.push_str(&format!("{a:02X}"));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Apply `c`, typed into the hex field, to `tgt` in one undo step, as a pick applies a color; the
|
||||
/// alpha `alpha` (0 to 1) also sets the opacity of what the row of Show Opacity edits, when it has
|
||||
/// something to edit.
|
||||
fn apply_typed(app: &mut VectorcraftApp, tgt: &Target, c: Color, alpha: Option<f32>) {
|
||||
let alpha = alpha.filter(|_| shown_opacity(app, tgt).1).map(|a| a.clamp(0.0, 1.0));
|
||||
match tgt {
|
||||
Target::Stop { paint: Paint::Gradient(g), index, .. } => {
|
||||
let mut stops = g.gradient.stops.clone();
|
||||
if let Some(s) = stops.get_mut(*index) {
|
||||
s.set_color(c, None);
|
||||
if let Some(a) = alpha {
|
||||
s.opacity = a;
|
||||
}
|
||||
}
|
||||
super::gradient::set_stops_keeping_models(app, &stops, None, Live::Released);
|
||||
}
|
||||
Target::Point { index, .. } => {
|
||||
let mut p = json!({"index": index, "color": super::color_json(&c), "stroke": !app.session.fill_active, "keepModel": true});
|
||||
if let Some(a) = alpha {
|
||||
p["opacity"] = json!(a);
|
||||
}
|
||||
super::live_run(app, "Color", "paint.freeform.setPoint", p, Live::Released);
|
||||
}
|
||||
_ => {
|
||||
let cmd = super::proxy_cmd(app, false);
|
||||
let mut p = json!({"color": super::color_json(&c), "focus": true, "keepModel": true});
|
||||
if let Some(a) = alpha {
|
||||
p["opacity"] = json!(f64::from(a) * 100.0);
|
||||
}
|
||||
super::live_run(app, "Color", cmd, p, Live::Released);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The text the hex field shows for `tgt` and its color, as [`hex_text`] gives it.
|
||||
fn hex_shown(app: &VectorcraftApp, tgt: &Target, color: Option<&Color>) -> String {
|
||||
let (o, live) = shown_opacity(app, tgt);
|
||||
hex_text(color, live.then_some(o))
|
||||
}
|
||||
|
||||
/// The hex field's id salt for `tgt`: it names the document, the selected objects or text
|
||||
/// characters, the object selected in a symbol instance, the appearance item, the proxy and the
|
||||
/// gradient stop or freeform point, but not the color, so a text typed for one of them is dropped
|
||||
/// when another one is targeted, even one showing the same hex.
|
||||
fn hex_field_salt(app: &VectorcraftApp, tgt: &Target) -> u64 {
|
||||
let o = Owner::of(app, tgt, Color::rgb8(0, 0, 0));
|
||||
let part = app.session.active().and_then(|d| d.selection.symbol_part.as_ref().map(|p| (p.instance, p.path.clone())));
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
("color-wheel-hex", o.doc, o.selection, part, o.text_selection, o.appearance_item, o.fill, o.slot).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// The Show Hex Field row for `tgt`: a field as wide as the row with a `#` before the text,
|
||||
/// showing `shown`. Returns the text committed with Enter or by moving the focus away.
|
||||
fn hex_row(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str) -> Option<String> {
|
||||
let edit = TextField::new(tl!("Hex or CSS color").to_string(), Bind::given(shown.to_owned()))
|
||||
.prefix("#")
|
||||
.submits()
|
||||
.select_on_focus()
|
||||
.id_salt(hex_field_salt(app, tgt))
|
||||
.sizing(Sizing::FillWidth)
|
||||
.show(ui);
|
||||
edit.events.committed().cloned()
|
||||
}
|
||||
|
||||
/// Apply the hex field's committed `text`: it goes through `color.parse` as typed, and a text it
|
||||
/// refuses shows its error in the status bar and changes nothing. The text's alpha is not applied
|
||||
/// when `opacity_set` (the opacity row set the opacity in this frame), so a press on that row that
|
||||
/// commits the text keeps the opacity it set. When the text is the one the field shows
|
||||
/// (`retyped`), its alpha stands for the opacity the field shows, not the value its two digits
|
||||
/// round to, so retyping it leaves that opacity as it was.
|
||||
fn apply_text(app: &mut VectorcraftApp, ui: &Ui, text: &str, opacity_set: bool, retyped: bool) {
|
||||
match app.run("color.parse", json!({ "text": text })) {
|
||||
Ok(r) => {
|
||||
let Ok(rgb) = serde_json::from_value::<Color>(r["color"].clone()) else { return };
|
||||
let tgt = wheel_target(app, ui);
|
||||
// The document's RGB numbers, in the model a pick would store them in.
|
||||
let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk);
|
||||
let c = stored_rgb(&cms::active(), rgb, replaced(app, &tgt, false).as_ref(), cmyk_doc);
|
||||
let alpha = r["opacity"].as_f64().map(|o| (o / 100.0) as f32).filter(|_| !opacity_set);
|
||||
let alpha = alpha.map(|a| if retyped { shown_opacity(app, &tgt).0 } else { a });
|
||||
apply_typed(app, &tgt, c, alpha);
|
||||
}
|
||||
Err(e) => app.status(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The wheel: the hue ring around the saturation and brightness square, with Show Harmony's markers
|
||||
/// on the ring. A click on a marker applies its color; a press held on one keeps the ring from
|
||||
/// picking.
|
||||
fn show_wheel(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pick, set: &Settings) {
|
||||
fn show_wheel(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> Picked {
|
||||
let marked = cx.color.is_some();
|
||||
let others: Vec<[f32; 3]> = if set.harmony && marked { set.harmony_rule.apply_hsb(cx.shown).into_iter().skip(1).collect() } else { Vec::new() };
|
||||
let markers: Vec<Srgba> = others.iter().map(|&hsb| srgb(hsb_to_rgb(hsb))).collect();
|
||||
@@ -1459,13 +1641,13 @@ fn show_wheel(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &P
|
||||
}
|
||||
let out = wheel.show(ui);
|
||||
match out.picked.and_then(|i| others.get(i)) {
|
||||
Some(&hsb) => cx.hsb(app, panel, hsb, Live::Released),
|
||||
None => cx.edits(app, panel, &out.edit),
|
||||
Some(&hsb) => Picked { marker: Some(hsb), edits: Vec::new() },
|
||||
None => Picked { marker: None, edits: vec![out.edit] },
|
||||
}
|
||||
}
|
||||
|
||||
/// The box: the field of channel `set.channel` and its strip.
|
||||
fn show_box(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pick, set: &Settings) {
|
||||
fn show_box(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> Picked {
|
||||
let ch = set.channel;
|
||||
let mode = area_mode(ch);
|
||||
let values = cx.color.map(|_| box_values(ch, cx.shown));
|
||||
@@ -1473,8 +1655,9 @@ fn show_box(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pic
|
||||
if set.gamut {
|
||||
area = area.gamut(gamut(app));
|
||||
}
|
||||
cx.edits(app, panel, &area.show(ui));
|
||||
cx.edits(app, panel, &ColorStrip::new(ch.name().to_string(), mode, bind(values)).show(ui));
|
||||
let field = area.show(ui);
|
||||
let strip = ColorStrip::new(ch.name().to_string(), mode, bind(values)).show(ui);
|
||||
Picked { marker: None, edits: vec![field, strip] }
|
||||
}
|
||||
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
@@ -1484,52 +1667,113 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
app.ui.color_wheel_panel = panel;
|
||||
}
|
||||
|
||||
/// The HSB the wheel shows for `tgt`'s `color`: the one picked last while it still applies, else
|
||||
/// the color's display HSB. With None, a pattern or a "?" proxy, that of the last solid color.
|
||||
fn shown_hsb(app: &VectorcraftApp, panel: &mut WheelUi, tgt: &Target, color: Option<Color>, cms: &Cms) -> [f32; 3] {
|
||||
match (color, recall(&mut panel.hsb, app, 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)),
|
||||
}
|
||||
}
|
||||
|
||||
fn show_with(app: &mut VectorcraftApp, panel: &mut WheelUi, 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 widgets show no markers, and a pick applies its color.
|
||||
let hsb = match (color, recall(&mut panel.hsb, app, &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 hsb = shown_hsb(app, panel, &tgt, color, &cms);
|
||||
let behind = alt_held(ui);
|
||||
let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk);
|
||||
let cx = Pick { tgt: &tgt, color, cms: &cms, behind, cmyk_doc, shown: hsb };
|
||||
let cx = Pick { tgt: &tgt, color, cms: &cms, behind, cmyk_doc, shown: hsb, drawn: None };
|
||||
let set = app.ui.color_wheel.clone();
|
||||
let now = ui.input(|i| i.time);
|
||||
// The stack's gap separates the rows.
|
||||
Stack::new().show(ui, |ui, _| show_rows(app, panel, ui, &cx, &set, now));
|
||||
}
|
||||
|
||||
/// The panel's rows: the Fill/Stroke proxy beside the box or the wheel, level with its top, then the slider rows,
|
||||
/// the color vision row and the document colors row that `set` turns on.
|
||||
/// The panel's rows: the Fill/Stroke proxy beside the box or the wheel, level with its top, then the opacity row, the
|
||||
/// hex field, the slider rows, the contrast row, the color vision row and the document colors row that `set` turns on.
|
||||
fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pick, set: &Settings, now: f64) {
|
||||
let (cms, behind, cmyk_doc, hsb) = (cx.cms, cx.behind, cx.cmyk_doc, cx.shown);
|
||||
let mut picked = Picked::default();
|
||||
Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| {
|
||||
super::proxy(app, ui);
|
||||
match set.view {
|
||||
View::Box => {
|
||||
Row::new().fill_width().show(ui, |ui, _| show_box(app, panel, ui, cx, set));
|
||||
Row::new().fill_width().show(ui, |ui, _| picked = show_box(app, ui, cx, set));
|
||||
}
|
||||
View::Wheel => show_wheel(app, panel, ui, cx, set),
|
||||
View::Wheel => picked = show_wheel(app, ui, cx, set),
|
||||
}
|
||||
});
|
||||
if set.opacity {
|
||||
let (color, tgt) = (cx.color, cx.tgt);
|
||||
let shown = color.unwrap_or(app.session.last_solid);
|
||||
let owner = color.map(|c| Owner::of(app, tgt, c));
|
||||
opacity_row(app, panel, ui, tgt, &shown, cx.cms);
|
||||
// An opacity edit adds an undo step, and on a gradient stop or point it also changes the
|
||||
// gradient its owner holds. The HSB, HSL and OKLCH picked last stay with the edited paint.
|
||||
if let (Some(c), Some(was)) = (color, owner) {
|
||||
let now = Owner::of(app, tgt, c);
|
||||
rekey(&mut panel.hsb, &was, &now);
|
||||
rekey(&mut panel.hsl, &was, &now);
|
||||
rekey(&mut panel.oklch, &was, &now);
|
||||
}
|
||||
// The hex field shows the text of the frame's start, so a text committed when a press on the
|
||||
// opacity row takes the focus is kept.
|
||||
let hex = set.hex_field.then(|| hex_shown(app, cx.tgt, cx.color.as_ref()));
|
||||
let opacity_edit = if set.opacity {
|
||||
let shown = cx.color.unwrap_or(app.session.last_solid);
|
||||
opacity_row(app, panel, ui, cx.tgt, &shown, cms)
|
||||
} else {
|
||||
end_opacity_drag(app, panel);
|
||||
None
|
||||
};
|
||||
let typed = hex.and_then(|hex| {
|
||||
hex_row(app, ui, cx.tgt, &hex).map(|text| {
|
||||
let shown = text.strip_prefix('#').unwrap_or(&text).eq_ignore_ascii_case(&hex);
|
||||
(text, shown)
|
||||
})
|
||||
});
|
||||
// A text committed by a press on the wheel, the box or the opacity row is applied first; the
|
||||
// opacity edit then goes to the target as the text left it, and a pick to the target as both
|
||||
// left it, so a stop keeps all of them.
|
||||
if let Some((text, shown)) = &typed {
|
||||
apply_text(app, ui, text, opacity_edit.is_some(), *shown);
|
||||
}
|
||||
let after_text;
|
||||
let tgt = if typed.is_some() {
|
||||
after_text = wheel_target(app, ui);
|
||||
&after_text
|
||||
} else {
|
||||
cx.tgt
|
||||
};
|
||||
if let Some(edit) = &opacity_edit {
|
||||
let owner = tgt.color().map(|c| (c, Owner::of(app, tgt, c)));
|
||||
apply_opacity_edit(app, panel, tgt, edit);
|
||||
// An opacity edit adds an undo step, and on a gradient stop or point it also changes the
|
||||
// gradient its owner holds. The HSB, HSL and OKLCH picked last stay with the edited paint.
|
||||
if let Some((c, was)) = owner {
|
||||
let moved = Owner::of(app, tgt, c);
|
||||
rekey(&mut panel.hsb, &was, &moved);
|
||||
rekey(&mut panel.hsl, &was, &moved);
|
||||
rekey(&mut panel.oklch, &was, &moved);
|
||||
}
|
||||
}
|
||||
let changed = typed.is_some() || opacity_edit.is_some();
|
||||
let after_opacity;
|
||||
let tgt = if opacity_edit.is_some() {
|
||||
after_opacity = wheel_target(app, ui);
|
||||
&after_opacity
|
||||
} else {
|
||||
tgt
|
||||
};
|
||||
let color = if changed { tgt.color() } else { cx.color };
|
||||
// After a text that changed the color, a pick sets the components it moved on the color the
|
||||
// text applied; a text that left the color as it was keeps the remembered hue.
|
||||
let shown = if changed { shown_hsb(app, panel, tgt, color, cms) } else { hsb };
|
||||
let drawn = (typed.is_some() && shown != hsb).then_some(hsb);
|
||||
let any_pick = picked.marker.is_some() || picked.edits.iter().any(|e| e.events.iter().next().is_some());
|
||||
let pick = Pick { tgt, color, cms, behind, cmyk_doc, shown, drawn };
|
||||
pick.picked(app, panel, picked);
|
||||
// The slider rows show the target as the picks left it.
|
||||
let after_pick;
|
||||
let tgt = if any_pick {
|
||||
after_pick = wheel_target(app, ui);
|
||||
&after_pick
|
||||
} else {
|
||||
tgt
|
||||
};
|
||||
let color = if any_pick { tgt.color() } else { color };
|
||||
let shown = if any_pick { shown_hsb(app, panel, tgt, color, cms) } else { shown };
|
||||
let rows = Pick { tgt, color, cms, behind, cmyk_doc, shown, drawn: None };
|
||||
let cx = &rows;
|
||||
match set.sliders {
|
||||
Sliders::None => {}
|
||||
Sliders::Oklch => oklch_rows(app, panel, ui, cx),
|
||||
|
||||
@@ -277,7 +277,7 @@ fn object_menu(tree: &DocLayers, id: NodeId, ids: &[u64]) -> Vec<MenuRow<String>
|
||||
let lock_label = if lock == "layer.lockOthers" { "Lock Others" } else { "Unlock All Layers" };
|
||||
let hide_label = if hide == "layer.hideOthers" { "Hide Others" } else { "Show All Layers" };
|
||||
let export = |multiple: bool| json!({ "ids": ids, "multiple": multiple });
|
||||
vec![
|
||||
let mut rows = vec![
|
||||
entry("ui.layerOptions", json!({ "ids": ids }), options, true),
|
||||
entry("layer.duplicate", json!({ "ids": ids }), duplicate, duplicate_ok),
|
||||
entry("layer.delete", json!({ "ids": ids }), delete, delete_ok),
|
||||
@@ -291,7 +291,21 @@ fn object_menu(tree: &DocLayers, id: NodeId, ids: &[u64]) -> Vec<MenuRow<String>
|
||||
tl!("Collect for Export").to_string().into(),
|
||||
vec![entry("assets.add", export(false), "As Single Asset", true), entry("assets.add", export(true), "As Multiple Assets", true)],
|
||||
),
|
||||
]
|
||||
];
|
||||
// The commands plug-in manifests list in this menu (`menu.context`): a submenu per plug-in,
|
||||
// each entry running its command on these rows' objects.
|
||||
let plugins = crate::dialogs::plugin::context_commands(vectorcraft_plugins::ContextMenu::Layers, doc, ids);
|
||||
if !plugins.is_empty() {
|
||||
let groups = plugins
|
||||
.into_iter()
|
||||
.map(|(name, commands)| {
|
||||
let entries = commands.into_iter().map(|c| entry(c.command, json!({ "ids": ids }), c.label, c.enabled)).collect();
|
||||
MenuRow::Submenu(name.to_string().into(), entries)
|
||||
})
|
||||
.collect();
|
||||
rows.extend([separator(), MenuRow::Submenu(tl!("Plug-ins").to_string().into(), groups)]);
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Locate Object, or Locate Layer with Show Layers Only on, for row `id`.
|
||||
|
||||
@@ -253,11 +253,16 @@ pub(super) fn apply(app: &mut VectorcraftApp, events: Vec<LayersEvent<RowId>>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the commands of one event other than a toggle sweep or an open.
|
||||
/// Runs the commands of one event other than a toggle sweep or an open. A plug-in command from a
|
||||
/// row's menu asks for its parameters first, as its menu item does.
|
||||
fn run_commands(app: &mut VectorcraftApp, event: LayersEvent<RowId>) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
for (c, p) in commands(app, st, event) {
|
||||
app.run(&c, p).ok();
|
||||
if vectorcraft_engine::cmd::plugin::is_command_id(&c) {
|
||||
crate::menus::invoke(app, &c, p);
|
||||
} else {
|
||||
app.run(&c, p).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -931,6 +931,62 @@ fn full_layers_are_the_layers_with_all_their_art_selected() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A row's menu ends with a Plug-ins submenu while a plug-in lists commands in the Layers panel's
|
||||
/// context menu (`menu.context`): a submenu named after the plug-in holding those commands, each
|
||||
/// enabled while its `when` holds for the rows the menu acts on. A pick runs the command on that
|
||||
/// row's object, whatever the selection, as one undo step.
|
||||
#[test]
|
||||
fn row_menus_list_plugin_commands() {
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::layers::ui::panel::MenuTarget;
|
||||
use craft::ui::menu::MenuRow;
|
||||
use vectorcraft_plugins::wat::{Given, when_given};
|
||||
let (mut app, layer, [a, b]) = two_rects();
|
||||
let id = "test.layers.context";
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Row Tools","api":2,"version":"1","kind":"filter","commands":[
|
||||
{{"id":"one","label":"One","menu":{{"context":[{{"menu":"layers","when":"oneObject"}}]}}}},
|
||||
{{"id":"canvas","label":"Canvas","menu":{{"context":[{{"menu":"canvas"}}]}}}}]}}"#
|
||||
);
|
||||
let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#;
|
||||
let module = wat::parse_str(when_given(&manifest, Given::Input, r#""name":"Target""#, triangle)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
|
||||
app.run("layer.setProps", json!({"ids": [a.0], "name": "Target"})).unwrap();
|
||||
app.run("select.set", json!({"ids": [b.0]})).unwrap();
|
||||
// The Plug-ins submenu of the menu on `row`: (plug-in, [(label, command, params, enabled)]).
|
||||
type Entries = Vec<(String, String, serde_json::Value, bool)>;
|
||||
let plugins = |app: &VectorcraftApp, row: NodeId| -> Vec<(String, Entries)> {
|
||||
let tree = DocLayers::new(app, app.session.active().unwrap());
|
||||
let menu = controls::row_menu(&tree, &MenuTarget::new(Some(layer_key(row))));
|
||||
let groups = menu.iter().find_map(|r| match r {
|
||||
MenuRow::Submenu(label, groups) if label.as_str() == tl!("Plug-ins") => Some(groups.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let entry = |r: &MenuRow<String>| {
|
||||
let MenuRow::Entry(e) = r else { panic!("a plug-in's submenu holds entries only") };
|
||||
let c = CommandRef::parse_key(e.value().expect("an entry runs a command")).expect("a command key");
|
||||
(e.label().as_str().to_string(), c.id.to_string(), c.params.clone(), e.is_enabled())
|
||||
};
|
||||
let group = |r: &MenuRow<String>| {
|
||||
let MenuRow::Submenu(name, entries) = r else { panic!("a plug-in's group is a submenu") };
|
||||
(name.as_str().to_string(), entries.iter().map(entry).collect())
|
||||
};
|
||||
groups.unwrap_or_default().iter().map(group).collect()
|
||||
};
|
||||
let one = vectorcraft_engine::cmd::plugin::command_id(id, "one");
|
||||
assert_eq!(plugins(&app, a), vec![("Row Tools".to_string(), vec![("One".to_string(), one.clone(), json!({"ids": [a.0]}), true)])]);
|
||||
assert!(!plugins(&app, layer)[0].1[0].3, "a layer row is not one object");
|
||||
|
||||
let undo = undo_len(&app);
|
||||
feed(&mut app, vec![LayersEvent::menu(MenuTarget::new(Some(layer_key(a))), CommandRef::with_params(&one, json!({"ids": [a.0]})).key())]);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!((undo_len(&app), st.history.undo.last().map(|s| s.label.as_str())), (undo + 1, Some("One")));
|
||||
assert!(st.doc.node(a).is_none() && st.doc.node(b).is_some(), "the plug-in was given the row's object, not the selection");
|
||||
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
assert!(plugins(&app, b).is_empty(), "removed: no Plug-ins submenu");
|
||||
}
|
||||
|
||||
/// A target circle's appearance held across File › Revert and dropped on another row's circle
|
||||
/// leaves the restored objects with the same IDs as they were; a drag started after the revert
|
||||
/// still moves the appearance.
|
||||
|
||||
@@ -362,15 +362,19 @@ impl<'a> View<'a> {
|
||||
|
||||
fn contents(&self, ui: &mut Ui, cx: &mut BodyCx<'_>, closed: &mut HashSet<(String, String)>, acts: &RefCell<Vec<Act>>) {
|
||||
if self.empty {
|
||||
Notice::new(Tone::Neutral, tl!("Drag art or swatches here, or use + to add the selection's colors and text styles."))
|
||||
.title(tl!("This library is empty"))
|
||||
.layout(NoticeLayout::Centred)
|
||||
.show(ui);
|
||||
super::notice_frame(ui, |ui| {
|
||||
Notice::new(Tone::Neutral, tl!("Drag art or swatches here, or use + to add the selection's colors and text styles."))
|
||||
.title(tl!("This library is empty"))
|
||||
.layout(NoticeLayout::Centred)
|
||||
.show(ui);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if self.searching && self.counts.iter().all(|n| *n == 0) {
|
||||
let message = crate::i18n::fmt(tl!("No items in this library match “{query}”."), &[("query", &self.query)]);
|
||||
Notice::new(Tone::Neutral, message).title(tl!("No results")).layout(NoticeLayout::Centred).show(ui);
|
||||
super::notice_frame(ui, |ui| {
|
||||
Notice::new(Tone::Neutral, message.clone()).title(tl!("No results")).layout(NoticeLayout::Centred).show(ui);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if !self.kinds(ui, cx, None, acts) && self.dragging_grouped(ui) {
|
||||
@@ -809,19 +813,22 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
/// The panel with no library: what libraries are, and Create New Library. → whether it was pressed.
|
||||
fn no_library(ui: &mut Ui) -> bool {
|
||||
let shown = Panel::new(tl!("Libraries")).show(ui, |ui, _| {
|
||||
Notice::new(
|
||||
Tone::Neutral,
|
||||
tl!(
|
||||
"Keep graphics, colors and text styles here to use them in any document. Libraries are stored on this machine — no account required."
|
||||
),
|
||||
)
|
||||
.title(tl!("Local Libraries"))
|
||||
.icon(NoticeIcon::Custom(IconSpec::svg(IconId::new("library"))))
|
||||
.layout(NoticeLayout::Centred)
|
||||
.action(NoticeAction::new(tl!("Create New Library")))
|
||||
.show(ui)
|
||||
.action
|
||||
.is_some()
|
||||
super::notice_frame(ui, |ui| {
|
||||
Notice::new(
|
||||
Tone::Neutral,
|
||||
tl!(
|
||||
"Keep graphics, colors and text styles here to use them in any document. Libraries are stored on this machine — no account required."
|
||||
),
|
||||
)
|
||||
.title(tl!("Local Libraries"))
|
||||
.icon(NoticeIcon::Custom(IconSpec::svg(IconId::new("library"))))
|
||||
.layout(NoticeLayout::Centred)
|
||||
.action(NoticeAction::new(tl!("Create New Library")))
|
||||
.show(ui)
|
||||
.action
|
||||
.is_some()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
});
|
||||
shown.inner.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -44,9 +44,12 @@ pub(crate) struct QuickAction {
|
||||
/// The panel for what is selected: the selection's kind as its heading, then its sections (Edit
|
||||
/// Artboards' with the Artboard tool, the document's with nothing selected).
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let inspector = Inspector::new(tl!("Properties")).title_strength(HeaderStrength::Quiet).empty(tl!("No document open"));
|
||||
let inspector = Inspector::new(tl!("Properties")).title_strength(HeaderStrength::Quiet);
|
||||
let Some(key) = target_key(app) else {
|
||||
inspector.show(ui, |_, _| {});
|
||||
// The panel's own empty state, inside the roomy pad: the inspector's notice has no pad of its own.
|
||||
inspector.target("no-document").show(ui, |ui, _| {
|
||||
super::empty_state(ui, "settings", tl!("No document open"), tl!("Open a document to see its properties."));
|
||||
});
|
||||
return;
|
||||
};
|
||||
let n_sel = app.session.active().map_or(0, |st| st.selection.len());
|
||||
|
||||
@@ -5,10 +5,10 @@ use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::buttons::{Button, IconButton};
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, clicked};
|
||||
use craft::ui::contract::{Bind, Gap, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, clicked};
|
||||
use craft::ui::display::{Elide, Shade, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::menu::Menu;
|
||||
use craft::ui::popover::Popover;
|
||||
use craft::ui::style::TypeRole;
|
||||
@@ -194,27 +194,40 @@ pub(crate) fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let caption = |ui: &mut Ui, text: &'static str| {
|
||||
Text::new(text).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
};
|
||||
caption(ui, tl!("Match"));
|
||||
if let Some(on) = option_check(ui, tl!("Appearance"), o.appearance) {
|
||||
set(app, json!({ "appearance": on }));
|
||||
let results = global_edit_results(global_edit_count(app));
|
||||
// Each group is its caption over its options a row gap apart; the groups and the Results line are a stack gap
|
||||
// apart. A click is kept and run after the stack returns.
|
||||
let mut changes = Vec::new();
|
||||
Stack::new().gap(Gap::Stack).show(ui, |ui, _| {
|
||||
FieldGroup::new(tl!("Match")).show(ui, |ui, _| {
|
||||
caption(ui, tl!("Match"));
|
||||
if let Some(on) = option_check(ui, tl!("Appearance"), o.appearance) {
|
||||
changes.push(json!({ "appearance": on }));
|
||||
}
|
||||
if let Some(on) = option_check(ui, tl!("Size"), o.size) {
|
||||
changes.push(json!({ "size": on }));
|
||||
}
|
||||
});
|
||||
FieldGroup::new(tl!("On Artboards")).show(ui, |ui, _| {
|
||||
caption(ui, tl!("On Artboards"));
|
||||
if let Some(all) = option_check(ui, tl!("All Artboards"), o.artboards.is_none()) {
|
||||
changes.push(json!({ "artboards": if all { "all" } else { "1" } }));
|
||||
}
|
||||
if let Some(range) = &o.artboards {
|
||||
let typed = Field::new(tl!("Range:")).show(ui, |ui, _| TextField::new(tl!("Range:"), Bind::given(range.clone())).show(ui)).inner;
|
||||
if let Some(range) = typed.and_then(|t| t.events.committed().cloned()) {
|
||||
changes.push(json!({ "artboards": range }));
|
||||
}
|
||||
}
|
||||
if let Some(on) = option_check(ui, tl!("Include Objects On Canvas"), o.include_canvas) {
|
||||
changes.push(json!({ "includeCanvas": on }));
|
||||
}
|
||||
});
|
||||
Text::new(results.clone()).shade(Shade::Muted).show(ui);
|
||||
});
|
||||
for p in changes {
|
||||
set(app, p);
|
||||
}
|
||||
if let Some(on) = option_check(ui, tl!("Size"), o.size) {
|
||||
set(app, json!({ "size": on }));
|
||||
}
|
||||
caption(ui, tl!("On Artboards"));
|
||||
if let Some(all) = option_check(ui, tl!("All Artboards"), o.artboards.is_none()) {
|
||||
set(app, json!({ "artboards": if all { "all" } else { "1" } }));
|
||||
}
|
||||
if let Some(range) = &o.artboards {
|
||||
let typed = Field::new(tl!("Range:")).show(ui, |ui, _| TextField::new(tl!("Range:"), Bind::given(range.clone())).show(ui)).inner;
|
||||
if let Some(range) = typed.and_then(|t| t.events.committed().cloned()) {
|
||||
set(app, json!({ "artboards": range }));
|
||||
}
|
||||
}
|
||||
if let Some(on) = option_check(ui, tl!("Include Objects On Canvas"), o.include_canvas) {
|
||||
set(app, json!({ "includeCanvas": on }));
|
||||
}
|
||||
Text::new(global_edit_results(global_edit_count(app))).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
|
||||
/// The options' line with how many objects Start Global Edit would take, in the interface language.
|
||||
|
||||
@@ -181,6 +181,34 @@ fn global_edit_starting_closes_the_quick_action_options() {
|
||||
assert!(!panel.app().ui.properties_panel.global_edit_open && !panel.shows(&results), "the options stay closed once Global Edit stops");
|
||||
}
|
||||
|
||||
/// The Global Edit Options are two groups, Match and On Artboards, and the Results line: the On Artboards caption is a
|
||||
/// stack gap below the Size option, and the Results line a stack gap below Include Objects On Canvas.
|
||||
#[test]
|
||||
fn global_edit_options_groups_are_a_stack_gap_apart() {
|
||||
use craft::ui::contract::Role;
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let stack = std::rc::Rc::new(std::cell::Cell::new(0.0));
|
||||
let seen = std::rc::Rc::clone(&stack);
|
||||
craft::ui::testing::Fixture::new(move |ui| seen.set(craft::ui::runtime::env::Env::of(ui).tokens.space.gap.stack)).frame(vec![]);
|
||||
let stack = stack.get();
|
||||
assert!(stack > 0.0, "the interface resolved its stack gap");
|
||||
let mut app = new_app();
|
||||
let a = rect(&mut app, 20.0, 20.0, 40.0, 40.0);
|
||||
rect(&mut app, 200.0, 20.0, 40.0, 40.0);
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut panel = Panel::new(app, super::appearance_section::global_edit_row);
|
||||
panel.click("Global Edit Options");
|
||||
let results = global_edit_results(2);
|
||||
assert!(panel.shows(&results), "the options open");
|
||||
let size = panel.rect_role("Size", Role::CHECK_BOX);
|
||||
let caption = panel.rect_role("On Artboards", Role::LABEL);
|
||||
let canvas = panel.rect_role("Include Objects On Canvas", Role::CHECK_BOX);
|
||||
let line = panel.rect(&results);
|
||||
let (above, below) = (caption.top() - size.bottom(), line.top() - canvas.bottom());
|
||||
assert!(above >= stack - 0.5, "On Artboards is {above} below Size, under the stack gap {stack}");
|
||||
assert!(below >= stack - 0.5, "Results is {below} below the last option, under the stack gap {stack}");
|
||||
}
|
||||
|
||||
/// The options' Results count is found once per document revision, options and selected
|
||||
/// object, not every frame; another selected object or other options find it again.
|
||||
#[test]
|
||||
|
||||
@@ -83,7 +83,7 @@ fn a_drag_in_the_field_is_one_undo_step_and_the_strip_sets_the_channel() {
|
||||
fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let others = json!({
|
||||
"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false, "contrast": false,
|
||||
"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false, "hexField": false, "contrast": false,
|
||||
"contrastFor": "normalText", "contrastBackground": null, "vision": false, "documentColors": false
|
||||
});
|
||||
let with = |v: serde_json::Value| {
|
||||
@@ -137,12 +137,12 @@ fn ui_color_wheel_rejects_other_params() {
|
||||
let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err();
|
||||
assert_eq!(
|
||||
e,
|
||||
"unknown parameter `veiw`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors"
|
||||
"unknown parameter `veiw`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors"
|
||||
);
|
||||
let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err();
|
||||
assert_eq!(
|
||||
e,
|
||||
"unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors"
|
||||
"unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors"
|
||||
);
|
||||
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing");
|
||||
}
|
||||
|
||||
@@ -87,8 +87,8 @@ fn ui_color_wheel_sets_gamut() {
|
||||
let with = |v: serde_json::Value| {
|
||||
let mut v = v;
|
||||
let rest = json!({
|
||||
"sliders": "none", "harmony": false, "harmonyRule": "complementary", "opacity": false, "contrast": false, "contrastFor": "normalText",
|
||||
"contrastBackground": null, "vision": false, "documentColors": false
|
||||
"sliders": "none", "harmony": false, "harmonyRule": "complementary", "opacity": false, "hexField": false, "contrast": false,
|
||||
"contrastFor": "normalText", "contrastBackground": null, "vision": false, "documentColors": false
|
||||
});
|
||||
v.as_object_mut().unwrap().extend(rest.as_object().unwrap().clone());
|
||||
v
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
//! The Color Wheel panel's Show Hex Field drawn headless through the `Fixture`: the setting and
|
||||
//! `ui.colorWheel`, hex with an alpha and CSS colors typed into the field, the opacity they set,
|
||||
//! nothing selected, a selection mixing type and other art, gradient stops and freeform points,
|
||||
//! and refused text.
|
||||
|
||||
use craft::ui::runtime::access::Role;
|
||||
use craft::ui::testing::Target;
|
||||
use egui::{Key, Modifiers, Pos2, vec2};
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::color_wheel::hex_text;
|
||||
use super::tests_color_wheel::Panel;
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
const FIELD: &str = "Hex or CSS color";
|
||||
|
||||
/// An app with a selected red rectangle and Show Hex Field checked.
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
|
||||
app.run("ui.colorWheel", json!({"hexField": true})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// The panel of `app`, with room for every row.
|
||||
fn panel(app: VectorcraftApp) -> Panel {
|
||||
let mut p = Panel::new(app);
|
||||
p.fx.room(vec2(260.0, 480.0)).settle();
|
||||
p
|
||||
}
|
||||
|
||||
fn field(p: &Panel) -> Option<Target> {
|
||||
p.fx.by_label(FIELD)
|
||||
}
|
||||
|
||||
/// Selects the field's text and types `text` over it, without committing it.
|
||||
fn type_pending(p: &mut Panel, text: &str) {
|
||||
let t = field(p).expect("the hex field");
|
||||
p.fx.click(&t).key(Key::A, Modifiers::COMMAND).type_text(text);
|
||||
}
|
||||
|
||||
/// Types `text` over the field's text and presses Enter.
|
||||
fn type_in(p: &mut Panel, text: &str) {
|
||||
type_pending(p, text);
|
||||
p.fx.key(Key::Enter, Modifiers::NONE).settle();
|
||||
}
|
||||
|
||||
fn shown(p: &Panel) -> String {
|
||||
p.value(FIELD).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn rgb8(c: &Color) -> [u8; 3] {
|
||||
let Color::Rgb { r, g, b } = *c else { panic!("an RGB color: {c:?}") };
|
||||
[r, g, b].map(|v| (v * 255.0).round() as u8)
|
||||
}
|
||||
|
||||
fn fill_color(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> Color {
|
||||
app.session.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color().expect("a solid fill")
|
||||
}
|
||||
|
||||
fn selected(app: &VectorcraftApp) -> Vec<vectorcraft_doc::NodeId> {
|
||||
app.session.doc().unwrap().selection.objects.clone()
|
||||
}
|
||||
|
||||
fn undo_count(app: &VectorcraftApp) -> usize {
|
||||
app.session.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The hex value and opacity of the fill's first gradient stop.
|
||||
fn first_stop(p: &Panel) -> (String, f32) {
|
||||
let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") };
|
||||
let s = &g.gradient.stops[0];
|
||||
(s.color.to_hex(), s.opacity)
|
||||
}
|
||||
|
||||
/// The Opacity row's slider.
|
||||
fn opacity_slider(p: &Panel) -> Target {
|
||||
p.fx.by_role(Role::SLIDER).into_iter().find(|t| p.fx.tree().name_of(t.node) == Some("Opacity")).expect("the Opacity slider")
|
||||
}
|
||||
|
||||
/// A click at `pos` whose press and release come in one frame.
|
||||
fn quick_click(p: &mut Panel, pos: Pos2) {
|
||||
p.fx.frame(vec![egui::Event::PointerMoved(pos)]);
|
||||
let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
p.fx.frame(vec![button(true), button(false)]).idle(2);
|
||||
}
|
||||
|
||||
/// The point near the top right corner of the saturation and brightness square.
|
||||
fn square_top_right(p: &Panel) -> Pos2 {
|
||||
p.node("Saturation and brightness").rect.right_top() + vec2(-1.0, 1.0)
|
||||
}
|
||||
|
||||
/// The panel menu's Show Hex Field and `ui.colorWheel {hexField}` check and uncheck the field; a bad
|
||||
/// value is an error and changes nothing.
|
||||
#[test]
|
||||
fn show_hex_field_is_a_setting_of_the_panel() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["hexField"], json!(false));
|
||||
assert_eq!(app.run("ui.colorWheel", json!({"hexField": true})).unwrap()["hexField"], json!(true));
|
||||
let e = app.run("ui.colorWheel", json!({"hexField": "yes"})).unwrap_err();
|
||||
assert_eq!(e, "`hexField` must be true or false");
|
||||
assert!(app.ui.color_wheel.hex_field, "an error changes nothing");
|
||||
assert_eq!(app.run("ui.colorWheel", json!({"hexField": null})).unwrap()["hexField"], json!(true), "null keeps it");
|
||||
assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["hexField"], json!(true));
|
||||
assert_eq!(super::color_wheel::run(&mut app, "ui.colorWheel.hexField", &json!({})).unwrap().unwrap()["hexField"], json!(false));
|
||||
let saved: super::color_wheel::Settings = serde_json::from_value(json!({"hexField": true, "view": "box"})).unwrap();
|
||||
assert!(saved.hex_field);
|
||||
let odd: super::color_wheel::Settings = serde_json::from_value(json!({"hexField": "on"})).unwrap();
|
||||
assert!(!odd.hex_field, "a saved value this build does not know reads as off");
|
||||
let p = panel({
|
||||
let mut app = self::app();
|
||||
app.run("ui.colorWheel", json!({"hexField": false})).unwrap();
|
||||
app
|
||||
});
|
||||
assert!(field(&p).is_none(), "no field while unchecked");
|
||||
}
|
||||
|
||||
/// An explicit null for any `ui.colorWheel` key keeps that key's value, as leaving the key out does,
|
||||
/// and the other keys of the same call still apply.
|
||||
#[test]
|
||||
fn ui_color_wheel_keeps_a_key_given_as_null() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let set = json!({
|
||||
"view": "box", "channel": "red", "opacity": true, "hexField": true, "sliders": "oklch",
|
||||
"gamut": true, "harmony": true, "harmonyRule": "triad", "vision": true, "documentColors": true
|
||||
});
|
||||
let all = app.run("ui.colorWheel", set.clone()).unwrap();
|
||||
assert_eq!(all, set);
|
||||
for key in ["view", "channel", "opacity", "hexField", "sliders", "gamut", "harmony", "harmonyRule", "vision", "documentColors"] {
|
||||
assert_eq!(app.run("ui.colorWheel", json!({ key: null })).unwrap(), all, "{key}: null");
|
||||
}
|
||||
let got = app.run("ui.colorWheel", json!({"view": null, "channel": "blue", "opacity": null, "hexField": false})).unwrap();
|
||||
assert_eq!(
|
||||
got,
|
||||
json!({
|
||||
"view": "box", "channel": "blue", "opacity": true, "hexField": false, "sliders": "oklch",
|
||||
"gamut": true, "harmony": true, "harmonyRule": "triad", "vision": true, "documentColors": true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// The field shows six digits, and two more when the opacity rounds to less than `ff`.
|
||||
#[test]
|
||||
fn the_field_shows_the_alpha_only_under_full_opacity() {
|
||||
let p = panel(app());
|
||||
assert_eq!(shown(&p), "FF0000");
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"opacity": 50})).unwrap();
|
||||
let p = panel(app);
|
||||
assert_eq!(shown(&p), "FF000080");
|
||||
assert_eq!(hex_text(None, Some(0.5)), "");
|
||||
assert_eq!(hex_text(Some(&Color::rgb8(0x33, 0x66, 0x99)), Some(0.999)), "336699", "an opacity that rounds to ff shows no alpha");
|
||||
assert_eq!(hex_text(Some(&Color::rgb8(0x33, 0x66, 0x99)), None), "336699");
|
||||
}
|
||||
|
||||
/// With Show Opacity on, typing `#33669980` sets the fill to #336699 at 50.2 % (128 of 255) in one
|
||||
/// undo step.
|
||||
#[test]
|
||||
fn typing_hex_with_an_alpha_sets_the_color_and_the_opacity() {
|
||||
let mut app = app();
|
||||
app.run("ui.colorWheel", json!({"opacity": true})).unwrap();
|
||||
let id = selected(&app)[0];
|
||||
let before = undo_count(&app);
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "#33669980");
|
||||
assert_eq!(rgb8(&fill_color(&p.app(), id)), [0x33, 0x66, 0x99]);
|
||||
let o = p.app().session.proxy_opacity(false).unwrap();
|
||||
assert!((o - 0.502).abs() < 1e-4, "{o}");
|
||||
assert_eq!(undo_count(&p.app()), before + 1, "one undo step");
|
||||
p.app_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(rgb8(&fill_color(&p.app(), id)), [255, 0, 0]);
|
||||
assert_eq!(p.app().session.proxy_opacity(false), Some(1.0));
|
||||
}
|
||||
|
||||
/// A typed color keeps the model of the color it replaces, as a pick on the wheel does: a CMYK fill
|
||||
/// stays CMYK, converted through the color settings.
|
||||
#[test]
|
||||
fn a_typed_color_keeps_a_cmyk_fill_cmyk() {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"color": {"c": 0, "m": 100, "y": 100, "k": 0}})).unwrap();
|
||||
let id = selected(&app)[0];
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "#336699");
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let want = cms.to_cmyk(&Color::rgb8(0x33, 0x66, 0x99), cms.settings().intent);
|
||||
let got = fill_color(&p.app(), id);
|
||||
let Color::Cmyk { c, m, y, k } = got else { panic!("a CMYK color: {got:?}") };
|
||||
assert_eq!([c, m, y, k], want);
|
||||
}
|
||||
|
||||
/// The alpha sets the opacity while the opacity row is hidden too, and text without an alpha keeps
|
||||
/// the opacity.
|
||||
#[test]
|
||||
fn the_alpha_applies_without_the_opacity_row_and_no_alpha_keeps_the_opacity() {
|
||||
let app = app();
|
||||
let id = selected(&app)[0];
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "rgb(51 102 153 / 25%)");
|
||||
assert_eq!(rgb8(&fill_color(&p.app(), id)), [51, 102, 153]);
|
||||
assert_eq!(p.app().session.proxy_opacity(false), Some(0.25));
|
||||
type_in(&mut p, "hsl(0 100% 50%)");
|
||||
assert_eq!(rgb8(&fill_color(&p.app(), id)), [255, 0, 0]);
|
||||
assert_eq!(p.app().session.proxy_opacity(false), Some(0.25), "no alpha in the text: the opacity stays");
|
||||
type_in(&mut p, "oklch(62.8% 0.2577 29.23 / 1)");
|
||||
assert_eq!(p.app().session.proxy_opacity(false), Some(1.0));
|
||||
}
|
||||
|
||||
/// With nothing selected, `#33669980` sets the default fill to #336699 and changes no opacity.
|
||||
#[test]
|
||||
fn with_nothing_selected_the_color_goes_to_the_defaults_without_the_alpha() {
|
||||
let mut app = app();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let doc = app.session.doc().unwrap().doc.clone();
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "#33669980");
|
||||
assert_eq!(p.app().session.paint.fill.color().map(|c| rgb8(&c)), Some([0x33, 0x66, 0x99]));
|
||||
assert_eq!(*p.app().session.doc().unwrap().doc, *doc, "no object changed");
|
||||
}
|
||||
|
||||
/// With a rectangle and a type object with no fill item selected, `#33669980` sets both fills to
|
||||
/// #336699 and the rectangle's fill opacity to 50.2 %.
|
||||
#[test]
|
||||
fn a_selection_mixing_type_and_art_takes_the_color_and_the_alpha_where_it_can() {
|
||||
let mut app = app();
|
||||
let rect = selected(&app)[0];
|
||||
let text = app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [rect.0, text]})).unwrap();
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "#33669980");
|
||||
{
|
||||
let app = p.app();
|
||||
assert_eq!(rgb8(&fill_color(&app, rect)), [0x33, 0x66, 0x99]);
|
||||
let fill = app.session.doc().unwrap().doc.node(rect).unwrap().appearance.fill_at(None).map(|f| f.opacity);
|
||||
assert!(fill.is_some_and(|o| (o - 0.502).abs() < 1e-4), "{fill:?}");
|
||||
let text_node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(text)).unwrap().appearance.clone();
|
||||
assert!(text_node.fill_at(None).is_none(), "the type object takes no fill item, so no alpha: {text_node:?}");
|
||||
}
|
||||
p.app_mut().run("select.set", json!({"ids": [text]})).unwrap();
|
||||
let (fill, _) = p.app().session.proxy_paints();
|
||||
assert_eq!(fill.color().map(|c| c.to_hex()), Some("#336699".into()), "the type's characters take the color: {fill:?}");
|
||||
}
|
||||
|
||||
/// With only a type object selected, where the opacity row is gray, `#33669980` sets the
|
||||
/// characters' color and adds no fill item for the alpha.
|
||||
#[test]
|
||||
fn with_only_type_selected_the_color_applies_without_the_alpha() {
|
||||
let mut app = app();
|
||||
let text = app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [text]})).unwrap();
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "#33669980");
|
||||
let (fill, _) = p.app().session.proxy_paints();
|
||||
assert_eq!(fill.color().map(|c| c.to_hex()), Some("#336699".into()), "the characters take the color: {fill:?}");
|
||||
let node = p.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(text)).unwrap().appearance.clone();
|
||||
assert!(node.fill_at(None).is_none(), "no fill item for the alpha: {node:?}");
|
||||
}
|
||||
|
||||
/// Retyping the color and opacity the selection has, in another form, records no undo step; an
|
||||
/// alpha that differs from the opacity by less than the field shows is still applied.
|
||||
#[test]
|
||||
fn retyping_the_shown_color_in_another_form_changes_nothing() {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"opacity": 50})).unwrap();
|
||||
let before = undo_count(&app);
|
||||
let mut p = panel(app);
|
||||
for same in ["rgb(255 0 0 / 50%)", "rgb(100% 0% 0% / 0.5)", "#f00", "hsl(0 100% 50%)"] {
|
||||
type_in(&mut p, same);
|
||||
assert_eq!(undo_count(&p.app()), before, "{same}");
|
||||
assert!(p.app().ui.status.is_empty(), "{same}: {}", p.app().ui.status);
|
||||
}
|
||||
let text = shown(&p);
|
||||
assert_eq!(text, "FF000080");
|
||||
type_in(&mut p, &text);
|
||||
assert_eq!(undo_count(&p.app()), before, "the shown text");
|
||||
assert_eq!(p.app().session.proxy_opacity(false), Some(0.5), "the shown alpha keeps 50 %");
|
||||
type_in(&mut p, "rgb(255 0 0 / 50.4%)");
|
||||
assert_eq!(undo_count(&p.app()), before + 1, "an alpha with the same two digits is applied");
|
||||
assert!(p.app().session.proxy_opacity(false).is_some_and(|o| (o - 0.504).abs() < 1e-4));
|
||||
let before = undo_count(&p.app());
|
||||
type_in(&mut p, "#00ff00");
|
||||
assert_eq!(undo_count(&p.app()), before + 1, "another color is applied");
|
||||
p.run("paint.setFill", json!({"opacity": 99.9}));
|
||||
assert_eq!(shown(&p), "00FF00", "99.9 % shows no alpha");
|
||||
let before = undo_count(&p.app());
|
||||
type_in(&mut p, "#00ff00ff");
|
||||
assert_eq!(undo_count(&p.app()), before + 1, "the alpha ff sets 100 %");
|
||||
assert_eq!(p.app().session.proxy_opacity(false), Some(1.0));
|
||||
}
|
||||
|
||||
/// Retyping the shown text with two objects selected gives the second the first one's opacity, the
|
||||
/// one the field shows, and leaves the first's as it was.
|
||||
#[test]
|
||||
fn retyping_the_shown_alpha_gives_the_selection_the_shown_opacity() {
|
||||
let mut app = app();
|
||||
let first = selected(&app)[0];
|
||||
app.run("paint.setFill", json!({"opacity": 50})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
let second = selected(&app)[0];
|
||||
app.run("paint.setFill", json!({"color": "#ff0000", "opacity": 80})).unwrap();
|
||||
app.run("select.set", json!({"ids": [first, second]})).unwrap();
|
||||
let mut p = panel(app);
|
||||
let text = shown(&p);
|
||||
assert_eq!(text, "FF000080");
|
||||
type_in(&mut p, &text);
|
||||
let opacity = |id| p.app().session.doc().unwrap().doc.node(id).unwrap().appearance.fill_at(None).map(|f| f.opacity);
|
||||
assert_eq!(opacity(first), Some(0.5), "the first keeps 50 %");
|
||||
assert_eq!(opacity(second), Some(0.5), "the second takes 50 %");
|
||||
}
|
||||
|
||||
/// Retyping a gradient stop's or a freeform point's color, with or without its alpha, records no
|
||||
/// step.
|
||||
#[test]
|
||||
fn retyping_a_stop_color_changes_nothing() {
|
||||
for gradient in [json!({}), json!({"kind": "freeform"})] {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({ "gradient": gradient })).unwrap();
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "#33669980");
|
||||
let before = undo_count(&p.app());
|
||||
type_in(&mut p, "#33669980");
|
||||
type_in(&mut p, "#369");
|
||||
assert_eq!(undo_count(&p.app()), before, "{gradient}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Retyping the color of a global swatch's tint unlinks the fill from the swatch in one step.
|
||||
#[test]
|
||||
fn retyping_a_tint_color_unlinks_the_swatch() {
|
||||
let mut app = app();
|
||||
app.run("swatch.new", json!({"name": "Ink", "color": "#ff0000", "spot": true})).unwrap();
|
||||
app.run("paint.setFill", json!({"swatch": "Ink", "tint": 100})).unwrap();
|
||||
let before = undo_count(&app);
|
||||
let mut p = panel(app);
|
||||
assert_eq!(shown(&p), "FF0000");
|
||||
type_in(&mut p, "#ff0000");
|
||||
assert_eq!(undo_count(&p.app()), before + 1);
|
||||
let Paint::Solid { swatch, .. } = crate::panels::current_paints(&p.app()).0 else { panic!("a solid fill") };
|
||||
assert_eq!(swatch, None);
|
||||
}
|
||||
|
||||
/// A click on the square that takes the focus from an edited field applies the text, then the
|
||||
/// click's pick to the target the text left: a gradient stop keeps the typed alpha.
|
||||
#[test]
|
||||
fn a_wheel_click_after_typing_applies_both() {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
|
||||
let before = undo_count(&app);
|
||||
let mut p = panel(app);
|
||||
type_pending(&mut p, "#33669980");
|
||||
let at = square_top_right(&p);
|
||||
p.fx.click_at(at).idle(2);
|
||||
let (hex, opacity) = first_stop(&p);
|
||||
assert!((opacity - 0.502).abs() < 1e-4, "the typed alpha stays: {opacity}");
|
||||
assert_ne!(hex, "#336699", "the click picked a color");
|
||||
let ch = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap();
|
||||
assert!(ch(5) >= ch(3) && ch(3) >= ch(1), "the pick keeps the typed hue: {hex}");
|
||||
assert_eq!(undo_count(&p.app()), before + 2);
|
||||
}
|
||||
|
||||
/// A click on the square in one frame that takes the focus from an edited field applies the text,
|
||||
/// then the click's saturation and brightness at the hue the text gave: a gradient stop keeps the
|
||||
/// typed alpha.
|
||||
#[test]
|
||||
fn a_wheel_click_in_one_frame_after_typing_applies_both() {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
|
||||
let before = undo_count(&app);
|
||||
let mut p = panel(app);
|
||||
type_pending(&mut p, "#33669980");
|
||||
let at = square_top_right(&p);
|
||||
quick_click(&mut p, at);
|
||||
let (hex, opacity) = first_stop(&p);
|
||||
assert!((opacity - 0.502).abs() < 1e-4, "the typed alpha stays: {opacity}");
|
||||
assert_ne!(hex, "#336699", "the click picked a color");
|
||||
let ch = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap();
|
||||
assert!(ch(5) > 0xf0 && ch(1) < 0x10 && ch(3) > 0x60 && ch(3) < 0xa0, "the pick keeps the typed hue: {hex}");
|
||||
assert_eq!(undo_count(&p.app()), before + 2);
|
||||
}
|
||||
|
||||
/// A lightness typed in the OKLCH L field and committed by a click on the C row in one frame keeps
|
||||
/// both edits: the color takes the typed L and the clicked C, and the hue stays.
|
||||
#[test]
|
||||
fn a_typed_lightness_committed_by_a_click_on_chroma_keeps_both() {
|
||||
let mut app = app();
|
||||
app.run("ui.colorWheel", json!({"hexField": false, "sliders": "oklch"})).unwrap();
|
||||
let mut p = panel(app);
|
||||
let named = |p: &Panel, role: Role, name: &str| p.fx.by_role(role).into_iter().find(|t| p.fx.tree().name_of(t.node) == Some(name));
|
||||
let oklch = |p: &Panel| {
|
||||
let id = selected(&p.app())[0];
|
||||
let Color::Rgb { r, g, b } = fill_color(&p.app(), id) else { panic!("an RGB fill") };
|
||||
vectorcraft_color::oklab::to_oklch([r, g, b])
|
||||
};
|
||||
let h0 = oklch(&p)[2];
|
||||
let field = named(&p, Role::SPIN_BUTTON, "Lightness").or_else(|| named(&p, Role::TEXT_INPUT, "Lightness")).expect("the L field");
|
||||
p.fx.click(&field).key(Key::A, Modifiers::COMMAND).type_text("50");
|
||||
let rail = named(&p, Role::SLIDER, "Chroma").expect("the C slider").rect;
|
||||
quick_click(&mut p, egui::pos2(rail.left() + 0.2 * rail.width(), rail.center().y));
|
||||
let [l, c, h] = oklch(&p);
|
||||
assert!((l - 0.5).abs() < 0.01, "the typed lightness stays: {l}");
|
||||
assert!((c - 0.08).abs() < 0.015, "the click sets the chroma: {c}");
|
||||
assert!((h - h0).abs() < 1.0, "the hue stays: {h0} → {h}");
|
||||
}
|
||||
|
||||
/// A text that leaves a white as it was, committed by a click on the square in one frame, keeps the
|
||||
/// hue the white was picked from: the click's saturation brings that hue back.
|
||||
#[test]
|
||||
fn a_click_that_commits_the_same_white_keeps_the_remembered_hue() {
|
||||
let mut app = app();
|
||||
let rect = selected(&app)[0];
|
||||
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
|
||||
let mut p = panel(app);
|
||||
let corner = p.node("Saturation and brightness").rect.left_top();
|
||||
quick_click(&mut p, corner);
|
||||
assert_eq!(rgb8(&fill_color(&p.app(), rect)), [255, 255, 255], "the square picks white");
|
||||
type_pending(&mut p, "#ffffff");
|
||||
let at = square_top_right(&p);
|
||||
quick_click(&mut p, at);
|
||||
let [r, g, b] = rgb8(&fill_color(&p.app(), rect));
|
||||
assert!(g > 0xf0 && r < 0x10 && b < 0x10, "the green comes back: {r:02x}{g:02x}{b:02x}");
|
||||
}
|
||||
|
||||
/// A press on the opacity slider in one frame that takes the focus from a field holding hex with an
|
||||
/// alpha applies the typed color and keeps the opacity the press set, not the typed alpha.
|
||||
#[test]
|
||||
fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
|
||||
app.run("ui.colorWheel", json!({"opacity": true})).unwrap();
|
||||
let mut p = panel(app);
|
||||
type_pending(&mut p, "#33669900");
|
||||
let rail = opacity_slider(&p);
|
||||
quick_click(&mut p, rail.rect.center());
|
||||
let (hex, opacity) = first_stop(&p);
|
||||
assert_eq!(hex, "#336699", "the text applies");
|
||||
assert!(opacity > 0.2 && opacity < 0.8, "the press sets the opacity: {opacity}");
|
||||
}
|
||||
|
||||
/// A press on the opacity slider that takes the focus from an edited field applies the text and
|
||||
/// keeps the opacity the press set: a gradient stop takes both.
|
||||
#[test]
|
||||
fn an_opacity_press_after_typing_keeps_both() {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
|
||||
app.run("ui.colorWheel", json!({"opacity": true})).unwrap();
|
||||
let mut p = panel(app);
|
||||
type_pending(&mut p, "#336699");
|
||||
let rail = opacity_slider(&p);
|
||||
p.fx.click_at(rail.rect.left_center() + vec2(rail.rect.width() * 0.25, 0.0)).idle(2);
|
||||
let (hex, opacity) = first_stop(&p);
|
||||
assert_eq!(hex, "#336699", "the text applies");
|
||||
assert!(opacity < 0.9, "the press sets the opacity: {opacity}");
|
||||
}
|
||||
|
||||
/// The same for a solid fill: the rectangle takes the typed color and the opacity the press set.
|
||||
#[test]
|
||||
fn an_opacity_press_after_typing_keeps_both_on_a_solid_fill() {
|
||||
let mut app = app();
|
||||
let rect = selected(&app)[0];
|
||||
app.run("ui.colorWheel", json!({"opacity": true})).unwrap();
|
||||
let mut p = panel(app);
|
||||
type_pending(&mut p, "#336699");
|
||||
let rail = opacity_slider(&p);
|
||||
p.fx.click_at(rail.rect.left_center() + vec2(rail.rect.width() * 0.25, 0.0)).idle(2);
|
||||
assert_eq!(rgb8(&fill_color(&p.app(), rect)), [0x33, 0x66, 0x99], "the text applies");
|
||||
let fill = p.app().session.proxy_opacity(false);
|
||||
assert!(fill.is_some_and(|o| o < 0.9), "the press sets the opacity: {fill:?}");
|
||||
}
|
||||
|
||||
/// A text typed for one rectangle is dropped when the selection changes to another showing the same
|
||||
/// hex: Enter then changes neither of them.
|
||||
#[test]
|
||||
fn a_text_typed_for_one_object_does_not_go_to_another_with_the_same_hex() {
|
||||
let mut app = app();
|
||||
let a = selected(&app)[0];
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
|
||||
let b = selected(&app)[0];
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let before = undo_count(&app);
|
||||
let mut p = panel(app);
|
||||
type_pending(&mut p, "#33669980");
|
||||
p.run("select.set", json!({"ids": [b]}));
|
||||
p.fx.key(Key::Enter, Modifiers::NONE).settle();
|
||||
for id in [a, b] {
|
||||
assert_eq!(rgb8(&fill_color(&p.app(), id)), [255, 0, 0]);
|
||||
}
|
||||
assert_eq!(p.app().session.proxy_opacity(false), Some(1.0));
|
||||
assert_eq!(undo_count(&p.app()), before, "nothing was applied");
|
||||
}
|
||||
|
||||
/// A text typed for one object of a dynamic symbol instance is dropped when another object of the
|
||||
/// same instance showing the same hex is selected: Enter then changes neither of them.
|
||||
#[test]
|
||||
fn a_text_typed_for_one_object_of_a_symbol_instance_does_not_go_to_another() {
|
||||
let mut app = app();
|
||||
let a = selected(&app)[0];
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
|
||||
let b = selected(&app)[0];
|
||||
let inst = app.run("symbol.new", json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("symbol.instance.selectPart", json!({"id": inst, "path": [0]})).unwrap();
|
||||
let before = undo_count(&app);
|
||||
let mut p = panel(app);
|
||||
type_pending(&mut p, "#336699");
|
||||
p.run("symbol.instance.selectPart", json!({"id": inst, "path": [1]}));
|
||||
p.fx.key(Key::Enter, Modifiers::NONE).settle();
|
||||
let Paint::Solid { color, .. } = crate::panels::current_paints(&p.app()).0 else { panic!("a solid fill") };
|
||||
assert_eq!(rgb8(&color), [255, 0, 0], "the second object keeps its color");
|
||||
assert_eq!(undo_count(&p.app()), before, "nothing was applied");
|
||||
}
|
||||
|
||||
/// A text with a character `color.parse` does not read as whitespace (a no-break space) is refused,
|
||||
/// as `color.parse` refuses it, and changes nothing.
|
||||
#[test]
|
||||
fn a_no_break_space_in_the_text_is_refused() {
|
||||
let app = app();
|
||||
let doc = app.session.doc().unwrap().doc.clone();
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "\u{a0}#336699");
|
||||
assert_eq!(*p.app().session.doc().unwrap().doc, *doc);
|
||||
assert!(!p.app().ui.status.is_empty(), "the status bar says why");
|
||||
assert!(p.app_mut().run("color.parse", json!({"text": "\u{a0}#336699"})).is_err());
|
||||
}
|
||||
|
||||
/// A selected gradient stop takes the color and the alpha in one step.
|
||||
#[test]
|
||||
fn a_gradient_stop_takes_the_color_and_the_alpha() {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "#33669980");
|
||||
let (hex, opacity) = first_stop(&p);
|
||||
assert_eq!(hex, "#336699");
|
||||
assert!((opacity - 0.502).abs() < 1e-4, "{opacity}");
|
||||
}
|
||||
|
||||
/// A selected freeform point takes the color and the alpha.
|
||||
#[test]
|
||||
fn a_freeform_point_takes_the_color_and_the_alpha() {
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"gradient": {"kind": "freeform"}})).unwrap();
|
||||
let mut p = panel(app);
|
||||
type_in(&mut p, "#33669980");
|
||||
let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") };
|
||||
let f = super::gradient::shown_points(&g);
|
||||
assert_eq!(f.points[0].color.to_hex(), "#336699");
|
||||
assert!((f.points[0].opacity - 0.502).abs() < 1e-4, "{}", f.points[0].opacity);
|
||||
}
|
||||
|
||||
/// Text `color.parse` refuses changes nothing and shows its error in the status bar.
|
||||
#[test]
|
||||
fn refused_text_changes_nothing_and_says_why() {
|
||||
let app = app();
|
||||
let doc = app.session.doc().unwrap().doc.clone();
|
||||
let mut p = panel(app);
|
||||
for bad in ["#12345", "rgb(1, 2%, 3)", "not a color", "cmyk(0 0 0 0)"] {
|
||||
type_in(&mut p, bad);
|
||||
assert_eq!(*p.app().session.doc().unwrap().doc, *doc, "{bad}");
|
||||
assert!(p.app().ui.status.contains("must be a hex color"), "{bad}: {}", p.app().ui.status);
|
||||
}
|
||||
assert_eq!(shown(&p), "FF0000", "the field shows the color again");
|
||||
p.app_mut().ui.status.clear();
|
||||
let t = field(&p).expect("the hex field");
|
||||
p.fx.click(&t).key(Key::A, Modifiers::COMMAND).key(Key::Backspace, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(*p.app().session.doc().unwrap().doc, *doc, "an emptied field");
|
||||
assert!(p.app().ui.status.contains("must be a hex color"), "an emptied field: {}", p.app().ui.status);
|
||||
}
|
||||
@@ -242,6 +242,84 @@ fn an_opacity_edit_keeps_the_hue_picked_for_a_white_stop() {
|
||||
assert_eq!(p.number("Hue"), Some(120.0), "the strip keeps the hue after the opacity edit");
|
||||
}
|
||||
|
||||
/// The OKLCH hue picked last for a white gradient stop stays on the OKLCH Hue row after the row
|
||||
/// sets the stop's opacity.
|
||||
#[test]
|
||||
fn an_opacity_edit_keeps_the_oklch_hue_picked_for_a_white_stop() {
|
||||
let mut app = app();
|
||||
let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#0000ff"}]);
|
||||
app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap();
|
||||
app.select_tool("gradient");
|
||||
app.run("gradient.selectStop", json!({"index": 0})).unwrap();
|
||||
app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap();
|
||||
let mut p = Panel::new(app);
|
||||
p.fx.room(egui::vec2(260.0, 480.0)).settle();
|
||||
p.set("Hue", 120.0);
|
||||
assert_eq!(p.number("Hue"), Some(120.0), "the Hue row shows the hue picked for white");
|
||||
act(&mut p, AccessActionKind::SetValue(30.0));
|
||||
let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") };
|
||||
assert!((g.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", g.gradient.stops);
|
||||
assert_eq!(p.number("Hue"), Some(120.0), "the Hue row keeps the hue after the opacity edit");
|
||||
}
|
||||
|
||||
/// A screen reader's SetValue for the Opacity slider and one for the node named `label`, in one
|
||||
/// frame.
|
||||
fn set_both(p: &mut Panel, opacity: f64, (label, value): (&str, f64)) {
|
||||
use egui::accesskit::{Action, ActionData, ActionRequest, NodeId, TreeId};
|
||||
let set = |t: &Target, v: f64| {
|
||||
let target_node = NodeId(t.node.raw());
|
||||
egui::Event::AccessKitActionRequest(ActionRequest {
|
||||
action: Action::SetValue,
|
||||
target_tree: TreeId::ROOT,
|
||||
target_node,
|
||||
data: Some(ActionData::NumericValue(v)),
|
||||
})
|
||||
};
|
||||
let events = vec![set(&slider(p), opacity), set(&p.node(label), value)];
|
||||
p.fx.frame(events).idle(2);
|
||||
}
|
||||
|
||||
/// A gradient stop with stops red and blue, the first selected.
|
||||
fn stop_app() -> VectorcraftApp {
|
||||
let mut app = app();
|
||||
let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]);
|
||||
app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap();
|
||||
app.select_tool("gradient");
|
||||
app.run("gradient.selectStop", json!({"index": 0})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// The first stop of the fill's gradient.
|
||||
fn first_stop(p: &Panel) -> vectorcraft_color::GradientStop {
|
||||
let Paint::Gradient(g) = crate::panels::current_paints(&p.app()).0 else { panic!("still a gradient") };
|
||||
g.gradient.stops[0].clone()
|
||||
}
|
||||
|
||||
/// An opacity edit and a pick on the box's hue strip in one frame: the stop keeps both.
|
||||
#[test]
|
||||
fn an_opacity_edit_and_a_hue_pick_in_one_frame_keep_both() {
|
||||
let mut app = stop_app();
|
||||
app.run("ui.colorWheel", json!({"view": "box", "channel": "hue"})).unwrap();
|
||||
let mut p = Panel::new(app);
|
||||
set_both(&mut p, 30.0, ("Hue", 120.0));
|
||||
let stop = first_stop(&p);
|
||||
assert!((stop.opacity - 0.3).abs() < 1e-6, "the stop keeps the opacity: {stop:?}");
|
||||
assert_ne!(stop.color.to_hex(), "#ff0000", "the stop takes the pick: {stop:?}");
|
||||
}
|
||||
|
||||
/// An opacity edit and an OKLCH Hue edit in one frame: the stop keeps both.
|
||||
#[test]
|
||||
fn an_opacity_edit_and_an_oklch_edit_in_one_frame_keep_both() {
|
||||
let mut app = stop_app();
|
||||
app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap();
|
||||
let mut p = Panel::new(app);
|
||||
p.fx.room(egui::vec2(260.0, 480.0)).settle();
|
||||
set_both(&mut p, 30.0, ("Hue", 140.0));
|
||||
let stop = first_stop(&p);
|
||||
assert!((stop.opacity - 0.3).abs() < 1e-6, "the stop keeps the opacity: {stop:?}");
|
||||
assert_ne!(stop.color.to_hex(), "#ff0000", "the stop takes the edit: {stop:?}");
|
||||
}
|
||||
|
||||
/// A drag across the slider previews and ends as one undo step named Opacity.
|
||||
#[test]
|
||||
fn a_drag_is_one_undo_step() {
|
||||
|
||||
@@ -91,7 +91,7 @@ fn ui_color_wheel_sets_and_reads_the_settings() {
|
||||
let settings = |view: &str, vision: bool| {
|
||||
json!({
|
||||
"view": view, "channel": "hue", "sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false,
|
||||
"contrast": false, "contrastFor": "normalText", "contrastBackground": null, "vision": vision, "documentColors": false
|
||||
"hexField": false, "contrast": false, "contrastFor": "normalText", "contrastBackground": null, "vision": vision, "documentColors": false
|
||||
})
|
||||
};
|
||||
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false));
|
||||
@@ -104,7 +104,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, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors"
|
||||
"unknown parameter `visoin`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors"
|
||||
);
|
||||
assert!(app.ui.color_wheel.vision);
|
||||
assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true);
|
||||
|
||||
@@ -916,8 +916,9 @@ pub struct UiState {
|
||||
#[serde(skip)]
|
||||
pub(crate) new_swatch: Option<crate::dialogs::new_swatch::Open>,
|
||||
/// Color Wheel panel: the wheel or the box, the box's channel, the slider rows, the
|
||||
/// out-of-gamut shading, Show Opacity, Show Contrast, Contrast For and Contrast Background, and
|
||||
/// the color vision row (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]).
|
||||
/// out-of-gamut shading, Show Opacity, Show Hex Field, Show Contrast, Contrast For and Contrast
|
||||
/// Background, 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
|
||||
|
||||
@@ -5,6 +5,7 @@ pub(super) mod background;
|
||||
mod clipboard;
|
||||
mod contextmenu;
|
||||
mod cut;
|
||||
mod dialog_layout;
|
||||
mod distortkeys;
|
||||
mod document_drag;
|
||||
mod drag_commands;
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Where the parameter dialogs draw their rows: option rows stand beside or under the choice they belong to, and
|
||||
//! every check box and picker shows its name.
|
||||
|
||||
use egui::{Pos2, Rect};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
type Window = egui_kittest::Harness<'static, VectorcraftApp>;
|
||||
|
||||
/// A document with one selected rectangle, in a window that runs whole app frames.
|
||||
fn window() -> Window {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 90})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(
|
||||
move |ui, app: &mut VectorcraftApp| {
|
||||
if !std::mem::replace(&mut fonts, true) {
|
||||
crate::testing::install(ui.ctx());
|
||||
return;
|
||||
}
|
||||
app.tick(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
let root = h.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default();
|
||||
root.inner_rect = Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 900.0)));
|
||||
root.focused = Some(true);
|
||||
for _ in 0..2 {
|
||||
step(&mut h);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// One frame as the hosts run the window's; the commands it fired run as the next frame begins.
|
||||
fn step(h: &mut Window) {
|
||||
let ctx = h.ctx.clone();
|
||||
let app = h.state_mut();
|
||||
app.adopt_context(&ctx);
|
||||
craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out));
|
||||
h.step();
|
||||
crate::testing::run_fired(h.state_mut(), &ctx);
|
||||
}
|
||||
|
||||
/// The texts the window paints with `command` run, each with where it was drawn, a field label's colon left off.
|
||||
fn texts(command: &str, params: Value) -> Vec<(String, Rect)> {
|
||||
fn collect(s: &egui::Shape, out: &mut Vec<(String, Rect)>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push((t.galley.text().trim().trim_end_matches(':').to_owned(), t.visual_bounding_rect())),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut h = window();
|
||||
crate::menus::invoke(h.state_mut(), command, params);
|
||||
for _ in 0..6 {
|
||||
step(&mut h);
|
||||
}
|
||||
let mut out = vec![];
|
||||
h.output().shapes.iter().for_each(|c| collect(&c.shape, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
/// Where each painted `label` was drawn, top to bottom.
|
||||
fn all(texts: &[(String, Rect)], label: &str) -> Vec<Rect> {
|
||||
let mut found: Vec<Rect> = texts.iter().filter(|(t, _)| t == label).map(|(_, r)| *r).collect();
|
||||
found.sort_by(|a, b| a.top().total_cmp(&b.top()));
|
||||
found
|
||||
}
|
||||
|
||||
/// The one painted `label`.
|
||||
fn one(texts: &[(String, Rect)], label: &str) -> Rect {
|
||||
let found = all(texts, label);
|
||||
assert_eq!(found.len(), 1, "`{label}` drawn {} times in {:?}", found.len(), texts.iter().map(|t| &t.0).collect::<Vec<_>>());
|
||||
found[0]
|
||||
}
|
||||
|
||||
/// `b` stands on `a`'s line, to its right.
|
||||
fn beside(a: Rect, b: Rect) -> bool {
|
||||
(a.center().y - b.center().y).abs() < a.height() / 2.0 && b.left() > a.right()
|
||||
}
|
||||
|
||||
/// The Transform effect names its Reflect X, Reflect Y and Random check boxes.
|
||||
#[test]
|
||||
fn the_transform_effect_names_its_reflect_options() {
|
||||
let shown = texts("effect.dialog", json!({"effect": "distort.transform"}));
|
||||
for label in ["Reflect X", "Reflect Y", "Random"] {
|
||||
one(&shown, label);
|
||||
}
|
||||
}
|
||||
|
||||
/// Transform Each names its reference point picker.
|
||||
#[test]
|
||||
fn transform_each_names_its_reference_point() {
|
||||
let shown = texts("object.transformEach", json!({}));
|
||||
one(&shown, "Reference Point");
|
||||
}
|
||||
|
||||
/// Roughen's Relative and Absolute stand on one line, and so do Smooth and Corner.
|
||||
#[test]
|
||||
fn roughen_puts_each_choice_on_one_line() {
|
||||
let shown = texts("effect.dialog", json!({"effect": "distort.roughen"}));
|
||||
assert!(beside(one(&shown, "Relative"), one(&shown, "Absolute")), "Relative, then Absolute on its line");
|
||||
// The Properties panel also shows a Corner row; the dialog's Corner is the one on Smooth's line.
|
||||
let smooth = one(&shown, "Smooth");
|
||||
assert!(all(&shown, "Corner").into_iter().any(|corner| beside(smooth, corner)), "Smooth, then Corner on its line");
|
||||
}
|
||||
|
||||
/// The Corners dialog's Relative and Absolute stand on one line.
|
||||
#[test]
|
||||
fn corners_puts_relative_and_absolute_on_one_line() {
|
||||
let shown = texts("ui.corners", json!({}));
|
||||
assert!(beside(one(&shown, "Relative"), one(&shown, "Absolute")), "Relative, then Absolute on its line");
|
||||
}
|
||||
|
||||
/// Drop Shadow's color row stands under the Color choice, before Darkness, and the Darkness row under Darkness.
|
||||
#[test]
|
||||
fn drop_shadow_rows_stand_under_their_choice() {
|
||||
let shown = texts("effect.dialog", json!({"effect": "stylize.dropShadow"}));
|
||||
let mut order: Vec<(f32, &str)> = ["Color", "Darkness"].iter().flat_map(|l| all(&shown, l).into_iter().map(move |r| (r.top(), *l))).collect();
|
||||
order.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let labels: Vec<&str> = order.iter().map(|(_, l)| *l).collect();
|
||||
assert_eq!(labels, ["Color", "Color", "Darkness", "Darkness"], "each choice, then its row");
|
||||
}
|
||||
|
||||
/// Print's Range field stands under the Range choice, before Ignore Artboards.
|
||||
#[test]
|
||||
fn print_range_stands_under_its_choice() {
|
||||
let shown = texts("file.print", json!({}));
|
||||
let ignore = one(&shown, "Ignore Artboards (all the art as one page)");
|
||||
let ranges = all(&shown, "Range");
|
||||
assert_eq!(ranges.len(), 2, "the choice and the field");
|
||||
assert!(ranges.iter().all(|r| r.bottom() <= ignore.top()), "the Range field before Ignore Artboards");
|
||||
}
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user