Merge main into fix/shortcuts-ui-group

This commit is contained in:
dotCooCoo committed 2026-11-25 22:21:31 -08:00
commit 52c134c7b6
55 files changed
+3395 -83

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+13 -6
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/vectorcraft",
"repository_id": 1398097510,
"producer_workflow_id": null,
"producer_workflow_id": 430275079,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
@@ -79,7 +79,14 @@
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [VectorCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
false && github.repository == 'storytold/vectorcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/vectorcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/vectorcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/vectorcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/vectorcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'vectorcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+10 -7
View File
@@ -1,7 +1,8 @@
name: VectorCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
@@ -22,21 +23,23 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/vectorcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: vectorcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+4 -4
View File
@@ -22,13 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: vectorcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+1
View File
@@ -14,6 +14,7 @@ pub mod oklab;
pub mod palette_io;
pub mod recolor;
pub mod swatch;
pub mod wcag;
pub use blend::BlendMode;
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
+146
View File
@@ -0,0 +1,146 @@
//! Contrast between two colors as WCAG 2 measures it (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>):
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
/// What the content in front is, which sets the ratio it needs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Category {
/// Text below the large-scale size: AA 4.5:1, AAA 7:1.
#[default]
NormalText,
/// Large-scale text (at least 18 pt, or 14 pt bold): AA 3:1, AAA 4.5:1.
LargeText,
/// User interface components and graphical objects: AA 3:1, no AAA level.
Graphics,
}
impl Category {
pub const ALL: [Category; 3] = [Category::NormalText, Category::LargeText, Category::Graphics];
/// The id commands and settings use.
pub fn id(self) -> &'static str {
match self {
Category::NormalText => "normalText",
Category::LargeText => "largeText",
Category::Graphics => "graphics",
}
}
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.id() == s)
}
/// The English name shown in menus.
pub fn label(self) -> &'static str {
match self {
Category::NormalText => "Normal Text",
Category::LargeText => "Large Text",
Category::Graphics => "Graphics",
}
}
/// The minimum ratio for AA, and for AAA where the category has that level.
pub fn minimums(self) -> (f64, Option<f64>) {
match self {
Category::NormalText => (4.5, Some(7.0)),
Category::LargeText => (3.0, Some(4.5)),
Category::Graphics => (3.0, None),
}
}
/// Whether `ratio` meets AA, and AAA where the category has that level. The unrounded ratio
/// is compared, so 4.499:1 fails 4.5:1.
pub fn passes(self, ratio: f64) -> (bool, Option<bool>) {
let (aa, aaa) = self.minimums();
(ratio >= aa, aaa.map(|m| ratio >= m))
}
}
/// The relative luminance of display sRGB `srgb` (each channel 0 to 1), from 0 for black to 1
/// for white.
pub fn relative_luminance(srgb: [f32; 3]) -> f64 {
let lin = |v: f32| {
let v = f64::from(v.clamp(0.0, 1.0));
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
};
0.2126 * lin(srgb[0]) + 0.7152 * lin(srgb[1]) + 0.0722 * lin(srgb[2])
}
/// The contrast ratio of display sRGB colors `a` and `b`, from 1 to 21, whichever is lighter.
pub fn contrast_ratio(a: [f32; 3], b: [f32; 3]) -> f64 {
let (la, lb) = (relative_luminance(a), relative_luminance(b));
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
}
/// Display sRGB `fg` drawn at `opacity` (0 to 1) over the opaque `bg`, mixed per channel as the
/// canvas mixes a translucent color.
pub fn over(fg: [f32; 3], opacity: f32, bg: [f32; 3]) -> [f32; 3] {
let a = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 };
std::array::from_fn(|i| fg[i] * a + bg[i] * (1.0 - a))
}
/// `ratio` as text with two decimals, cut off rather than rounded, so a ratio just under a
/// minimum never reads as the minimum: 4.4963 is "4.49:1".
pub fn ratio_text(ratio: f64) -> String {
let r = if ratio.is_finite() { ratio.clamp(1.0, 21.0) } else { 1.0 };
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(s: &str) -> [f32; 3] {
let v = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).map_or(0.0, |b| f32::from(b) / 255.0);
[v(0), v(2), v(4)]
}
#[test]
fn black_on_white_is_21_and_a_color_on_itself_is_1() {
assert!((contrast_ratio(hex("000000"), hex("ffffff")) - 21.0).abs() < 1e-9);
assert!((contrast_ratio(hex("ffffff"), hex("000000")) - 21.0).abs() < 1e-9);
assert!((contrast_ratio(hex("355f78"), hex("355f78")) - 1.0).abs() < 1e-12);
}
#[test]
fn ratios_near_a_minimum_are_compared_unrounded_and_cut_off_in_text() {
let r = contrast_ratio(hex("fdc96e"), hex("355f78"));
assert!((r - 4.4963).abs() < 1e-3, "{r}");
assert_eq!(ratio_text(r), "4.49:1");
assert_eq!(Category::NormalText.passes(r), (false, Some(false)));
assert_eq!(Category::LargeText.passes(r), (true, Some(false)));
let gray = contrast_ratio(hex("767676"), hex("ffffff"));
assert!((gray - 4.542).abs() < 1e-3, "{gray}");
assert_eq!(ratio_text(gray), "4.54:1");
assert!(Category::NormalText.passes(gray).0);
let lighter = contrast_ratio(hex("777777"), hex("ffffff"));
assert!((lighter - 4.478).abs() < 1e-3, "{lighter}");
assert_eq!(ratio_text(lighter), "4.47:1");
assert!(!Category::NormalText.passes(lighter).0);
assert_eq!(ratio_text(21.0), "21.00:1");
assert_eq!(ratio_text(f64::NAN), "1.00:1");
}
#[test]
fn graphics_have_no_aaa_level() {
assert_eq!(Category::Graphics.passes(3.0), (true, None));
assert_eq!(Category::Graphics.passes(2.99), (false, None));
assert_eq!(Category::LargeText.passes(4.5), (true, Some(true)));
}
#[test]
fn category_ids_parse_back() {
for c in Category::ALL {
assert_eq!(Category::parse(c.id()), Some(c));
}
assert_eq!(Category::parse("NormalText"), None);
}
#[test]
fn half_opaque_black_over_white_is_mid_gray() {
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
assert_eq!(over([0.2; 3], f32::NAN, [1.0; 3]), [0.2; 3]);
assert_eq!(over([0.2; 3], 2.0, [1.0; 3]), [0.2; 3]);
}
}
+633 -1
View File
@@ -14,7 +14,8 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::cms::Model;
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
use vectorcraft_color::{Color, Paint, keep_model};
use vectorcraft_color::wcag::{self, Category};
use vectorcraft_color::{BlendMode, Color, Paint, keep_model};
use vectorcraft_doc::live::lerp_color;
use vectorcraft_doc::pattern::PatternDef;
pub(crate) use vectorcraft_doc::recolor::map_paint;
@@ -135,6 +136,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
harmony
),
cmd!(
query "color.contrast",
"Contrast",
[],
None,
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
always,
contrast
),
]
}
@@ -991,3 +1001,625 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
let hex = |cs: &[Color]| cs.iter().map(Color::to_hex).collect::<Vec<_>>();
Ok(json!({ "rule": rule.id(), "colors": hex(&g.colors), "grid": g.grid.iter().map(|r| hex(r)).collect::<Vec<_>>() }))
}
/// The side, in points, of the square [`color_below`] renders.
const BELOW_SIDE: f64 = 1.0;
/// The pixels per point [`color_below`] renders at.
const BELOW_SCALE: f64 = 4.0;
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.contrast";
check_numbers(p, &["opacity"], C)?;
let opacity = match p.get("opacity").and_then(Value::as_f64) {
Some(o) if (0.0..=100.0).contains(&o) => Some(o as f32 / 100.0),
Some(_) => {
let key = "opacity";
return Err(bad(C, format!("`{key}` must be from 0 to 100")));
}
None => None,
};
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
let (color, drawn) = match p.get("color") {
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
};
let rich_black = s.prefs.black_on_screen == "rich";
let cms = vectorcraft_color::cms::active();
let shown = |c: &Color| match *c {
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
_ => cms.display_rgb(c),
};
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
let (against, written) = match p.get("against").filter(|_| !below) {
None => {
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
// one the ratio uses, and giving it back answers the same ratio.
let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
}
Some(v) => {
let key = "against";
let shown = shown(&color_value(v).ok_or_else(|| bad(C, format!("`{key}` must be a color or {}", "\"below\"")))?);
(shown, to_8bit(cms.srgb_to_rgb(shown)))
}
};
// Innermost first: the row (inside the object), the object, then its groups and layer. A given
// opacity takes the place of the object's and of its groups' and layer's.
let row = drawn.row.map(|(blend, o)| Step {
blend,
opacity: if opacity.is_some() { 1.0 } else { o },
isolate: false,
hide: Some(Part::Rows),
within: Part::Rows,
});
let object = Step { blend: drawn.blend, opacity: opacity.unwrap_or(drawn.opacity), isolate: drawn.isolate, hide: None, within: Part::Object };
let groups = drawn.around.iter().map(|l| Step {
blend: l.blend,
opacity: if opacity.is_some() { 1.0 } else { l.opacity },
isolate: l.isolate,
hide: Some(l.part.clone()),
within: l.part.clone(),
});
let steps = row.into_iter().chain([object]).chain(groups).collect::<Vec<_>>();
// With the background sampled and no opacity given, each level blends with and draws over the
// art below it inside the levels around it, as the canvas composites groups; otherwise the
// background stands for that art. Inside an object, group or layer that isolates its blending,
// the art below is only what that level holds (nothing, for a given background).
let sampled = below && opacity.is_none();
// A level with a blend mode that does not isolate draws what is inside it over the art below it,
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
let mut x = (shown(&color), 1.0f32);
let mut alone = 1.0f32;
for (k, step) in steps.iter().enumerate() {
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
continue;
}
let above = &steps[k + 1..];
let scope = above.iter().find(|a| a.isolate);
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::<Vec<_>>();
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
let backdrop = match scope {
Some(_) if !sampled => ([0.0; 3], 0.0),
None if !sampled => (against, 1.0),
// The background itself, as the answer writes it.
None if step.hide.is_none() && full.is_empty() => (against, 1.0),
_ => read(scope.map(|a| &a.within))?,
};
// The alpha of the art below the level inside the level around it, while a blending level
// lies further out (none for a given background).
let inner = match above.first() {
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
_ => 0.0,
};
let source = if !blends(step) {
x
} else if alone <= 0.0 {
(x.0, 0.0)
} else {
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
};
// A level that isolates its blending carries out the alpha of what it holds composited on
// its own.
let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
x = composite(step.blend, source, step.opacity, backdrop);
alone = drawn + inner * (1.0 - drawn);
}
let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
let ratio = wcag::contrast_ratio(front, against);
let levels = |c: Category| {
let (aa, aaa) = c.passes(ratio);
match aaa {
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
None => json!({ "aa": aa }),
}
};
let [r, g, b] = written;
Ok(json!({
"ratio": ratio,
"against": format!("#{r:02x}{g:02x}{b:02x}"),
"normalText": levels(Category::NormalText),
"largeText": levels(Category::LargeText),
"graphics": levels(Category::Graphics),
}))
}
/// An object around the proxy's object: one in the document, or a group of the picked object's
/// dynamic symbol instance's art, by its path in the art (the art's root for an empty path). For
/// [`color_below`], also the objects the proxy's color comes from, or their rows from the one the
/// proxy shows up.
#[derive(Clone, PartialEq)]
enum Part {
Doc(NodeId),
Art(Vec<u32>),
Object,
Rows,
}
/// An object around the proxy's object that draws it: its opacity, blend mode, whether it isolates
/// the blending inside it, and which object it is.
#[derive(Clone, PartialEq)]
struct Level {
opacity: f32,
blend: BlendMode,
isolate: bool,
part: Part,
/// Whether it has an opacity mask that is not disabled.
masked: bool,
}
/// Whether object `n` has an opacity mask that is not disabled.
fn masked(n: &Node) -> bool {
n.extras().mask.as_ref().is_some_and(|m| !m.disabled)
}
/// How the proxy's color is drawn: the object's opacity, its fill or stroke row's blend mode and
/// opacity (none for type's character paint or a colorize color), each times that of a stop or
/// point when it holds the paint, the object's blend mode and whether it isolates its blending, and
/// the groups and layer around the object, innermost first.
#[derive(Clone, PartialEq)]
struct Drawn {
opacity: f32,
row: Option<(BlendMode, f32)>,
blend: BlendMode,
isolate: bool,
around: Vec<Level>,
/// The object's shown fill and stroke rows with paint below the row, which the row draws over.
lower: Vec<vectorcraft_doc::AppearanceItem>,
}
impl Default for Drawn {
fn default() -> Self {
Self { opacity: 1.0, row: None, blend: BlendMode::Normal, isolate: false, around: vec![], lower: vec![] }
}
}
/// One level [`contrast`] draws the color through: the row, the object, or a [`Level`]. `hide` is
/// what [`color_below`] hides to read the art below it (`None`: the selection), and `within` the
/// object whose art is read inside it.
struct Step {
blend: BlendMode,
opacity: f32,
isolate: bool,
hide: Option<Part>,
within: Part,
}
/// `x` (a display sRGB color and its alpha) drawn at `opacity` with blend mode `mode` over `backdrop`
/// (likewise), as the PDF compositing formulas give it: the mode applies where the backdrop is
/// drawn, and over nothing the color stays as it is.
fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32; 3], f32)) -> ([f32; 3], f32) {
let (b, ab) = backdrop;
let a = x.1 * if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 };
let mixed = vectorcraft_color::blend::blend_rgb(mode, b, x.0);
let out = a + ab * (1.0 - a);
if out <= 0.0 {
return (b, 0.0);
}
(std::array::from_fn(|i| (a * ((1.0 - ab) * x.0[i] + ab * mixed[i]) + ab * (1.0 - a) * b[i]) / out), out)
}
/// Whether `a` and `b` draw a color alike: the same blend modes and isolation, and unless
/// `given_opacity` (which takes the place of their opacities) the same opacities. With `below`, the
/// levels that change what they draw must be the same objects too, since the art below each one is
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
/// since the row draws over the object's rows below it and the object over the art behind it, and a
/// row that blends or is translucent must lie over the same shown rows.
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
let level = |x: &Level, y: &Level| {
x.blend == y.blend
&& x.isolate == y.isolate
&& (given_opacity || (x.opacity - y.opacity).abs() < 1e-6)
&& (!below || given_opacity || x.part == y.part)
};
let (la, lb) = (a.around.iter().filter(counts).collect::<Vec<_>>(), b.around.iter().filter(counts).collect::<Vec<_>>());
// A row in Normal mode draws as type's character paint does, and an object's isolation only
// changes a row's blending.
let row = |d: &Drawn| d.row.map(|r| r.0).filter(|m| *m != BlendMode::Normal);
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
// A row that blends or lets art through draws over the rows below it, read at one point.
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
row(a) == row(b)
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
&& a.blend == b.blend
&& (row(a).is_none() || a.isolate == b.isolate)
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
&& la.len() == lb.len()
&& la.iter().zip(&lb).all(|(x, y)| level(x, y))
}
/// The active proxy's color (its selected gradient stop or freeform point, else the first, or a
/// gradient mesh's first picked point, each at its own opacity) and how
/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not
/// compared, since the given opacity takes their place; with `below` (the background is sampled),
/// objects in different translucent or blending groups or layers differ, since the art below each
/// such level is read with it hidden.
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> {
let stroke = !s.fill_active;
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
if if stroke { stroke_mixed } else { fill_mixed } {
return Err("the selected objects' colors differ: give `color`".into());
}
let (fill, stroke_paint) = s.proxy_paints();
// The Fill proxy shows a gradient mesh's picked points, each drawn at its own opacity.
let points = if stroke { vec![] } else { s.fill_mesh_points() };
let source = || {
s.proxy_source(stroke)
.map(|(n, item)| {
let d = drawn_settings(s, &n, item, stroke)?;
Ok::<_, String>(match picked_opacities(&n, &points).first() {
Some(o) => at(&d, *o),
None => d,
})
})
.transpose()
};
let drawing;
// Selected objects that share a color but draw it differently have no one answer.
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) {
let item = s.appearance_item();
// Every painted object inside a selected group counts, as the proxy's color comes from all,
// except hidden ones and those inside a hidden group, which draw nothing. The first shown
// one gives the opacity and blend modes the answer uses.
let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible));
let mut drawn = vec![];
for n in st.selection.subjects().iter().filter_map(|id| st.doc.node(*id)) {
for (n, item) in shown_sources(n, item, stroke).into_iter().filter(|(c, _)| shown(c.id)) {
let d = drawn_settings(s, n, item, stroke)?;
let picked = picked_opacities(n, &points);
if picked.is_empty() {
drawn.push(d);
} else {
drawn.extend(picked.into_iter().map(|o| at(&d, o)));
}
}
}
drawing = match drawn.first() {
Some(first) => first.clone(),
None => source()?.unwrap_or_default(),
};
if !drawn.iter().all(|d| draws_alike(d, &drawing, given_opacity, below)) {
// With `opacity` given, the opacities are not compared and the background stands for the
// art below.
if !given_opacity && drawn.iter().all(|d| draws_alike(d, &drawing, true, below)) {
return Err("the selected objects' colors differ: give `opacity` or `color`".into());
}
return Err("the selected objects' colors differ: give `color`".into());
}
} else {
drawing = source()?.unwrap_or_default();
}
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
match if stroke { stroke_paint } else { fill } {
Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
}
Paint::Gradient(g) => {
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
}
Paint::None | Paint::Pattern { .. } => Err(no_color()),
}
}
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
/// row, else in the object.
fn at(drawing: &Drawn, opacity: f32) -> Drawn {
match drawing.row {
Some((m, o)) => Drawn { row: Some((m, o * opacity)), ..drawing.clone() },
None => Drawn { opacity: drawing.opacity * opacity, ..drawing.clone() },
}
}
/// The opacities of the picked points of gradient mesh `n` ([`Session::fill_mesh_points`]), whose
/// colors the Fill proxy shows for it: empty for another object or with no points picked.
fn picked_opacities(n: &Node, points: &[(NodeId, Vec<usize>)]) -> Vec<f32> {
match (&n.kind, points.iter().find(|(id, _)| *id == n.id)) {
(NodeKind::Mesh(m), Some((_, v))) => v.iter().filter_map(|i| m.points.get(*i)).map(|q| q.opacity).collect(),
_ => vec![],
}
}
/// The objects whose fill or stroke the proxy shows for selected object `n`, with the appearance
/// item each shows: `n` itself when it holds such an item, else every painted object inside it
/// ([`Session::proxy_source`] shows the first).
fn shown_sources(n: &Node, item: Option<usize>, stroke: bool) -> Vec<(&Node, Option<usize>)> {
if n.appearance.item_of_kind(item, !stroke).is_some() {
return vec![(n, item)];
}
let mut nodes = vec![];
super::paint::painted(n, true, stroke, &mut nodes);
nodes.into_iter().map(|c| (c, None)).collect()
}
/// How object `n` draws its fill or stroke (`item`, else the proxy's row), as [`Drawn`] gives it. An
/// error for a hidden row.
fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> std::result::Result<Drawn, String> {
let item = n.appearance.item_of_kind(item, !stroke);
// Without a targeted row, type shows its characters' paint and a colorized image its
// colorize color, which no fill or stroke row's opacity applies to.
let own_paint = item.is_none() && (matches!(n.kind, NodeKind::Text(_)) || (!stroke && n.extras().colorize.is_some()));
let own = match (own_paint, stroke) {
(true, _) => None,
(false, true) => n.appearance.stroke_at(item).map(|l| (l.opacity, l.blend, l.visible)),
(false, false) => n.appearance.fill_at(item).map(|l| (l.opacity, l.blend, l.visible)),
};
if own.is_some_and(|o| !o.2) {
return Err("the active fill or stroke is hidden: give `color`".to_string());
}
// The groups and layer the object is in draw it too (`enclosing` lists the outermost first).
let mut around = enclosing(s, n.id);
around.reverse();
// An opacity mask sets how much of the color shows at each point, which no one opacity gives.
if masked(n) || around.iter().any(|l| l.masked) {
return Err("the active fill or stroke is drawn through an opacity mask: give `color`".to_string());
}
// The rows below the row that draw, as `hide_rows` leaves them shown.
let rows = &n.appearance.items;
let at_row = item.or_else(|| rows.iter().rposition(|r| r.is_fill() != stroke));
let lower = match (own, at_row) {
(Some(_), Some(i)) => rows.iter().take(i).filter(|r| r.visible() && !r.paint().is_none()).cloned().collect(),
_ => vec![],
};
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
}
/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
/// `color` itself otherwise.
fn stained(s: &Session, color: Color) -> Color {
let stain = s.active().and_then(|st| {
let sp = st.selection.symbol_part.as_ref()?;
st.selected_symbol_part()?;
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
});
match stain {
Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
None => color,
}
}
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
/// layer, and for a picked object of a dynamic symbol instance, the instance, its groups and layer,
/// and the groups of the symbol's art around the object.
fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
let Some(st) = s.active() else { return vec![] };
let doc = &st.doc;
let level = |n: &Node, part: Part| Level { opacity: n.opacity, blend: n.blend, isolate: n.isolate, part, masked: masked(n) };
// `ancestry` lists the object itself last.
let in_doc = |id: NodeId, own: bool| {
let ids = doc.ancestry(id).unwrap_or_default();
let nodes = ids.into_iter().filter(|a| own || *a != id).filter_map(|a| doc.node(a));
nodes.map(|a| level(a, Part::Doc(a.id))).collect::<Vec<_>>()
};
let Some(sp) = st.selection.symbol_part.as_ref() else { return in_doc(id, false) };
let art = doc.node(sp.instance).and_then(|inst| {
let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { return None };
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
Some(vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst))
});
// Without the picked object, the proxy shows the selected object itself (`proxy_source`).
let Some(art) = art.filter(|a| vectorcraft_doc::symbol_overrides::part(a, &sp.path).is_some()) else { return in_doc(id, false) };
let mut out = in_doc(sp.instance, true);
if let Some((_, groups)) = sp.path.split_last() {
// The art's root and each group on the way to the object, not the object itself.
let mut n = &art;
out.push(level(n, Part::Art(vec![])));
for (k, &i) in groups.iter().enumerate() {
let Some(c) = n.children().and_then(|c| c.get(usize::try_from(i).ok()?)) else { break };
n = c;
out.push(level(n, Part::Art(groups[..=k].to_vec())));
}
}
out
}
/// The display sRGB VectorCraft draws at the center of the selection's bounds with the selected
/// objects hidden: the average of a small square rendered as the canvas renders it (artboards, the
/// on-screen Appearance of Black, no proof, no template layers or guides), over white where nothing
/// is drawn, with its alpha. With `hide`, that object (a group or layer around the selection) is
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
/// without artboards.
fn color_below(
s: &Session,
rich_black: bool,
hide: Option<&Part>,
full: &[&Part],
scope: Option<&Part>,
) -> std::result::Result<([f32; 3], f32), String> {
super::has_selection(s)?;
let st = s.active().ok_or("no document open")?;
let ids = st.selection.objects.clone();
// A picked object of a dynamic symbol instance hides only itself: the rest of the instance
// stays in the sample, measured at the object's center.
let picked = st.selection.symbol_part.as_ref().and_then(|sp| {
let inst = st.doc.node(sp.instance)?;
let center = kurbo::Shape::bounding_box(&vectorcraft_doc::hit::symbol_part_outline(&st.doc, inst, &sp.path)?).center();
vectorcraft_doc::symbol_overrides::part(inst_art(&st.doc, sp.instance)?, &sp.path)?;
Some((sp, center))
});
let center = match picked {
Some((_, center)) => center,
None => st.doc.bounds_of(&ids, false).ok_or("nothing selected")?.center(),
};
// The objects the proxy's color comes from, with the row each shows (`proxy_color`); for a picked
// object, the object itself at `sp.path`, with its topmost row of the kind.
let (stroke, item) = (!s.fill_active, s.appearance_item());
let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible));
let painted = match picked {
Some(_) => vec![],
None => {
let nodes = st.selection.subjects().iter().filter_map(|id| st.doc.node(*id));
nodes.flat_map(|n| shown_sources(n, item, stroke)).filter(|(c, _)| shown(c.id)).map(|(c, item)| (c.id, item)).collect::<Vec<_>>()
}
};
let own = |p: Option<&Part>| matches!(p, Some(Part::Art(_) | Part::Object | Part::Rows));
let art_edits = picked.is_some() && (hide.is_none() || own(hide) || full.iter().any(|p| own(Some(p))) || own(scope));
let mut copy = (art_edits || !full.is_empty() || hide == Some(&Part::Rows)).then(|| Document::clone(&st.doc));
let mut hidden = HashSet::new();
// The art of the picked object's instance in `copy`, as a copy of its symbol that only this
// instance draws, so other instances of the symbol keep it.
let symbol = match (picked, copy.as_mut()) {
(Some((sp, _)), Some(doc)) if art_edits => Some(own_symbol(doc, sp.instance).ok_or("the picked object is not found")?),
_ => None,
};
let lost = || "the picked object is not found".to_string();
match (hide, picked) {
(None, Some((sp, _))) => art_mut(copy.as_mut(), symbol, &sp.path).ok_or_else(lost)?.visible = false,
(None, None) => hidden.extend(ids),
(Some(Part::Doc(id)), _) => hidden.extend([*id]),
// The art's root is all the instance draws.
(Some(Part::Art(path)), Some((sp, _))) if path.is_empty() => hidden.extend([sp.instance]),
(Some(Part::Art(path)), _) => art_mut(copy.as_mut(), symbol, path).ok_or_else(lost)?.visible = false,
(Some(Part::Rows), Some((sp, _))) => hide_rows(art_mut(copy.as_mut(), symbol, &sp.path).ok_or_else(lost)?, None, stroke),
(Some(Part::Rows), None) => {
for (id, item) in &painted {
if let Some(n) = copy.as_mut().and_then(|d| d.node_mut(*id)) {
hide_rows(n, *item, stroke);
}
}
}
(Some(Part::Object), _) => return Err(lost()),
}
// The levels around the one read draw what is inside them as it is. An instance's override of
// an object of its art's opacity or blend mode is dropped with it.
let plain = |n: &mut Node| {
n.opacity = 1.0;
n.blend = BlendMode::Normal;
};
let plain_art = |copy: &mut Option<Document>, path: &[u32]| -> std::result::Result<(), String> {
plain(art_mut(copy.as_mut(), symbol, path).ok_or_else(lost)?);
let sp = picked.ok_or_else(lost)?.0;
if let Some(e) = copy.as_mut().and_then(|d| d.node_mut(sp.instance)).and_then(Node::extras_if_any) {
for o in e.symbol_overrides.iter_mut().filter(|o| o.path == path) {
(o.opacity, o.blend) = (None, None);
}
}
Ok(())
};
for p in full {
let ids = match (p, picked) {
(Part::Doc(id), _) => vec![*id],
(Part::Art(path), _) => {
plain_art(&mut copy, path)?;
continue;
}
(Part::Object, Some((sp, _))) => {
plain_art(&mut copy, &sp.path)?;
continue;
}
(Part::Object, None) => painted.iter().map(|p| p.0).collect(),
(Part::Rows, _) => continue,
};
for id in ids {
if let Some(n) = copy.as_mut().and_then(|d| d.node_mut(id)) {
plain(n);
}
}
}
// Inside a level, only the art that level holds is drawn, over nothing.
if let Some(scope) = scope {
let (keep, path) = match (scope, picked) {
(Part::Doc(id), _) => (vec![*id], &[][..]),
(Part::Art(path), Some((sp, _))) => (vec![sp.instance], &path[..]),
(Part::Object, Some((sp, _))) => (vec![sp.instance], &sp.path[..]),
(Part::Object, None) => (painted.iter().map(|p| p.0).collect(), &[][..]),
_ => return Err(lost()),
};
// Everything that is neither on the way to a kept object nor inside one is hidden.
let on_way = keep.iter().flat_map(|k| st.doc.ancestry(*k).unwrap_or_default()).collect::<HashSet<_>>();
let parents = std::iter::once(None).chain(on_way.iter().filter(|a| !keep.contains(a)).map(|a| Some(*a)));
for parent in parents {
hidden.extend(st.doc.children(parent).into_iter().flatten().map(|n| n.id).filter(|n| !on_way.contains(n)));
}
for (k, &keep) in path.iter().enumerate() {
let group = art_mut(copy.as_mut(), symbol, &path[..k]).and_then(Node::children_mut).ok_or_else(lost)?;
for (i, c) in group.iter_mut().enumerate() {
if u32::try_from(i).ok() != Some(keep) {
Arc::make_mut(c).visible = false;
}
}
}
}
let h = BELOW_SIDE / 2.0;
let region = vectorcraft_geom::Rect::new(center.x - h, center.y - h, center.x + h, center.y + h);
// Template layers and guides are aids to drawing, not artwork: left out as exports leave them.
let opts = vectorcraft_render::RenderOptions {
background: scope.is_none().then_some([255, 255, 255, 255]),
artboards: scope.is_none(),
hidden,
rich_black,
skip_templates: true,
..Default::default()
};
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
let px = img.pixels.as_chunks::<4>().0;
if px.is_empty() {
return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
}
// The pixels are premultiplied: the average color is their sum over their alpha's.
let mut sum = [0.0f64; 4];
for p in px {
for (s, v) in sum.iter_mut().zip(p) {
*s += f64::from(*v);
}
}
let alpha = sum[3] / (px.len() as f64 * 255.0);
if alpha <= 0.0 {
return Ok(([0.0; 3], 0.0));
}
let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32);
Ok((rgb, alpha as f32))
}
/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it.
fn hide_rows(n: &mut Node, item: Option<usize>, stroke: bool) {
let a = &mut n.appearance;
let Some(i) = a.item_of_kind(item, !stroke).or_else(|| a.items.iter().rposition(|r| r.is_fill() != stroke)) else { return };
for r in a.items.iter_mut().skip(i) {
match r {
vectorcraft_doc::AppearanceItem::Fill(f) => f.visible = false,
vectorcraft_doc::AppearanceItem::Stroke(s) => s.visible = false,
}
}
}
/// The art the symbol instance `inst` of `doc` draws, as its symbol holds it.
fn inst_art(doc: &Document, inst: NodeId) -> Option<&Arc<Node>> {
let NodeKind::SymbolInstance { symbol, .. } = &doc.node(inst)?.kind else { return None };
doc.symbols.iter().find(|s| s.name == *symbol).map(|s| &s.art)
}
/// The object at `path` in the art of `doc`'s symbol at index `symbol` (the art's root for an empty
/// path).
fn art_mut<'a>(doc: Option<&'a mut Document>, symbol: Option<usize>, path: &[u32]) -> Option<&'a mut Node> {
let mut n = Arc::make_mut(&mut doc?.symbols.get_mut(symbol?)?.art);
for &i in path {
n = Arc::make_mut(n.children_mut()?.get_mut(usize::try_from(i).ok()?)?);
}
Some(n)
}
/// Makes the symbol instance `inst` of `doc` draw a copy of its symbol, so that a change to the copy
/// leaves other instances as they are. Returns the copy's index in the document's symbols.
fn own_symbol(doc: &mut Document, inst: NodeId) -> Option<usize> {
let NodeKind::SymbolInstance { symbol, .. } = &doc.node(inst)?.kind else { return None };
let mut sym = doc.symbols.iter().find(|s| s.name == *symbol)?.clone();
sym.name = unique_name(&sym.name, |name| doc.symbols.iter().any(|s| s.name == name));
let name = sym.name.clone();
doc.symbols.push(sym);
if let NodeKind::SymbolInstance { symbol, .. } = &mut doc.node_mut(inst)?.kind {
*symbol = name;
}
Some(doc.symbols.len() - 1)
}
@@ -742,6 +742,7 @@ pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
"addon.pen.nextSegment",
"color.contrast",
"effect.refreshDeferred",
"graphicStyle.setOptions",
"object.blend.createSpine",
+1
View File
@@ -32,6 +32,7 @@ mod clipflavours;
mod clippaint;
mod cmdsplit;
mod cmykflatten;
mod colorcontrast;
mod colorguide;
mod colorguidelib;
mod colorize;
+854
View File
@@ -0,0 +1,854 @@
//! `color.contrast`: the WCAG 2 contrast of a color against the color behind the selection.
use serde_json::{Value, json};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s
}
fn ratio(r: &Value) -> f64 {
r["ratio"].as_f64().unwrap()
}
#[test]
fn a_pair_just_under_aa_fails_it() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
assert!((ratio(&r) - 4.496).abs() < 1e-3, "{r}");
assert_eq!(r["against"], "#355f78");
assert_eq!(r["normalText"], json!({"aa": false, "aaa": false}));
assert_eq!(r["largeText"], json!({"aa": true, "aaa": false}));
assert_eq!(r["graphics"], json!({"aa": true}), "graphics have no AAA level");
assert_eq!(vectorcraft_color::wcag::ratio_text(ratio(&r)), "4.49:1");
}
#[test]
fn black_on_white_is_21_and_grays_fall_either_side_of_aa() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
assert_eq!(r["normalText"], json!({"aa": true, "aaa": true}));
let pass = s.execute("color.contrast", &json!({"color": "#767676", "against": "#ffffff"})).unwrap();
assert!((ratio(&pass) - 4.542).abs() < 1e-3 && pass["normalText"]["aa"] == true, "{pass}");
let fail = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap();
assert!((ratio(&fail) - 4.478).abs() < 1e-3 && fail["normalText"]["aa"] == false, "{fail}");
}
#[test]
fn the_background_is_the_locked_art_behind_the_selected_type() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 80})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffff00"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("text.create", &json!({"x": 60, "y": 70, "text": "Label", "size": 24, "color": "#000000"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ffff00", "{r}");
let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 1.0, 0.0]);
assert!((ratio(&r) - want).abs() < 1e-3, "{r}");
}
#[test]
fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ffffff", "the selected rectangle is hidden: the artboard's white shows");
let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "{r}");
// A given opacity replaces it, and a given color is drawn fully opaque.
let full = s.execute("color.contrast", &json!({"opacity": 100})).unwrap();
assert!((ratio(&full) - 21.0).abs() < 1e-3, "{full}");
let given = s.execute("color.contrast", &json!({"color": "#000000"})).unwrap();
assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}");
}
#[test]
fn a_translucent_group_counts_for_the_art_inside_it() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "the group draws the black at 50 %: {r}");
}
#[test]
fn a_blend_mode_counts_as_it_draws_over_the_background() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ff0000", "{r}");
assert!((ratio(&r) - 1.0).abs() < 1e-3, "white multiplied over red draws red: {r}");
// A group's blend mode counts for the art inside it, and a given color draws in Normal mode.
s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&r) - 1.0).abs() < 1e-3, "{r}");
let given = s.execute("color.contrast", &json!({"color": "#ffffff"})).unwrap();
let want = vectorcraft_color::wcag::contrast_ratio([1.0; 3], [1.0, 0.0, 0.0]);
assert!((ratio(&given) - want).abs() < 1e-3, "{given}");
}
/// A selected blue square at (50, 50) over locked red art, with its fill row's blend mode set to
/// `row`.
fn blended_over_red(row: &str) -> Session {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#4080c0"})).unwrap();
s.execute("transparency.set", &json!({"item": fill_index(&s), "blend": row})).unwrap();
s
}
/// The index of the selected object's fill row.
fn fill_index(s: &Session) -> usize {
let st = s.active().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
n.appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap()
}
/// The contrast against red of the color the canvas draws at the square's center.
fn drawn_ratio(s: &Session) -> f64 {
let doc = &s.doc().unwrap().doc;
let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true);
let p = img.pixel(1, 1);
vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), [1.0, 0.0, 0.0])
}
#[test]
fn nested_blend_modes_count_as_the_canvas_draws_them() {
let mut s = blended_over_red("multiply");
s.execute("transparency.set", &json!({"item": null, "blend": "screen"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ff0000", "{r}");
let drawn = drawn_ratio(&s);
assert!((ratio(&r) - drawn).abs() < 0.02, "the fill multiplies, then the object screens: {r} against {drawn}");
// A translucent row and object: the canvas takes the backdrop back out of a group that blends
// through before it blends the group, so the opacities multiply over the nested modes.
s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
s.execute("transparency.set", &json!({"item": null, "blend": "overlay", "opacity": 70})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let drawn = drawn_ratio(&s);
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
s.execute("transparency.set", &json!({"item": null, "opacity": 100})).unwrap();
// Grouped, the group's mode blends the result again.
s.execute("transparency.set", &json!({"item": null, "blend": "normal"})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let drawn = drawn_ratio(&s);
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// In a 50 % group, a black square over a white one draws black over the black outside: the group's
/// opacity applies to the white behind the square once, not again over it.
#[test]
fn a_translucent_group_draws_the_art_behind_the_object_once() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.active_mut().unwrap().selection.objects = vec![black];
let r = s.execute("color.contrast", &json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true);
let p = img.pixel(1, 1);
let behind = vectorcraft_color::Color::from_hex(r["against"].as_str().unwrap()).unwrap().to_rgb_uncalibrated();
let drawn = vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), behind);
assert!(p[0] < 3, "the canvas draws black: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// The pixel the canvas draws at (100, 100), and its contrast against the answer's `against`.
fn canvas_ratio(s: &Session, r: &Value) -> ([u8; 4], f64) {
let doc = &s.doc().unwrap().doc;
let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true);
let p = img.pixel(1, 1);
let behind = vectorcraft_color::Color::from_hex(r["against"].as_str().unwrap()).unwrap().to_rgb_uncalibrated();
(p, vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), behind))
}
/// A selected white Multiply square over a white one in a 50 % group over black: the square
/// multiplies with the white inside the group, and the group's opacity applies once.
#[test]
fn a_blend_mode_in_a_translucent_group_blends_with_the_art_inside_it() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let back = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
let square = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap();
s.execute("object.group", &json!({"ids": [back.0, square.0]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.active_mut().unwrap().selection.objects = vec![square];
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!((i32::from(p[0]) - 128).abs() < 3, "the canvas draws half gray: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// In a dynamic symbol instance whose art is a 50 % group of a black square over a white one, over
/// black, the picked black square draws over the black outside the group, not over the group's
/// white.
#[test]
fn a_picked_symbol_object_in_a_translucent_group_of_the_art_draws_over_what_is_outside_it() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
let group = id(s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap());
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [group.0], "type": "dynamic"})).unwrap());
let doc = &s.doc().unwrap().doc;
let art = &doc.symbols.iter().find(|x| x.name == "Pair").unwrap().art;
let path = if vectorcraft_doc::symbol_overrides::part(art, &[0, 1]).is_some() { vec![0, 1] } else { vec![1] };
let st = s.active_mut().unwrap();
st.selection.objects = vec![inst];
st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path });
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!(p[0] < 3, "the canvas draws black: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// As above with the group's 50 % set by the instance instead of the symbol, and the picked black
/// square itself at 50 %: the square draws over the group's white, read with the instance's
/// opacity for the group taken out, then the group's 50 % applies once over the black outside.
#[test]
fn an_instances_opacity_for_a_group_of_its_art_applies_once() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let group = id(s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap());
let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [group.0], "type": "dynamic"})).unwrap());
let doc = &s.doc().unwrap().doc;
let art = &doc.symbols.iter().find(|x| x.name == "Pair").unwrap().art;
let path = if vectorcraft_doc::symbol_overrides::part(art, &[0, 1]).is_some() { vec![0, 1] } else { vec![1] };
let st = s.active_mut().unwrap();
let n = std::sync::Arc::make_mut(&mut st.doc).node_mut(inst).unwrap();
let over = vectorcraft_doc::SymbolOverride { path: path[..path.len() - 1].to_vec(), opacity: Some(0.5), ..Default::default() };
n.extras_mut().symbol_overrides = vec![over];
st.selection.objects = vec![inst];
st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path });
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!((i32::from(p[0]) - 64).abs() < 3, "the canvas draws a quarter gray: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// A selected 50 % black square in a 50 % group, over a 50 % white square, all in a Difference group
/// over gray: the inner group's opacity applies to the black square only, and the white beside the
/// inner group counts once in the alpha the Difference group takes the gray back out by.
#[test]
fn a_groups_opacity_leaves_out_the_art_beside_it_in_a_blending_group() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#8c8c8c"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let inner = id(s.execute("object.group", &json!({"ids": [black.0]})).unwrap());
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.execute("object.group", &json!({"ids": [white.0, inner.0]})).unwrap();
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
s.active_mut().unwrap().selection.objects = vec![black];
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
// The canvas pixel is rounded to 8 bits, which moves this dark gray's ratio by up to 0.04; with
// the white counted twice the answer is 3.15.
assert!((ratio(&r) - drawn).abs() < 0.05, "{r} against {drawn} ({p:?})");
}
/// An object that isolates its blending, with a white Multiply fill over a blue one, over red: the
/// white multiplies with the blue row below it.
#[test]
fn a_row_in_an_isolating_object_blends_with_the_rows_below_it() {
let mut s = blended_over_red("normal");
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let st = s.active().unwrap();
let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items;
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "blend": "multiply"})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!(p[0] < 3 && p[2] > 252, "the canvas draws blue: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// An object that isolates its blending, in a Screen group over black: a 50 % white fill over an
/// opaque white one composites to opaque white inside the object, so the group screens opaque
/// white. With the lower fill removed, the object holds the white at 50 %.
#[test]
fn an_isolating_object_in_a_blending_group_carries_the_alpha_of_its_composite() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let square = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let st = s.active().unwrap();
let items = &st.doc.node(square).unwrap().appearance.items;
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
let lower = items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"blend": "screen"})).unwrap();
s.active_mut().unwrap().selection.objects = vec![square];
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!(p[0] > 252 && p[1] > 252 && p[2] > 252, "the canvas draws white: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
assert_eq!(r["normalText"], json!({"aa": true, "aaa": true}), "{r}");
s.execute("appearance.removeItem", &json!({"index": lower})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!((i32::from(p[0]) - 128).abs() < 3, "the canvas draws half gray: {p:?}");
// The canvas pixel is rounded to 8 bits, which moves a ratio near half gray by up to 0.04.
assert!((ratio(&r) - drawn).abs() < 0.05, "{r} against {drawn}");
}
/// A 50 % white fill over an opaque blue one draws over the blue, not over the red art behind it.
#[test]
fn a_translucent_row_draws_over_the_rows_below_it() {
let mut s = blended_over_red("normal");
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let st = s.active().unwrap();
let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items;
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!((i32::from(p[0]) - 128).abs() < 3 && p[2] > 252, "the canvas draws the white at 50 % over the blue: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// A path's Normal fill row and type's character paint draw one black alike.
#[test]
fn a_normal_fill_row_and_type_of_one_color_leave_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
let t = id(s.execute("text.create", &json!({"x": 80, "y": 60, "text": "Label", "size": 24, "color": "#000000"})).unwrap());
s.execute("select.set", &json!({"ids": [a, t]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
}
/// In a group that isolates its blending, a selected white Multiply square blends with the blue
/// art the group holds, and with nothing outside it.
#[test]
fn a_blend_mode_in_an_isolating_group_blends_with_the_art_inside_it_only() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let back = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap());
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
let square = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap();
s.execute("object.group", &json!({"ids": [back.0, square.0]})).unwrap();
s.execute("transparency.set", &json!({"isolate": true})).unwrap();
s.active_mut().unwrap().selection.objects = vec![square];
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!(p[0] < 3 && p[2] > 252, "the canvas draws blue: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
// With the blue art out of the group, the square blends with nothing and draws white over red.
s.execute("select.set", &json!({"ids": [back.0]})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s.active_mut().unwrap().selection.objects = vec![square];
let r = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &r);
assert!(p[1] > 252, "the canvas draws white: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
#[test]
fn template_layers_and_guides_are_left_out_of_the_background() {
let mut s = session();
let first = s.doc().unwrap().doc.layers[0].id;
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("layer.setProps", &json!({"id": first.0, "template": true})).unwrap();
s.execute("layer.new", &json!({"top": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ffffff", "the artboard, without the template's red or the guide: {r}");
}
#[test]
fn objects_that_draw_one_color_differently_have_no_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
s.execute("select.set", &json!({"ids": [b]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}");
s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
// A given opacity takes the place of the objects' own.
let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
// A blend mode that differs is not one a given opacity replaces.
s.execute("select.set", &json!({"ids": [b]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 100, "blend": "multiply"})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ: give `color`"), "{e}");
}
/// A 50 % white row over a blue row in an opaque object draws over the blue; an opaque white row in
/// a 50 % object draws over what is behind it, though both draw the white at 50 %.
#[test]
fn a_row_and_an_object_of_one_total_opacity_draw_differently_over_the_rows_below() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let st = s.active().unwrap();
let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items;
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}");
// A given background stands for the rows below, so both draw the white at 50 % over it.
let r = s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "{r}");
}
/// Two squares with the same 50 % white top fill, one over an opaque black fill and one over an
/// opaque white one, draw the white over different rows: no one answer. Over the same lower fill
/// they leave one answer, also when one of them has a lower row with no paint.
#[test]
fn translucent_rows_over_different_lower_rows_have_no_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let square = |s: &mut Session, x: i32, lower: &str| {
let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap());
s.execute("paint.setFill", &json!({"color": lower})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let st = s.active().unwrap();
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
n
};
let a = square(&mut s, 50, "#000000");
let b = square(&mut s, 100, "#ffffff");
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ"), "{e}");
let c = square(&mut s, 150, "#000000");
s.execute("select.set", &json!({"ids": [a, c]})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
// A row with no paint draws nothing, so it does not count among the rows below.
s.execute("select.set", &json!({"ids": [c]})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let st = s.active().unwrap();
let items = &st.doc.node(vectorcraft_doc::NodeId(c)).unwrap().appearance.items;
let fills: Vec<usize> = items.iter().enumerate().filter(|(_, i)| i.is_fill()).map(|(k, _)| k).collect();
let (middle, top) = (fills[fills.len() - 2], fills[fills.len() - 1]);
s.execute("appearance.setItem", &json!({"ids": [c], "index": top, "color": "#ffffff", "opacity": 50})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [c], "index": middle, "none": true})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
s.execute("select.set", &json!({"ids": [a, c]})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
}
#[test]
fn a_selected_group_whose_objects_draw_one_color_differently_has_no_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
s.execute("select.set", &json!({"ids": [b]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}");
}
#[test]
fn a_hidden_object_in_a_selected_group_leaves_one_answer() {
let id = |v: Value| v["id"].as_u64().unwrap();
// The first and then the second object hidden: the hidden one is neither compared nor measured.
for first in [false, true] {
let mut s = session();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
s.execute("select.set", &json!({"ids": [if first { a } else { b }]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "first hidden {first}: {r}");
}
}
#[test]
fn a_given_color_is_drawn_at_a_given_opacity() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "opacity": 50})).unwrap();
let opaque = s.execute("color.contrast", &json!({"color": "#808080", "against": "#ffffff"})).unwrap();
assert!((ratio(&r) - ratio(&opaque)).abs() < 0.05, "{r} {opaque}");
assert!(ratio(&r) < 5.0, "{r}");
}
#[test]
fn an_opaque_group_around_one_of_the_objects_leaves_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
s.execute("object.group", &json!({"ids": [b]})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
}
#[test]
fn objects_in_two_groups_of_one_opacity_answer_against_a_given_color() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
for o in [a, b] {
let g = id(s.execute("object.group", &json!({"ids": [o]})).unwrap());
s.execute("select.set", &json!({"ids": [g]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
}
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
// Sampled, each group is hidden in turn to read what is outside it, so the two differ.
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}");
}
#[test]
fn a_hidden_fill_row_has_no_color_to_measure() {
let mut s = blended_over_red("normal");
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("appearance.setItem", &json!({"index": fill_index(&s), "visible": false})).unwrap();
let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string();
assert!(e.contains("the active fill or stroke is hidden: give `color`"), "{e}");
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
assert!((ratio(&given) - 21.0).abs() < 1e-6, "{given}");
}
/// An opacity mask on the object, or on a group around it, sets how much of the color shows at each
/// point, so the color has no one opacity to measure; a disabled mask draws nothing.
#[test]
fn a_color_drawn_through_an_opacity_mask_has_no_one_answer() {
let mut s = session();
let rect = |s: &mut Session, color: &str| {
let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"color": color, "ids": [id]})).unwrap();
id
};
let masked = |s: &mut Session, owner: u64, color: &str| {
let m = rect(s, color);
s.execute("select.set", &json!({"ids": [owner, m]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [owner]})).unwrap();
};
let black = rect(&mut s, "#000000");
masked(&mut s, black, "#000000");
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("drawn through an opacity mask: give `color`"), "{e}");
let e = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap_err().to_string();
assert!(e.contains("drawn through an opacity mask"), "{e}");
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
assert!((ratio(&given) - 21.0).abs() < 1e-6, "{given}");
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-3, "a disabled mask leaves the black as it is: {r}");
// A group's mask counts for the objects inside it.
let mut s = session();
let inner = rect(&mut s, "#000000");
let group = s.execute("object.group", &json!({"ids": [inner]})).unwrap()["id"].as_u64().unwrap();
masked(&mut s, group, "#000000");
s.execute("select.set", &json!({"ids": [inner]})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("drawn through an opacity mask"), "{e}");
}
/// A background sampled across an edge averages two colors; the answer's `against` is exactly the
/// background the ratio used, so giving it back answers the same ratio.
#[test]
fn the_background_written_back_answers_the_same_ratio() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80.3, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#2050a0"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap();
let below = s.execute("color.contrast", &json!({})).unwrap();
let hex = below["against"].as_str().unwrap();
assert!(hex != "#ffffff" && hex != "#2050a0", "the sample straddles the edge: {below}");
let given = s.execute("color.contrast", &json!({"against": hex})).unwrap();
assert!((ratio(&below) - ratio(&given)).abs() < 1e-6, "{below} {given}");
}
/// In a 50 % group, a selected black square over a red one draws over the white outside the group,
/// while a given background stands for the art below every level, so giving the answer's `against`
/// back draws the black at 50 % over it instead.
#[test]
fn a_background_given_back_stands_for_the_art_outside_a_translucent_group() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
let red = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.group", &json!({"ids": [red.0, black.0]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.active_mut().unwrap().selection.objects = vec![black];
let below = s.execute("color.contrast", &json!({})).unwrap();
let (_, drawn) = canvas_ratio(&s, &below);
assert!((ratio(&below) - drawn).abs() < 0.02, "{below} against {drawn}");
let hex = below["against"].as_str().unwrap();
let behind = vectorcraft_color::Color::from_hex(hex).unwrap().to_rgb_uncalibrated();
let given = s.execute("color.contrast", &json!({"against": hex})).unwrap();
let want = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::wcag::over([0.0; 3], 0.5, behind), behind);
assert!((ratio(&given) - want).abs() < 1e-3, "{given}");
assert!((ratio(&below) - ratio(&given)).abs() > 0.1, "{below} {given}");
}
#[test]
fn an_object_that_isolates_its_blending_draws_its_fill_as_it_is() {
let mut s = blended_over_red("multiply");
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let drawn = drawn_ratio(&s);
let own = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::Color::from_hex("#4080c0").unwrap().to_rgb_uncalibrated(), [1.0, 0.0, 0.0]);
assert!((drawn - own).abs() < 0.02, "the canvas draws the fill unblended: {drawn} against {own}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// A dynamic symbol instance of a white square in front of a red one, at 50 % opacity, with its
/// white square picked.
fn picked_symbol_part() -> Session {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
let back = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let front = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [back.0, front.0], "type": "dynamic"})).unwrap());
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let st = s.active_mut().unwrap();
st.selection.objects = vec![inst];
st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
s
}
#[test]
fn a_picked_symbol_object_is_measured_against_the_rest_of_its_instance() {
let mut s = picked_symbol_part();
let r = s.execute("color.contrast", &json!({"opacity": 100})).unwrap();
// The red square at 50 % over the artboard's white (#ff7f7f or #ff8080 as the renderer rounds
// it), not the artboard alone.
let hex = r["against"].as_str().unwrap();
let gb = vectorcraft_color::Color::from_hex(hex).unwrap().to_rgb_uncalibrated();
assert!(hex.starts_with("#ff") && (gb[1] - 0.5).abs() < 0.01 && (gb[2] - 0.5).abs() < 0.01, "{r}");
}
#[test]
fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
let mut s = picked_symbol_part();
let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance;
// The instance's fill stains its art half way to black.
s.active_mut().unwrap().selection.symbol_part = None;
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
let n = s.doc().unwrap().doc.node(inst).unwrap().clone();
assert!(vectorcraft_doc::symbol_overrides::stain(&n).is_some_and(|(_, a)| (a - 0.5).abs() < 1e-6));
s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap();
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}");
}
#[test]
fn a_picked_symbol_object_is_drawn_at_its_instances_opacity() {
let mut s = picked_symbol_part();
let r = s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
let gray = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::wcag::over([1.0; 3], 0.5, [0.0; 3]), [0.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "the instance draws the white at 50 %: {r}");
}
#[test]
fn type_measures_its_characters_without_an_appearance_rows_opacity() {
let mut s = session();
s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Label", "size": 24, "color": "#000000"})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let index = s.doc().unwrap().doc.node(s.doc().unwrap().selection.objects[0]).unwrap().appearance.items.len() - 1;
s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-3, "the characters stay opaque black: {r}");
}
#[test]
fn a_gradient_stop_counts_with_its_own_opacity() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
let stops = json!([{"offset": 0, "color": "#000000", "opacity": 0.5}, {"offset": 1, "color": "#ff0000"}]);
s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "the first stop, black at 50 %: {r}");
}
/// Picks the points of the selected gradient mesh inside the box from `a` to `b` with the Lasso tool.
fn pick_points(s: &mut Session, a: (f64, f64), b: (f64, f64)) {
use vectorcraft_tools::{PointerEvent, PointerKind};
let v = ViewInfo::default();
s.select_tool("lasso", v).unwrap();
let pts = [(a.0, a.1), (b.0, a.1), (b.0, b.1), (a.0, b.1), (a.0, b.1)];
for (i, (x, y)) in pts.iter().enumerate() {
let kind = match i {
0 => PointerKind::Down,
4 => PointerKind::Up,
_ => PointerKind::Drag,
};
s.pointer(&PointerEvent::new(kind, *x, *y), v).unwrap();
}
}
#[test]
fn a_picked_mesh_point_counts_with_its_own_opacity() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap();
// The top-left point at 50 %, the top-right one opaque.
pick_points(&mut s, (40.0, 40.0), (60.0, 60.0));
assert_eq!(s.fill_mesh_points().first().map(|(_, v)| v.len()), Some(1), "one point is picked");
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "the picked point, black at 50 %: {r}");
pick_points(&mut s, (140.0, 40.0), (160.0, 60.0));
let r = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-3, "the opaque point: {r}");
// Both picked: one color at two opacities has no one answer, unless `opacity` is given.
pick_points(&mut s, (40.0, 40.0), (160.0, 60.0));
let both = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(both.contains("the selected objects' colors differ: give `opacity` or `color`"), "{both}");
assert!(s.execute("color.contrast", &json!({"opacity": 100})).is_ok());
}
#[test]
fn below_needs_a_selection_and_bad_params_are_errors() {
let mut s = session();
let none = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(none.contains("nothing selected"), "{none}");
// A given background needs no selection: the proxy shows the defaults for new art.
assert!(s.execute("color.contrast", &json!({"against": "#ffffff"})).is_ok());
for bad in [
json!({"color": "#000000", "against": "behind"}),
json!({"color": "#000000", "against": 3}),
json!({"color": "#00000080", "against": "#ffffff"}),
json!({"color": "nope", "against": "#ffffff"}),
json!({"color": "#000000", "against": "#ffffff", "opacity": 101}),
json!({"color": "#000000", "against": "#ffffff", "opacity": -1}),
json!({"color": "#000000", "against": "#ffffff", "opacity": "50"}),
] {
assert!(s.execute("color.contrast", &bad).is_err(), "{bad}");
}
}
#[test]
fn a_fill_of_none_has_no_color_to_measure() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("has no color"), "{e}");
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
}
+26
View File
@@ -939,6 +939,32 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
}
}
/// With a working RGB space other than sRGB, `color.contrast` writes the background in working RGB,
/// the form `against` takes: a given brown comes back as it was given, and the background read
/// behind the selection, given back, answers the same ratio.
#[test]
fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() {
let _g = settings();
let before = cms::active_settings();
let mut s = session();
exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB}));
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"}));
exec(&mut s, "file.new", json!({"width": 200, "height": 200}));
exec(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 80.3, "height": 160}));
exec(&mut s, "paint.setFill", json!({"color": "#2050a0"}));
exec(&mut s, "object.lock", json!({}));
exec(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
exec(&mut s, "paint.setFill", json!({"color": "#808080"}));
let below = s.execute("color.contrast", &json!({}));
let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok());
cms::set_active(&before).unwrap();
let given = given.unwrap();
assert_eq!(given["against"], "#806040", "{given}");
let (below, again) = (below.unwrap(), again.unwrap());
assert_eq!(below["against"], again["against"], "{below} {again}");
assert!((below["ratio"].as_f64().unwrap() - again["ratio"].as_f64().unwrap()).abs() < 1e-9, "{below} {again}");
}
/// View › Proof Setup › Customize's Preserve CMYK Numbers proofs each color from its own inks:
/// with Device CMYK as the working space, C50 M50 Y50 and K50 show as the same gray, and on
/// VectorCraft Generic CMYK they print, and so proof, as different grays; a pattern's tile art
+1 -1
View File
@@ -1597,7 +1597,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, 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: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; 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); 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 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, vision, documentColors}",
"{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; 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 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}",
),
(
"ui.savePdfDialog",
+11
View File
@@ -1741,6 +1741,17 @@ font-technology Variable Променливи
Graphic Styles Графични стилове
Graphic Styles Options Опции за графични стилове
Graphics Графика
Show Contrast Показване на контраста
Contrast For Контраст за
Normal Text Нормален текст
Large Text Голям текст
Contrast Background Фон за контраста
Behind Selection Зад селекцията
Current Color Текущ цвят
Pass Покрива
Fail Не покрива
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимален контраст по WCAG 2.2: нормален текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), голям текст AA 3:1 и AAA 4.5:1, графики и контроли AA 3:1 (1.4.11).
The background is read at the center of the selection. Фонът се отчита в центъра на селекцията.
Graphics Processor Графичен процесор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
Can't render this file because it is too large.
+11
View File
@@ -2105,6 +2105,17 @@ digits Malayalam Malajalam
@msg `Custom` stands for changed settings: save the preset under another name `Custom` označava promijenjene postavke: sačuvajte unaprijed postavljeno pod drugim nazivom
@msg `{key}` must be an array of these names: {_1} `{key}` mora biti niz ovih naziva: {_1}
Graphics Grafika
Show Contrast Prikaži kontrast
Contrast For Kontrast za
Normal Text Normalni tekst
Large Text Veliki tekst
Contrast Background Pozadina kontrasta
Behind Selection Iza odabira
Current Color Trenutna boja
Pass Prolazi
Fail Ne prolazi
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalni kontrast po WCAG 2.2: normalni tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), veliki tekst AA 3:1 i AAA 4.5:1, grafike i kontrole AA 3:1 (1.4.11).
The background is read at the center of the selection. Pozadina se očitava u sredini odabira.
Local Libraries Lokalne biblioteke
Add Content Dodaj sadržaj
Click to apply to the selected type Kliknite da primijenite na odabrani tekst
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -2144,6 +2144,17 @@ digits Malayalam Malaiàlam
Graphic Styles (4) Estils gràfics (4)
Graphic Styles Options Opcions d’estils gràfics
Graphics Gràfics
Show Contrast Mostra el contrast
Contrast For Contrast per a
Normal Text Text normal
Large Text Text gran
Contrast Background Fons del contrast
Behind Selection Darrere la selecció
Current Color Color actual
Pass Supera
Fail No supera
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrast mínim de les WCAG 2.2: text normal AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), text gran AA 3:1 i AAA 4.5:1, gràfics i controls AA 3:1 (1.4.11).
The background is read at the center of the selection. El fons es llegeix al centre de la selecció.
Graphics Processor Processador gràfic
Graphics: {adapter} Gràfics: {adapter}
Gravity Gravetat
@@ -7039,6 +7050,12 @@ liquify-list-end {0}, {1} {0} i {1}
@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no s’ha aplicat res del conjunt de dades {name}: cap objecte està vinculat a una variable per a la qual tingui un valor
@msg no bound object reports a value (locked objects and embedded images report none) cap objecte vinculat no informa d’un valor (els objectes bloquejats i les imatges incrustades no n’informen cap)
@msg nothing selected no hi ha res seleccionat
@msg `{key}` must be a color or {_1} `{key}` ha de ser un color o {_1}
@msg the selected objects' colors differ: give `color` els colors dels objectes seleccionats són diferents: indiqueu `color`
@msg the selected objects' colors differ: give `opacity` or `color` els colors dels objectes seleccionats són diferents: indiqueu `opacity` o `color`
@msg the active fill or stroke has no color: give `color` l’emplenament o el traç actiu no té color: indiqueu `color`
@msg the active fill or stroke is hidden: give `color` l’emplenament o el traç actiu està ocult: indiqueu `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` l’emplenament o el traç actiu es dibuixa a través d’una màscara d’opacitat: indiqueu `color`
@msg nothing to align no hi ha res per alinear
@msg nothing to distort no hi ha res per distorsionar
@msg nothing to export: the document has no visible art (or turn on Use Artboards) no hi ha res per exportar: el document no té art visible (o activeu Utilitza els taulers)
Can't render this file because it is too large.
+17
View File
@@ -2177,6 +2177,17 @@ digits Malayalam Malajálamské
@msg `Custom` stands for changed settings: save the preset under another name `Custom` označuje změněná nastavení: uložte přednastavení pod jiným názvem
@msg `{key}` must be an array of these names: {_1} `{key}` musí být pole těchto názvů: {_1}
Graphics Grafika
Show Contrast Zobrazit kontrast
Contrast For Kontrast pro
Normal Text Normální text
Large Text Velký text
Contrast Background Pozadí kontrastu
Behind Selection Za výběrem
Current Color Aktuální barva
Pass Vyhovuje
Fail Nevyhovuje
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimální kontrast podle WCAG 2.2: normální text AA 4.5:1 (1.4.3) a AAA 7:1 (1.4.6), velký text AA 3:1 a AAA 4.5:1, grafika a ovládací prvky AA 3:1 (1.4.11).
The background is read at the center of the selection. Pozadí se čte uprostřed výběru.
Local Libraries Místní knihovny
Add Content Přidat obsah
Click to apply to the selected type Kliknutím použijete na vybraný text
@@ -5888,6 +5899,12 @@ liquify-list-end {0}, {1} {0} a {1}
@msg finish editing the pattern first nejprve dokončete úpravy vzorku
@msg nothing encoded nic nebylo zakódováno
@msg nothing selected nic není vybráno
@msg `{key}` must be a color or {_1} `{key}` musí být barva nebo {_1}
@msg the selected objects' colors differ: give `color` barvy vybraných objektů se liší: zadejte `color`
@msg the selected objects' colors differ: give `opacity` or `color` barvy vybraných objektů se liší: zadejte `opacity` nebo `color`
@msg the active fill or stroke has no color: give `color` aktivní výplň nebo tah nemá barvu: zadejte `color`
@msg the active fill or stroke is hidden: give `color` aktivní výplň nebo tah je skrytý: zadejte `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` aktivní výplň nebo tah je kreslen přes masku krytí: zadejte `color`
@msg nothing selected is in a group nic z výběru není ve skupině
@msg nothing to align není co zarovnat
@msg nothing to distort není co deformovat
Can't render this file because it is too large.
+11
View File
@@ -4767,6 +4767,17 @@ digits Malayalam Malayalam
Create New Sublayer Opret nyt underlag
Search All Søg i alle
Graphics Grafik
Show Contrast Vis kontrast
Contrast For Kontrast for
Normal Text Normal tekst
Large Text Stor tekst
Contrast Background Kontrastbaggrund
Behind Selection Bag markeringen
Current Color Aktuel farve
Pass Bestået
Fail Ikke bestået
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindstekontrast efter WCAG 2.2: normal tekst AA 4.5:1 (1.4.3) og AAA 7:1 (1.4.6), stor tekst AA 3:1 og AAA 4.5:1, grafik og kontrolelementer AA 3:1 (1.4.11).
The background is read at the center of the selection. Baggrunden aflæses i midten af markeringen.
Local Libraries Lokale biblioteker
Add Content Tilføj indhold
Click to apply to the selected type Klik for at anvende på den markerede tekst
Can't render this file because it is too large.
+17
View File
@@ -1668,6 +1668,17 @@ file-filter Templates Vorlagen
Graphic Styles Grafikstile
Graphic Styles Options Optionen für Grafikstile
Graphics Grafik
Show Contrast Kontrast einblenden
Contrast For Kontrast für
Normal Text Normaler Text
Large Text Großer Text
Contrast Background Kontrasthintergrund
Behind Selection Hinter der Auswahl
Current Color Aktuelle Farbe
Pass Bestanden
Fail Nicht bestanden
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindestkontrast nach WCAG 2.2: normaler Text AA 4.5:1 (1.4.3) und AAA 7:1 (1.4.6), großer Text AA 3:1 und AAA 4.5:1, Grafiken und Bedienelemente AA 3:1 (1.4.11).
The background is read at the center of the selection. Der Hintergrund wird in der Mitte der Auswahl gemessen.
Graphics Processor Grafikprozessor
Graphics: {adapter} Grafik: {adapter}
Gravity Schwerkraft
@@ -5470,6 +5481,12 @@ liquify-list-end {0}, {1} {0} und {1}
@msg finish editing the pattern first beenden Sie zuerst die Bearbeitung des Musters
@msg nothing encoded nichts kodiert
@msg nothing selected nichts ausgewählt
@msg `{key}` must be a color or {_1} `{key}` muss eine Farbe oder {_1} sein
@msg the selected objects' colors differ: give `color` die Farben der ausgewählten Objekte unterscheiden sich: geben Sie `color` an
@msg the selected objects' colors differ: give `opacity` or `color` die Farben der ausgewählten Objekte unterscheiden sich: geben Sie `opacity` oder `color` an
@msg the active fill or stroke has no color: give `color` die aktive Fläche oder Kontur hat keine Farbe: geben Sie `color` an
@msg the active fill or stroke is hidden: give `color` die aktive Fläche oder Kontur ist ausgeblendet: geben Sie `color` an
@msg the active fill or stroke is drawn through an opacity mask: give `color` die aktive Fläche oder Kontur wird durch eine Deckkraftmaske gezeichnet: geben Sie `color` an
@msg nothing selected is in a group nichts Ausgewähltes befindet sich in einer Gruppe
@msg nothing to align nichts auszurichten
@msg nothing to distort nichts zu verzerren
Can't render this file because it is too large.
+17
View File
@@ -1587,6 +1587,17 @@ font-technology Variable Μεταβλητές
Graphic Styles Στυλ γραφικών
Graphic Styles Options Επιλογές στυλ γραφικών
Graphics Γραφικά
Show Contrast Εμφάνιση αντίθεσης
Contrast For Αντίθεση για
Normal Text Κανονικό κείμενο
Large Text Μεγάλο κείμενο
Contrast Background Φόντο αντίθεσης
Behind Selection Πίσω από την επιλογή
Current Color Τρέχον χρώμα
Pass Επιτυχία
Fail Αποτυχία
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Ελάχιστη αντίθεση κατά WCAG 2.2: κανονικό κείμενο AA 4.5:1 (1.4.3) και AAA 7:1 (1.4.6), μεγάλο κείμενο AA 3:1 και AAA 4.5:1, γραφικά και στοιχεία ελέγχου AA 3:1 (1.4.11).
The background is read at the center of the selection. Το φόντο διαβάζεται στο κέντρο της επιλογής.
Graphics Processor Επεξεργαστής γραφικών
Graphics: {adapter} Γραφικά: {adapter}
Gravity Βαρύτητα
@@ -5529,6 +5540,12 @@ digits Malayalam Μαλαγιάλαμ
@msg finish editing the pattern first ολοκληρώστε πρώτα την επεξεργασία του μοτίβου
@msg nothing encoded δεν κωδικοποιήθηκε τίποτα
@msg nothing selected δεν έχει επιλεγεί τίποτα
@msg `{key}` must be a color or {_1} το `{key}` πρέπει να είναι χρώμα ή {_1}
@msg the selected objects' colors differ: give `color` τα χρώματα των επιλεγμένων αντικειμένων διαφέρουν: δώστε `color`
@msg the selected objects' colors differ: give `opacity` or `color` τα χρώματα των επιλεγμένων αντικειμένων διαφέρουν: δώστε `opacity` ή `color`
@msg the active fill or stroke has no color: give `color` το ενεργό γέμισμα ή η πινελιά δεν έχει χρώμα: δώστε `color`
@msg the active fill or stroke is hidden: give `color` το ενεργό γέμισμα ή η πινελιά είναι κρυφό: δώστε `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` το ενεργό γέμισμα ή η πινελιά σχεδιάζεται μέσα από μάσκα αδιαφάνειας: δώστε `color`
@msg nothing selected is in a group τίποτα από τα επιλεγμένα δεν βρίσκεται σε ομάδα
@msg nothing to align δεν υπάρχει τίποτα για στοίχιση
@msg nothing to distort δεν υπάρχει τίποτα για παραμόρφωση
Can't render this file because it is too large.
+17
View File
@@ -1677,6 +1677,17 @@ font-technology Variable Variables
Graphic Styles Estilos gráficos
Graphic Styles Options Opciones de estilos gráficos
Graphics Gráficos
Show Contrast Mostrar contraste
Contrast For Contraste para
Normal Text Texto normal
Large Text Texto grande
Contrast Background Fondo del contraste
Behind Selection Detrás de la selección
Current Color Color actual
Pass Cumple
Fail No cumple
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo de WCAG 2.2: texto normal AA 4.5:1 (1.4.3) y AAA 7:1 (1.4.6), texto grande AA 3:1 y AAA 4.5:1, gráficos y controles AA 3:1 (1.4.11).
The background is read at the center of the selection. El fondo se lee en el centro de la selección.
Graphics Processor Procesador gráfico
Graphics: {adapter} Gráficos: {adapter}
Gravity Gravedad
@@ -5579,6 +5590,12 @@ liquify-list-end {0}, {1} {0}, {1}
@msg finish editing the pattern first termina primero la edición del motivo
@msg nothing encoded no se codificó nada
@msg nothing selected no hay nada seleccionado
@msg `{key}` must be a color or {_1} `{key}` debe ser un color o {_1}
@msg the selected objects' colors differ: give `color` los colores de los objetos seleccionados difieren: indique `color`
@msg the selected objects' colors differ: give `opacity` or `color` los colores de los objetos seleccionados difieren: indique `opacity` o `color`
@msg the active fill or stroke has no color: give `color` el relleno o trazo activo no tiene color: indique `color`
@msg the active fill or stroke is hidden: give `color` el relleno o trazo activo está oculto: indique `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` el relleno o trazo activo se dibuja a través de una máscara de opacidad: indique `color`
@msg nothing selected is in a group nada de lo seleccionado está en un grupo
@msg nothing to align no hay nada que alinear
@msg nothing to distort no hay nada que distorsionar
Can't render this file because it is too large.
+17
View File
@@ -2136,6 +2136,17 @@ digits Malayalam Malajalam
Create New Sublayer Luo uusi alataso
Search All Hae kaikista
Graphics Grafiikka
Show Contrast Näytä kontrasti
Contrast For Kontrasti kohteelle
Normal Text Tavallinen teksti
Large Text Suuri teksti
Contrast Background Kontrastin tausta
Behind Selection Valinnan takana
Current Color Nykyinen väri
Pass Läpäisee
Fail Ei läpäise
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2:n vähimmäiskontrastit: tavallinen teksti AA 4.5:1 (1.4.3) ja AAA 7:1 (1.4.6), suuri teksti AA 3:1 ja AAA 4.5:1, grafiikka ja säätimet AA 3:1 (1.4.11).
The background is read at the center of the selection. Tausta luetaan valinnan keskeltä.
Local Libraries Paikalliset kirjastot
Add Content Lisää sisältöä
Click to apply to the selected type Käytä valittuun tekstiin napsauttamalla
@@ -5809,6 +5820,12 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg finish editing the pattern first lopeta ensin kuvion muokkaus
@msg nothing encoded mitään ei koodattu
@msg nothing selected mitään ei ole valittu
@msg `{key}` must be a color or {_1} `{key}` on oltava väri tai {_1}
@msg the selected objects' colors differ: give `color` valittujen objektien värit eroavat: anna `color`
@msg the selected objects' colors differ: give `opacity` or `color` valittujen objektien värit eroavat: anna `opacity` tai `color`
@msg the active fill or stroke has no color: give `color` aktiivisella täytöllä tai viivalla ei ole väriä: anna `color`
@msg the active fill or stroke is hidden: give `color` aktiivinen täyttö tai viiva on piilotettu: anna `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` aktiivinen täyttö tai viiva piirretään peittävyysmaskin läpi: anna `color`
@msg nothing selected is in a group mikään valituista ei ole ryhmässä
@msg nothing to align ei tasattavaa
@msg nothing to distort ei vääristettävää
Can't render this file because it is too large.
+17
View File
@@ -1667,6 +1667,17 @@ font-technology Variable Variables
Graphic Styles Styles graphiques
Graphic Styles Options Options des styles graphiques
Graphics Graphiques
Show Contrast Afficher le contraste
Contrast For Contraste pour
Normal Text Texte normal
Large Text Grand texte
Contrast Background Arrière-plan du contraste
Behind Selection Derrière la sélection
Current Color Couleur actuelle
Pass Réussi
Fail Échec
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste minimal WCAG 2.2 : texte normal AA 4.5:1 (1.4.3) et AAA 7:1 (1.4.6), grand texte AA 3:1 et AAA 4.5:1, graphiques et commandes AA 3:1 (1.4.11).
The background is read at the center of the selection. L’arrière-plan est lu au centre de la sélection.
Graphics Processor Processeur graphique
Graphics: {adapter} Carte graphique : {adapter}
Gravity Gravité
@@ -5536,6 +5547,12 @@ liquify-list-end {0}, {1} {0} et {1}
@msg finish editing the pattern first terminez d’abord la modification du motif
@msg nothing encoded rien n’a été encodé
@msg nothing selected aucune sélection
@msg `{key}` must be a color or {_1} `{key}` doit être une couleur ou {_1}
@msg the selected objects' colors differ: give `opacity` or `color` les couleurs des objets sélectionnés diffèrent : indiquez `opacity` ou `color`
@msg the selected objects' colors differ: give `color` les couleurs des objets sélectionnés diffèrent : indiquez `color`
@msg the active fill or stroke has no color: give `color` le fond ou le contour actif n’a pas de couleur : indiquez `color`
@msg the active fill or stroke is hidden: give `color` le fond ou le contour actif est masqué : indiquez `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` le fond ou le contour actif est dessiné à travers un masque d’opacité : indiquez `color`
@msg nothing selected is in a group aucun élément sélectionné ne se trouve dans un groupe
@msg nothing to align rien à aligner
@msg nothing to distort rien à déformer
Can't render this file because it is too large.
+12
View File
@@ -1730,6 +1730,18 @@
Graphic Styles ગ્રાફિક સ્ટાઇલ્સ
Graphic Styles Options ગ્રાફિક સ્ટાઇલ્સ વિકલ્પો
Graphics ગ્રાફિક્સ
Contrast કોન્ટ્રાસ્ટ
Show Contrast કોન્ટ્રાસ્ટ બતાવો
Contrast For આના માટે કોન્ટ્રાસ્ટ
Normal Text સામાન્ય ટેક્સ્ટ
Large Text મોટું ટેક્સ્ટ
Contrast Background કોન્ટ્રાસ્ટ પૃષ્ઠભૂમિ
Behind Selection પસંદગીની પાછળ
Current Color વર્તમાન રંગ
Pass પાસ
Fail નાપાસ
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 લઘુત્તમ કોન્ટ્રાસ્ટ: સામાન્ય ટેક્સ્ટ AA 4.5:1 (1.4.3) અને AAA 7:1 (1.4.6), મોટું ટેક્સ્ટ AA 3:1 અને AAA 4.5:1, ગ્રાફિક્સ અને નિયંત્રણો AA 3:1 (1.4.11).
The background is read at the center of the selection. પૃષ્ઠભૂમિ પસંદગીના કેન્દ્રમાં વાંચવામાં આવે છે.
Graphics Processor ગ્રાફિક્સ પ્રોસેસર
Graphics: {adapter} ગ્રાફિક્સ: {adapter}
Gravity ગ્રેવિટી
Can't render this file because it contains an unexpected character in line 72 and column 5.
+17
View File
@@ -2618,6 +2618,17 @@ arrowhead Feather पंख
Graphic Styles (4) ग्राफिक स्टाइल्स (4)
Graphic Styles Options ग्राफ़िक स्टाइल ऑप्शन्स
Graphics ग्राफ़िक्स
Show Contrast कंट्रास्ट दिखाएँ
Contrast For इसके लिए कंट्रास्ट
Normal Text सामान्य टेक्स्ट
Large Text बड़ा टेक्स्ट
Contrast Background कंट्रास्ट पृष्ठभूमि
Behind Selection सिलेक्शन के पीछे
Current Color मौजूदा रंग
Pass पास
Fail फ़ेल
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 न्यूनतम कंट्रास्ट: सामान्य टेक्स्ट AA 4.5:1 (1.4.3) और AAA 7:1 (1.4.6), बड़ा टेक्स्ट AA 3:1 और AAA 4.5:1, ग्राफ़िक्स और कंट्रोल AA 3:1 (1.4.11)।
The background is read at the center of the selection. पृष्ठभूमि सिलेक्शन के केंद्र पर पढ़ी जाती है।
Graphics Processor ग्राफिक्स प्रोसेसर
Graphics: {adapter} ग्राफिक्स: {adapter}
Gravity ग्रेविटी
@@ -8684,6 +8695,12 @@ liquify-list-end {0}, {1} {0} और {1}
@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for डेटा सेट {name} से कुछ भी लागू नहीं हुआ: उसमें मान वाले किसी भी वेरिएबल से कोई ऑब्जेक्ट नहीं बाँधा गया है
@msg nothing prints कुछ भी प्रिंट
@msg nothing selected कुछ भी नहीं चुना
@msg `{key}` must be a color or {_1} `{key}` कोई रंग या {_1} होना चाहिए
@msg the selected objects' colors differ: give `color` चुने गए ऑब्जेक्ट्स के रंग अलग-अलग हैं: `color` दें
@msg the selected objects' colors differ: give `opacity` or `color` चुने गए ऑब्जेक्ट्स के रंग अलग-अलग हैं: `opacity` या `color` दें
@msg the active fill or stroke has no color: give `color` सक्रिय फ़िल या स्ट्रोक में कोई रंग नहीं है: `color` दें
@msg the active fill or stroke is hidden: give `color` सक्रिय फ़िल या स्ट्रोक छिपा हुआ है: `color` दें
@msg the active fill or stroke is drawn through an opacity mask: give `color` सक्रिय फ़िल या स्ट्रोक ओपेसिटी मास्क से होकर बनाया जाता है: `color` दें
@msg nothing selected is in a group कुछ भी नहीं चुना गया है एक समूह में
@msg nothing to align संरेखित करने के लिए कुछ नहीं
@msg nothing to bind बाध्य करने के लिए कुछ नहीं
Can't render this file because it is too large.
+17
View File
@@ -2071,6 +2071,17 @@ file-filter Templates Sablonok
Graphic Styles (4) Grafikai stílusok (4)
Graphic Styles Options Grafikai stílusok beállításai
Graphics Grafikák
Show Contrast Kontraszt megjelenítése
Contrast For Kontraszt ehhez
Normal Text Normál szöveg
Large Text Nagy szöveg
Contrast Background Kontraszt háttere
Behind Selection A kijelölés mögött
Current Color Aktuális szín
Pass Megfelel
Fail Nem felel meg
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 szerinti minimális kontraszt: normál szöveg AA 4.5:1 (1.4.3) és AAA 7:1 (1.4.6), nagy szöveg AA 3:1 és AAA 4.5:1, grafikák és vezérlők AA 3:1 (1.4.11).
The background is read at the center of the selection. A háttér színét a kijelölés közepén olvassa le a program.
Graphics Processor Grafikus processzor
Graphics: {adapter} Grafika: {adapter}
Gravity Gravitáció
@@ -6277,6 +6288,12 @@ liquify-list-end {0}, {1} {0} és {1}
@msg finish editing the pattern first előbb fejezd be a mintázat szerkesztését
@msg nothing encoded nincs kódolt adat
@msg nothing selected nincs kijelölés
@msg `{key}` must be a color or {_1} a(z) `{key}` értéke csak szín vagy {_1} lehet
@msg the selected objects' colors differ: give `color` a kijelölt objektumok színei eltérnek: adja meg a `color` értékét
@msg the selected objects' colors differ: give `opacity` or `color` a kijelölt objektumok színei eltérnek: adja meg az `opacity` vagy a `color` értékét
@msg the active fill or stroke has no color: give `color` az aktív kitöltésnek vagy körvonalnak nincs színe: adja meg a `color` értékét
@msg the active fill or stroke is hidden: give `color` az aktív kitöltés vagy körvonal rejtett: adja meg a `color` értékét
@msg the active fill or stroke is drawn through an opacity mask: give `color` az aktív kitöltés vagy körvonal átlátszósági maszkon keresztül rajzolódik: adja meg a `color` értékét
@msg nothing selected is in a group a kijelölésből semmi sincs csoportban
@msg nothing to align nincs mit igazítani
@msg nothing to distort nincs mit torzítani
Can't render this file because it is too large.
+11
View File
@@ -2644,6 +2644,17 @@ digits Malayalam Malayalam
Create New Sublayer Buat sublapisan baru
Search All Cari semua
Graphics Grafis
Show Contrast Tampilkan kontras
Contrast For Kontras untuk
Normal Text Teks normal
Large Text Teks besar
Contrast Background Latar kontras
Behind Selection Di belakang seleksi
Current Color Warna saat ini
Pass Lulus
Fail Gagal
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Kontras minimum WCAG 2.2: teks normal AA 4.5:1 (1.4.3) dan AAA 7:1 (1.4.6), teks besar AA 3:1 dan AAA 4.5:1, grafis dan kontrol AA 3:1 (1.4.11).
The background is read at the center of the selection. Latar dibaca di tengah seleksi.
Local Libraries Pustaka lokal
Add Content Tambahkan konten
Click to apply to the selected type Klik untuk menerapkan ke teks terpilih
Can't render this file because it is too large.
+17
View File
@@ -1705,6 +1705,17 @@ file-filter Templates Modelli
Graphic Styles Stili grafici
Graphic Styles Options Opzioni stili grafici
Graphics Grafica
Show Contrast Mostra contrasto
Contrast For Contrasto per
Normal Text Testo normale
Large Text Testo grande
Contrast Background Sfondo del contrasto
Behind Selection Dietro la selezione
Current Color Colore corrente
Pass Superato
Fail Non superato
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrasto minimo WCAG 2.2: testo normale AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), testo grande AA 3:1 e AAA 4.5:1, grafica e controlli AA 3:1 (1.4.11).
The background is read at the center of the selection. Lo sfondo viene letto al centro della selezione.
Graphics Processor Processore grafico
Graphics: {adapter} Scheda grafica: {adapter}
Gravity Gravità
@@ -5607,6 +5618,12 @@ liquify-list-end {0}, {1} {0} e {1}
@msg finish editing the pattern first termina prima la modifica del motivo
@msg nothing encoded nessun dato codificato
@msg nothing selected nessuna selezione
@msg `{key}` must be a color or {_1} `{key}` deve essere un colore o {_1}
@msg the selected objects' colors differ: give `color` i colori degli oggetti selezionati sono diversi: indica `color`
@msg the selected objects' colors differ: give `opacity` or `color` i colori degli oggetti selezionati sono diversi: indica `opacity` o `color`
@msg the active fill or stroke has no color: give `color` il riempimento o la traccia attivi non hanno colore: indica `color`
@msg the active fill or stroke is hidden: give `color` il riempimento o la traccia attivi sono nascosti: indica `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` il riempimento o la traccia attivi sono disegnati attraverso una maschera di opacità: indica `color`
@msg nothing selected is in a group nessun elemento selezionato si trova in un gruppo
@msg nothing to align niente da allineare
@msg nothing to distort niente da distorcere
Can't render this file because it is too large.
+17
View File
@@ -4443,6 +4443,17 @@ file-filter Templates テンプレート
Stacked 積み重ね
Graphic Style Libraries Menu グラフィックスタイルライブラリメニュー
Graphics グラフィックス
Show Contrast コントラストを表示
Contrast For コントラストの対象
Normal Text 通常のテキスト
Large Text 大きなテキスト
Contrast Background コントラストの背景
Behind Selection 選択範囲の背後
Current Color 現在のカラー
Pass 合格
Fail 不合格
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 の最小コントラスト:通常のテキスト AA 4.5:1 (1.4.3) と AAA 7:1 (1.4.6)、大きなテキスト AA 3:1 と AAA 4.5:1、グラフィックとコントロール AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景は選択範囲の中央で読み取ります。
Greek & Cyrillic ギリシャ文字とキリル文字
Hex by Column 六角形 (列)
Hex by Row 六角形 (行)
@@ -6063,6 +6074,12 @@ liquify-list-end {0}, {1} {0}、{1}
@msg Couldn't paste from the clipboard: {e} クリップボードから貼り付けられませんでした: {e}
@msg Couldn't paste: the document it was pasted in was closed 貼り付けられませんでした: 貼り付け先のドキュメントは閉じられています
@msg nothing selected 何も選択されていません
@msg `{key}` must be a color or {_1} `{key}` はカラーまたは {_1} である必要があります
@msg the selected objects' colors differ: give `color` 選択したオブジェクトのカラーが異なります:`color` を指定してください
@msg the selected objects' colors differ: give `opacity` or `color` 選択したオブジェクトのカラーが異なります:`opacity` または `color` を指定してください
@msg the active fill or stroke has no color: give `color` アクティブな塗りまたは線にカラーがありません:`color` を指定してください
@msg the active fill or stroke is hidden: give `color` アクティブな塗りまたは線が非表示です:`color` を指定してください
@msg the active fill or stroke is drawn through an opacity mask: give `color` アクティブな塗りまたは線は不透明マスクを通して描画されます:`color` を指定してください
@msg nothing selected is in a group 選択したオブジェクトはどれもグループ内にありません
@msg the {tool} tool has no options {tool} ツールにはオプションがありません
@msg unknown tool `{tool}` `{tool}` は不明なツールです
Can't render this file because it is too large.
+17
View File
@@ -4119,6 +4119,17 @@ digits Malayalam მალაიალამური
Create New Sublayer ახალი ქვეშრის შექმნა
Search All ყველგან ძიება
Graphics გრაფიკა
Show Contrast კონტრასტის ჩვენება
Contrast For კონტრასტი ამისთვის
Normal Text ჩვეულებრივი ტექსტი
Large Text დიდი ტექსტი
Contrast Background კონტრასტის ფონი
Behind Selection მონიშნულის უკან
Current Color მიმდინარე ფერი
Pass აკმაყოფილებს
Fail არ აკმაყოფილებს
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2-ის მინიმალური კონტრასტი: ჩვეულებრივი ტექსტი AA 4.5:1 (1.4.3) და AAA 7:1 (1.4.6), დიდი ტექსტი AA 3:1 და AAA 4.5:1, გრაფიკა და მართვის ელემენტები AA 3:1 (1.4.11).
The background is read at the center of the selection. ფონი იკითხება მონიშნულის ცენტრში.
Local Libraries ლოკალური ბიბლიოთეკები
Add Content შიგთავსის დამატება
Click to apply to the selected type დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად
@@ -7335,6 +7346,12 @@ font-technology Variable ცვლადი
@msg finish editing the pattern first ჯერ დაასრულეთ პატერნის რედაქტირება
@msg nothing encoded არაფერია კოდირებული
@msg nothing selected არაფერია მონიშნული
@msg `{key}` must be a color or {_1} `{key}` უნდა იყოს ფერი ან {_1}
@msg the selected objects' colors differ: give `color` მონიშნული ობიექტების ფერები განსხვავდება: მიუთითეთ `color`
@msg the selected objects' colors differ: give `opacity` or `color` მონიშნული ობიექტების ფერები განსხვავდება: მიუთითეთ `opacity` ან `color`
@msg the active fill or stroke has no color: give `color` აქტიურ შევსებას ან კონტურს ფერი არ აქვს: მიუთითეთ `color`
@msg the active fill or stroke is hidden: give `color` აქტიური შევსება ან კონტური დამალულია: მიუთითეთ `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` აქტიური შევსება ან კონტური იხატება გაუმჭვირვალობის ნიღბით: მიუთითეთ `color`
@msg nothing selected is in a group მონიშნულთაგან არაფერია ჯგუფში
@msg nothing to align გასასწორებელი არაფერია
@msg nothing to distort დასადეფორმირებელი არაფერია
Can't render this file because it is too large.
+17
View File
@@ -4433,6 +4433,17 @@ file-filter Templates 템플릿
Stacked 누적
Graphic Style Libraries Menu 그래픽 스타일 라이브러리 메뉴
Graphics 그래픽
Show Contrast 대비 표시
Contrast For 대비 기준
Normal Text 일반 텍스트
Large Text 큰 텍스트
Contrast Background 대비 배경
Behind Selection 선택 영역 뒤
Current Color 현재 색상
Pass 통과
Fail 실패
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 최소 대비: 일반 텍스트 AA 4.5:1 (1.4.3) 및 AAA 7:1 (1.4.6), 큰 텍스트 AA 3:1 및 AAA 4.5:1, 그래픽과 컨트롤 AA 3:1 (1.4.11).
The background is read at the center of the selection. 배경은 선택 영역의 중앙에서 읽습니다.
Greek & Cyrillic 그리스어 및 키릴 문자
Hex by Column 열 기준 육각형
Hex by Row 행 기준 육각형
@@ -5992,6 +6003,12 @@ liquify-list-end {0}, {1} {0} 및 {1}
@msg Couldn't paste from the clipboard: {e} 클립보드에서 붙여넣을 수 없습니다: {e}
@msg Couldn't paste: the document it was pasted in was closed 붙여넣을 수 없습니다: 붙여넣던 문서가 닫혔습니다
@msg nothing selected 선택된 항목이 없습니다
@msg `{key}` must be a color or {_1} `{key}`은(는) 색상 또는 {_1}이어야 합니다
@msg the selected objects' colors differ: give `color` 선택한 개체의 색상이 서로 다릅니다: `color`를 지정하세요
@msg the selected objects' colors differ: give `opacity` or `color` 선택한 개체의 색상이 서로 다릅니다: `opacity` 또는 `color`를 지정하세요
@msg the active fill or stroke has no color: give `color` 활성 칠 또는 획에 색상이 없습니다: `color`를 지정하세요
@msg the active fill or stroke is hidden: give `color` 활성 칠 또는 획이 숨겨져 있습니다: `color`를 지정하세요
@msg the active fill or stroke is drawn through an opacity mask: give `color` 활성 칠 또는 획이 불투명 마스크를 통해 그려집니다: `color`를 지정하세요
@msg nothing selected is in a group 선택한 항목 중 그룹에 속한 항목이 없습니다
@msg the {tool} tool has no options {tool} 도구에는 옵션이 없습니다
@msg unknown tool `{tool}` 알 수 없는 도구 `{tool}`
Can't render this file because it is too large.
+17
View File
@@ -2630,6 +2630,17 @@ digits Malayalam Malayalam
Create New Sublayer Nieuwe sublaag maken
Search All Alles doorzoeken
Graphics Illustraties
Show Contrast Contrast tonen
Contrast For Contrast voor
Normal Text Normale tekst
Large Text Grote tekst
Contrast Background Contrastachtergrond
Behind Selection Achter selectie
Current Color Huidige kleur
Pass Geslaagd
Fail Niet geslaagd
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimumcontrast volgens WCAG 2.2: normale tekst AA 4.5:1 (1.4.3) en AAA 7:1 (1.4.6), grote tekst AA 3:1 en AAA 4.5:1, illustraties en bedieningselementen AA 3:1 (1.4.11).
The background is read at the center of the selection. De achtergrond wordt in het midden van de selectie gemeten.
Local Libraries Lokale bibliotheken
Add Content Inhoud toevoegen
Click to apply to the selected type Klik om toe te passen op de geselecteerde tekst
@@ -5970,6 +5981,12 @@ imageTrace Outline Contour
@msg finish editing the pattern first rond eerst het bewerken van het patroon af
@msg nothing encoded niets gecodeerd
@msg nothing selected niets geselecteerd
@msg `{key}` must be a color or {_1} `{key}` moet een kleur of {_1} zijn
@msg the selected objects' colors differ: give `color` de kleuren van de geselecteerde objecten verschillen: geef `color` op
@msg the selected objects' colors differ: give `opacity` or `color` de kleuren van de geselecteerde objecten verschillen: geef `opacity` of `color` op
@msg the active fill or stroke has no color: give `color` de actieve vulling of lijn heeft geen kleur: geef `color` op
@msg the active fill or stroke is hidden: give `color` de actieve vulling of lijn is verborgen: geef `color` op
@msg the active fill or stroke is drawn through an opacity mask: give `color` de actieve vulling of lijn wordt door een dekkingmasker getekend: geef `color` op
@msg nothing selected is in a group niets van de selectie zit in een groep
@msg nothing to align niets om uit te lijnen
@msg nothing to distort niets om te vervormen
Can't render this file because it is too large.
+17
View File
@@ -2095,6 +2095,17 @@ digits Malayalam Malajalam
@msg `Custom` stands for changed settings: save the preset under another name `Custom` oznacza zmienione ustawienia: zapisz ustawienie pod inną nazwą
@msg `{key}` must be an array of these names: {_1} `{key}` musi być tablicą tych nazw: {_1}
Graphics Grafiki
Show Contrast Pokaż kontrast
Contrast For Kontrast dla
Normal Text Zwykły tekst
Large Text Duży tekst
Contrast Background Tło kontrastu
Behind Selection Za zaznaczeniem
Current Color Bieżący kolor
Pass Spełnia
Fail Nie spełnia
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalny kontrast według WCAG 2.2: zwykły tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), duży tekst AA 3:1 i AAA 4.5:1, grafika i elementy sterujące AA 3:1 (1.4.11).
The background is read at the center of the selection. Tło jest odczytywane na środku zaznaczenia.
Local Libraries Biblioteki lokalne
Add Content Dodaj zawartość
Click to apply to the selected type Kliknij, aby zastosować do zaznaczonego tekstu
@@ -5709,6 +5720,12 @@ liquify-list-end {0}, {1} {0} i {1}
@msg finish editing the pattern first najpierw zakończ edycję wzorka
@msg nothing encoded nic nie zakodowano
@msg nothing selected nic nie zaznaczono
@msg `{key}` must be a color or {_1} `{key}` musi być kolorem lub {_1}
@msg the selected objects' colors differ: give `color` kolory zaznaczonych obiektów się różnią: podaj `color`
@msg the selected objects' colors differ: give `opacity` or `color` kolory zaznaczonych obiektów się różnią: podaj `opacity` lub `color`
@msg the active fill or stroke has no color: give `color` aktywne wypełnienie lub obrys nie ma koloru: podaj `color`
@msg the active fill or stroke is hidden: give `color` aktywne wypełnienie lub obrys jest ukryte: podaj `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` aktywne wypełnienie lub obrys jest rysowane przez maskę krycia: podaj `color`
@msg nothing selected is in a group nic z zaznaczenia nie należy do grupy
@msg nothing to align nie ma czego wyrównać
@msg nothing to distort nie ma czego zniekształcić
Can't render this file because it is too large.
+17
View File
@@ -4125,6 +4125,17 @@ font-technology Variable Variáveis
Symbol Set Density: Densidade do conjunto de símbolos:
Flatten Artwork Achatar arte-final
Graphics Gráficos
Show Contrast Mostrar Contraste
Contrast For Contraste Para
Normal Text Texto Normal
Large Text Texto Grande
Contrast Background Fundo do Contraste
Behind Selection Atrás da Seleção
Current Color Cor Atual
Pass Aprovado
Fail Reprovado
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo da WCAG 2.2: texto normal AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), texto grande AA 3:1 e AAA 4.5:1, gráficos e controles AA 3:1 (1.4.11).
The background is read at the center of the selection. O fundo é lido no centro da seleção.
Highlight Rows Destacar linhas
Highlight Variable Destacar variável
Sort Variables Ordenar variáveis
@@ -4843,6 +4854,12 @@ axis Both Ambos
@msg finish editing the pattern first termine de editar o padrão primeiro
@msg nothing encoded nada codificado
@msg nothing selected nada selecionado
@msg `{key}` must be a color or {_1} `{key}` deve ser uma cor ou {_1}
@msg the selected objects' colors differ: give `color` as cores dos objetos selecionados são diferentes: informe `color`
@msg the selected objects' colors differ: give `opacity` or `color` as cores dos objetos selecionados são diferentes: informe `opacity` ou `color`
@msg the active fill or stroke has no color: give `color` o preenchimento ou traçado ativo não tem cor: informe `color`
@msg the active fill or stroke is hidden: give `color` o preenchimento ou traçado ativo está oculto: informe `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` o preenchimento ou traçado ativo é desenhado através de uma máscara de opacidade: informe `color`
@msg nothing selected is in a group nada do que está selecionado está em um grupo
@msg nothing to align nada para alinhar
@msg nothing to distort nada para distorcer
Can't render this file because it is too large.
+17
View File
@@ -1690,6 +1690,17 @@ file-filter Templates Шаблоны
Graphic Styles Графические стили
Graphic Styles Options Параметры графических стилей
Graphics Графика
Show Contrast Показать контраст
Contrast For Контраст для
Normal Text Обычный текст
Large Text Крупный текст
Contrast Background Фон контраста
Behind Selection За выделением
Current Color Текущий цвет
Pass Соответствует
Fail Не соответствует
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимальный контраст по WCAG 2.2: обычный текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), крупный текст AA 3:1 и AAA 4.5:1, графика и элементы управления AA 3:1 (1.4.11).
The background is read at the center of the selection. Фон определяется в центре выделения.
Graphics Processor Графический процессор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
@@ -5602,6 +5613,12 @@ liquify-list-end {0}, {1} {0} и {1}
@msg finish editing the pattern first сначала завершите редактирование узора
@msg nothing encoded ничего не закодировано
@msg nothing selected ничего не выделено
@msg `{key}` must be a color or {_1} `{key}` должен быть цветом или {_1}
@msg the selected objects' colors differ: give `color` цвета выделенных объектов различаются: укажите `color`
@msg the selected objects' colors differ: give `opacity` or `color` цвета выделенных объектов различаются: укажите `opacity` или `color`
@msg the active fill or stroke has no color: give `color` у активной заливки или обводки нет цвета: укажите `color`
@msg the active fill or stroke is hidden: give `color` активная заливка или обводка скрыта: укажите `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` активная заливка или обводка рисуется через непрозрачную маску: укажите `color`
@msg nothing selected is in a group ничего из выделенного не находится в группе
@msg nothing to align нечего выравнивать
@msg nothing to distort нечего искажать
Can't render this file because it is too large.
+17
View File
@@ -1624,6 +1624,17 @@ font-technology Variable Variabla
Graphic Styles Grafikstilar
Graphic Styles Options Grafikstilalternativ
Graphics Grafik
Show Contrast Visa kontrast
Contrast For Kontrast för
Normal Text Normal text
Large Text Stor text
Contrast Background Kontrastbakgrund
Behind Selection Bakom markeringen
Current Color Aktuell färg
Pass Godkänd
Fail Underkänd
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minsta kontrast enligt WCAG 2.2: normal text AA 4.5:1 (1.4.3) och AAA 7:1 (1.4.6), stor text AA 3:1 och AAA 4.5:1, grafik och kontroller AA 3:1 (1.4.11).
The background is read at the center of the selection. Bakgrunden läses i mitten av markeringen.
Graphics Processor Grafikprocessor
Graphics: {adapter} Grafik: {adapter}
Gravity Gravitation
@@ -5462,6 +5473,12 @@ liquify-list-end {0}, {1} {0} och {1}
@msg finish editing the pattern first slutför redigeringen av mönstret först
@msg nothing encoded inget kodat
@msg nothing selected inget markerat
@msg `{key}` must be a color or {_1} `{key}` måste vara en färg eller {_1}
@msg the selected objects' colors differ: give `color` de markerade objektens färger skiljer sig: ange `color`
@msg the selected objects' colors differ: give `opacity` or `color` de markerade objektens färger skiljer sig: ange `opacity` eller `color`
@msg the active fill or stroke has no color: give `color` den aktiva fyllningen eller linjen har ingen färg: ange `color`
@msg the active fill or stroke is hidden: give `color` den aktiva fyllningen eller linjen är dold: ange `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` den aktiva fyllningen eller linjen ritas genom en opacitetsmask: ange `color`
@msg nothing selected is in a group inget av det markerade ligger i en grupp
@msg nothing to align inget att justera
@msg nothing to distort inget att förvränga
Can't render this file because it is too large.
+17
View File
@@ -1588,6 +1588,17 @@ font-technology Variable Değişken
Graphic Styles Grafik Stilleri
Graphic Styles Options Grafik Stilleri Seçenekleri
Graphics Grafik
Show Contrast Kontrastı Göster
Contrast For Kontrast Hedefi
Normal Text Normal Metin
Large Text Büyük Metin
Contrast Background Kontrast Arka Planı
Behind Selection Seçimin Arkası
Current Color Geçerli Renk
Pass Geçti
Fail Kaldı
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 en düşük kontrast: normal metin AA 4.5:1 (1.4.3) ve AAA 7:1 (1.4.6), büyük metin AA 3:1 ve AAA 4.5:1, grafikler ve denetimler AA 3:1 (1.4.11).
The background is read at the center of the selection. Arka plan seçimin ortasında okunur.
Graphics Processor Grafik İşlemcisi
Graphics: {adapter} Grafik: {adapter}
Gravity Yerçekimi
@@ -5303,6 +5314,12 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg finish editing the pattern first önce deseni düzenlemeyi bitir
@msg nothing encoded kodlanmış hiçbir şey yok
@msg nothing selected hiçbir şey seçilmedi
@msg `{key}` must be a color or {_1} `{key}` bir renk veya {_1} olmalıdır
@msg the selected objects' colors differ: give `color` seçili nesnelerin renkleri farklı: `color` belirtin
@msg the selected objects' colors differ: give `opacity` or `color` seçili nesnelerin renkleri farklı: `opacity` veya `color` belirtin
@msg the active fill or stroke has no color: give `color` etkin dolgu veya konturun rengi yok: `color` belirtin
@msg the active fill or stroke is hidden: give `color` etkin dolgu veya kontur gizli: `color` belirtin
@msg the active fill or stroke is drawn through an opacity mask: give `color` etkin dolgu veya kontur bir opaklık maskesi üzerinden çiziliyor: `color` belirtin
@msg nothing selected is in a group seçilenlerin hiçbiri bir grupta değil
@msg nothing to align hizalanacak hiçbir şey yok
@msg nothing to distort çarpıtılacak hiçbir şey yok
Can't render this file because it is too large.
+17
View File
@@ -1699,6 +1699,17 @@ file-filter Templates Шаблони
Graphic Styles Графічні стилі
Graphic Styles Options Параметри графічних стилів
Graphics Графіка
Show Contrast Показати контраст
Contrast For Контраст для
Normal Text Звичайний текст
Large Text Великий текст
Contrast Background Фон контрасту
Behind Selection За виділенням
Current Color Поточний колір
Pass Відповідає
Fail Не відповідає
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Мінімальний контраст за WCAG 2.2: звичайний текст AA 4.5:1 (1.4.3) і AAA 7:1 (1.4.6), великий текст AA 3:1 і AAA 4.5:1, графіка й елементи керування AA 3:1 (1.4.11).
The background is read at the center of the selection. Фон визначається в центрі виділення.
Graphics Processor Графічний процесор
Graphics: {adapter} Графіка: {adapter}
Gravity Гравітація
@@ -5591,6 +5602,12 @@ liquify-list-end {0}, {1} {0} і {1}
@msg finish editing the pattern first спочатку завершіть редагування візерунка
@msg nothing encoded нічого не закодовано
@msg nothing selected нічого не виділено
@msg `{key}` must be a color or {_1} `{key}` має бути кольором або {_1}
@msg the selected objects' colors differ: give `color` кольори виділених об’єктів відрізняються: укажіть `color`
@msg the selected objects' colors differ: give `opacity` or `color` кольори виділених об’єктів відрізняються: укажіть `opacity` або `color`
@msg the active fill or stroke has no color: give `color` активна заливка чи обведення не має кольору: укажіть `color`
@msg the active fill or stroke is hidden: give `color` активна заливка чи обведення приховані: укажіть `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` активна заливка чи обведення малюються крізь маску непрозорості: укажіть `color`
@msg nothing selected is in a group нічого з виділеного не перебуває в групі
@msg nothing to align нічого вирівнювати
@msg nothing to distort нічого спотворювати
Can't render this file because it is too large.
+17
View File
@@ -1933,6 +1933,17 @@ file-filter Templates Mẫu
Graphic Styles Kiểu đồ họa
Graphic Styles Options Tùy chọn kiểu đồ họa
Graphics Đồ họa
Show Contrast Hiện độ tương phản
Contrast For Tương phản cho
Normal Text Văn bản thường
Large Text Văn bản lớn
Contrast Background Nền tương phản
Behind Selection Phía sau vùng chọn
Current Color Màu hiện tại
Pass Đạt
Fail Không đạt
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Độ tương phản tối thiểu theo WCAG 2.2: văn bản thường AA 4.5:1 (1.4.3) và AAA 7:1 (1.4.6), văn bản lớn AA 3:1 và AAA 4.5:1, đồ họa và điều khiển AA 3:1 (1.4.11).
The background is read at the center of the selection. Nền được đọc tại tâm vùng chọn.
Graphics Processor Bộ xử lý đồ họa
Graphics: {adapter} Đồ họa: {adapter}
Gravity Trọng lực
@@ -5978,6 +5989,12 @@ liquify-list-end {0}, {1} {0} và {1}
@msg finish editing the pattern first hãy hoàn tất chỉnh sửa họa tiết trước
@msg nothing encoded không có gì được mã hóa
@msg nothing selected chưa chọn gì
@msg `{key}` must be a color or {_1} `{key}` phải là một màu hoặc {_1}
@msg the selected objects' colors differ: give `color` màu của các đối tượng đã chọn khác nhau: hãy cung cấp `color`
@msg the selected objects' colors differ: give `opacity` or `color` màu của các đối tượng đã chọn khác nhau: hãy cung cấp `opacity` hoặc `color`
@msg the active fill or stroke has no color: give `color` phần tô hoặc nét đang hoạt động không có màu: hãy cung cấp `color`
@msg the active fill or stroke is hidden: give `color` phần tô hoặc nét đang hoạt động bị ẩn: hãy cung cấp `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` phần tô hoặc nét đang hoạt động được vẽ qua mặt nạ độ mờ: hãy cung cấp `color`
@msg nothing selected is in a group không mục nào được chọn nằm trong nhóm
@msg nothing to align không có gì để căn chỉnh
@msg nothing to distort không có gì để làm méo
Can't render this file because it is too large.
+17
View File
@@ -1633,6 +1633,17 @@ file-filter Templates 模板
Graphic Styles 图形样式
Graphic Styles Options 图形样式选项
Graphics 图形
Show Contrast 显示对比度
Contrast For 对比度适用于
Normal Text 普通文本
Large Text 大号文本
Contrast Background 对比度背景
Behind Selection 所选对象后方
Current Color 当前颜色
Pass 通过
Fail 未通过
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低对比度:普通文本 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大号文本 AA 3:1 和 AAA 4.5:1,图形和控件 AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景在所选对象的中心读取。
Gravity 重力
Grays 灰度级数
Grays and Neutrals 灰色和中性色
@@ -5718,6 +5729,12 @@ liquify-list-end {0}, {1} {0}和{1}
@msg Couldn't paste from the clipboard: {e} 无法从剪贴板粘贴:{e}
@msg Couldn't paste: the document it was pasted in was closed 无法粘贴:要粘贴到的文档已关闭
@msg nothing selected 未选择任何对象
@msg `{key}` must be a color or {_1} `{key}` 必须是颜色或 {_1}
@msg the selected objects' colors differ: give `color` 所选对象的颜色不同:请提供 `color`
@msg the selected objects' colors differ: give `opacity` or `color` 所选对象的颜色不同:请提供 `opacity` 或 `color`
@msg the active fill or stroke has no color: give `color` 现用填色或描边没有颜色:请提供 `color`
@msg the active fill or stroke is hidden: give `color` 现用填色或描边已隐藏:请提供 `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` 现用填色或描边通过不透明度蒙版绘制:请提供 `color`
@msg nothing selected is in a group 所选对象均不在编组中
@msg the {tool} tool has no options {tool} 工具没有选项
@msg unknown tool `{tool}` 未知工具 `{tool}`
Can't render this file because it is too large.
+17
View File
@@ -1669,6 +1669,17 @@ file-filter Templates 範本
Graphic Styles 繪圖樣式
Graphic Styles Options 繪圖樣式選項
Graphics 圖形
Show Contrast 顯示對比度
Contrast For 對比度適用於
Normal Text 一般文字
Large Text 大型文字
Contrast Background 對比度背景
Behind Selection 選取範圍後方
Current Color 目前顏色
Pass 通過
Fail 未通過
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低對比度:一般文字 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大型文字 AA 3:1 和 AAA 4.5:1,圖形和控制項 AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景在選取範圍的中心讀取。
Graphics Processor 圖形處理器
Graphics: {adapter} 圖形:{adapter}
Gravity 重力
@@ -3062,6 +3073,12 @@ liquify-list-end {0}, {1} {0}和{1}
@msg Couldn't paste from the clipboard: {e} 無法從剪貼簿貼上:{e}
@msg Couldn't paste: the document it was pasted in was closed 無法貼上:要貼上的文件已關閉
@msg nothing selected 未選取任何物件
@msg `{key}` must be a color or {_1} `{key}` 必須是顏色或 {_1}
@msg the selected objects' colors differ: give `color` 所選物件的顏色不同:請提供 `color`
@msg the selected objects' colors differ: give `opacity` or `color` 所選物件的顏色不同:請提供 `opacity` 或 `color`
@msg the active fill or stroke has no color: give `color` 作用中的填色或筆畫沒有顏色:請提供 `color`
@msg the active fill or stroke is hidden: give `color` 作用中的填色或筆畫已隱藏:請提供 `color`
@msg the active fill or stroke is drawn through an opacity mask: give `color` 作用中的填色或筆畫透過不透明度遮色片繪製:請提供 `color`
@msg nothing selected is in a group 選取的物件都不在群組中
@msg the {tool} tool has no options {tool} 工具沒有選項
@msg unknown tool `{tool}` 未知的工具 `{tool}`
Can't render this file because it is too large.
+1 -1
View File
@@ -1598,7 +1598,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, 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: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; 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); 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 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, vision, documentColors}",
"{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; 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 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}",
),
(
"ui.savePdfDialog",
+2
View File
@@ -990,6 +990,8 @@ mod tests_color_wheel;
#[cfg(test)]
mod tests_color_wheel_box;
#[cfg(test)]
mod tests_color_wheel_contrast;
#[cfg(test)]
mod tests_color_wheel_document_colors;
#[cfg(test)]
mod tests_color_wheel_gamut;
+277 -16
View File
@@ -27,6 +27,11 @@
//! 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 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
//! whether it meets AA and AAA for the category picked under Contrast For (`color.contrast`).
//!
//! Panel menu › Show Color Vision Preview adds a row under the wheel or the box with the color as
//! simulated for protanopia, deuteranopia and tritanopia, through the simulations View › Proof
//! Setup uses, and for achromatopsia as the gray with the color's CIE L*. The chips only show the
@@ -47,8 +52,8 @@
//! preferences too.
//!
//! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule,
//! Show Opacity, Show Color Vision Preview and Show Document Colors are kept with the preferences
//! (`ui.colorWheel`).
//! Show Opacity, 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;
@@ -62,7 +67,7 @@ use craft::color_ui::AreaMode;
use craft::color_ui::ui::{ChannelRow, ChannelUnit, ColorArea, ColorStrip, ColorWheel, WheelInner};
use craft::keymap::CommandRef;
use craft::theme::{ColorModel, HsbModel, ModelValues, RgbModel, Srgba};
use craft::ui::choice::{SwatchSpacing, SwatchTable};
use craft::ui::choice::{Swatch, SwatchSpacing, SwatchTable};
use craft::ui::contract::{ActivateOn, Bind, EditResponse, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::{Shade, Text};
use craft::ui::layout::CellAlign;
@@ -76,6 +81,7 @@ use serde_json::{Value, json};
use vectorcraft_color::cms::{self, Cms, ProofSetup, ProofTarget};
use vectorcraft_color::harmony::{self, Harmony};
use vectorcraft_color::oklab::{self, CHROMA_FULL};
use vectorcraft_color::wcag::{self, Category};
use vectorcraft_color::{Color, Paint, hsb_to_rgb, hsl_to_rgb, rgb_to_hsb, rgb_to_hsl};
use vectorcraft_doc::{ColorMode, NodeId};
@@ -186,6 +192,16 @@ pub struct Settings {
/// Show Opacity: the opacity row under the wheel or the box.
#[serde(deserialize_with = "deserialize_flag")]
pub opacity: bool,
/// Show Contrast: the contrast row under the wheel or the box.
#[serde(deserialize_with = "deserialize_flag")]
pub contrast: bool,
/// Contrast For: the category whose AA and AAA results the row shows.
#[serde(serialize_with = "serialize_category", deserialize_with = "deserialize_category")]
pub contrast_for: Category,
/// Contrast Background › Current Color: the pinned background; None for the color behind the
/// selection.
#[serde(deserialize_with = "deserialize_background")]
pub contrast_background: Option<Color>,
/// Show Color Vision Preview: the row of simulated colors under the wheel or the box. A saved
/// `true` shows the row and any other value hides it.
#[serde(deserialize_with = "crate::panels::color::deserialize_lenient_bool")]
@@ -239,6 +255,9 @@ impl Default for Settings {
harmony: false,
harmony_rule: Harmony::Complementary,
opacity: false,
contrast: false,
contrast_for: Category::default(),
contrast_background: None,
vision: false,
document_colors: false,
}
@@ -284,6 +303,25 @@ fn deserialize_channel<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Channel
Ok(v.as_str().and_then(Channel::parse).unwrap_or_default())
}
fn serialize_category<S: serde::Serializer>(c: &Category, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(c.id())
}
fn deserialize_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Category, D::Error> {
let v = <Value as Deserialize>::deserialize(d)?;
Ok(v.as_str().and_then(Category::parse).unwrap_or_default())
}
/// A pinned background as saved (`{model, …}`) or as `ui.colorWheel` takes it (any color the
/// paint commands take); anything else reads as no pin.
fn background_value(v: &Value) -> Option<Color> {
serde_json::from_value(v.clone()).ok().or_else(|| vectorcraft_engine::cmd::color_value(v))
}
fn deserialize_background<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Color>, D::Error> {
Ok(background_value(&<Value as Deserialize>::deserialize(d)?))
}
/// Serde reader for the saved settings ([`crate::UiState::color_wheel`]): a value that is not an
/// object reads as the defaults, so it doesn't lose the rest of the preferences.
pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Settings, D::Error> {
@@ -291,12 +329,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?, 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 or hide the color vision row and the Show
/// Document Colors row. Keys left out or null keep their values; params that are not an object,
/// another key or a value off the list are an error and change nothing.
/// `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.
/// `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> {
@@ -307,7 +347,20 @@ 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; 9] = ["view", "channel", "sliders", "gamut", "harmony", "harmonyRule", "opacity", "vision", "documentColors"];
const KEYS: [&str; 12] = [
"view",
"channel",
"sliders",
"gamut",
"harmony",
"harmonyRule",
"opacity",
"contrast",
"contrastFor",
"contrastBackground",
"vision",
"documentColors",
];
match p {
Value::Null => {}
Value::Object(o) => {
@@ -359,6 +412,29 @@ 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;
}
match p.get("contrast") {
None | Some(Value::Null) => {}
Some(v) => {
let key = "contrast";
set.contrast = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?;
}
}
match p.get("contrastFor") {
None | Some(Value::Null) => {}
Some(v) => {
let key = "contrastFor";
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
set.contrast_for = v.as_str().and_then(Category::parse).ok_or_else(|| format!("`{key}` must be one of {}", ids.join(", ")))?;
}
}
match p.get("contrastBackground") {
None => {}
Some(Value::Null) => set.contrast_background = None,
Some(v) => {
let key = "contrastBackground";
set.contrast_background = Some(background_value(v).ok_or_else(|| format!("`{key}` must be a color or {}", "null"))?);
}
}
if let Some(on) = crate::menus::opt_bool(p, "vision")? {
set.vision = on;
}
@@ -393,9 +469,19 @@ fn rule_row_id(rule: Harmony) -> String {
format!("rule.{}", rule.id())
}
fn category_row_id(c: Category) -> String {
format!("contrastFor.{}", c.id())
}
/// A Contrast For category's menu label in the interface language.
pub(super) fn category_name(c: Category) -> &'static str {
tl!(c.label())
}
/// Every row of the panel menu with its state for `set`, `srgb` telling whether the active
/// document's RGB space is sRGB.
fn items(set: &Settings, srgb: bool) -> Vec<Item> {
/// document's RGB space is sRGB and `current` the color the panel edits, which Contrast Background
/// › Current Color pins.
fn items(set: &Settings, srgb: bool, current: Option<Color>) -> Vec<Item> {
let item = |id: String, label: &str, checked: bool, enabled: bool, params: Value| Item {
id,
label: label.to_string(),
@@ -432,6 +518,14 @@ fn items(set: &Settings, srgb: bool) -> Vec<Item> {
));
}
out.push(item("opacity".into(), tl!("Show Opacity"), set.opacity, true, json!({ "opacity": !set.opacity })));
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() })));
}
let pinned = set.contrast_background.is_some();
out.push(item("contrastBackground.below".into(), tl!("Behind Selection"), !pinned, true, json!({ "contrastBackground": null })));
let params = current.map_or(Value::Null, |c| json!({ "contrastBackground": crate::panels::color_json(&c) }));
out.push(item("contrastBackground.current".into(), tl!("Current Color"), pinned, current.is_some(), params));
out.push(item("vision".into(), tl!("Show Color Vision Preview"), set.vision, true, json!({ "vision": !set.vision })));
out.push(item(
"documentColors".into(),
@@ -445,7 +539,8 @@ fn items(set: &Settings, srgb: bool) -> 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 Color Vision Preview; and Show Document Colors.
/// Opacity; 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())];
@@ -456,13 +551,27 @@ 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", "vision", "documentColors"].map(|row| command(row.into())));
rows.extend(["opacity", "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(),
));
rows.push(PanelRow::Submenu(
Label::from(tl!("Contrast Background").to_string()),
["contrastBackground.below", "contrastBackground.current"].into_iter().map(|row| command(row.into())).collect(),
));
rows.extend(["vision", "documentColors"].map(|row| command(row.into())));
rows
}
/// The menu rows of `app`'s settings, with the color the panel edits for Current Color.
fn app_items(app: &VectorcraftApp) -> Vec<Item> {
items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), super::color::target_now(app).color())
}
/// The labels, checks and enabled states of [`menu_rows`].
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
for item in items(&app.ui.color_wheel, cms::active().rgb_is_srgb()) {
for item in app_items(app) {
let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked);
if let Some(hint) = item.hint {
state = state.hint(hint);
@@ -474,7 +583,10 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
/// Run the menu row `id` (`ui.colorWheel.<row>`); `None` when it is not one of this panel's.
pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option<Result<Value, String>> {
let row = id.strip_prefix("ui.colorWheel.")?;
let params = items(&app.ui.color_wheel, cms::active().rgb_is_srgb()).into_iter().find(|item| item.id == row)?.params;
if row == "contrastBackground.current" && super::color::target_now(app).color().is_none() {
return Some(Err("Current Color needs a solid color in the active proxy".to_string()));
}
let params = app_items(app).into_iter().find(|item| item.id == row)?.params;
Some(command(app, &params))
}
@@ -544,6 +656,10 @@ pub struct WheelUi {
rows_live: Option<Sliders>,
/// Whether a drag of the Show Opacity row previews on an open interaction, until it is released.
opacity_live: bool,
/// The color behind the selection, as `#rrggbb`, with the [`BehindKey`] it was read for.
pub(super) behind: Option<(BehindKey, Option<String>)>,
/// The contrast row's `color.contrast` answer, with the [`RatioKey`] it was asked for.
pub(super) ratio: Option<(RatioKey, Option<Value>)>,
}
/// The colors the row shows and whether they are the selection's, read with `color.used` once per
@@ -726,6 +842,148 @@ fn vision_row(ui: &mut Ui, cms: &Cms, color: Option<&Color>) {
.show_all(ui);
}
/// What the color behind the selection depends on: the document and its revision, the selected
/// objects, the picked object of a dynamic symbol instance, the on-screen Appearance of Black and
/// the color settings ([`under`]).
pub(super) type BehindKey = (u64, u64, Vec<NodeId>, Option<Vec<u32>>, String, Under);
/// What the contrast row's answer depends on.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct RatioKey {
/// The pinned background, or `below` for the color behind the selection.
pub(super) background: String,
/// The active proxy's paint; with nothing selected it is the default for new art, which no
/// revision counts.
pub(super) paint: String,
/// The document and its revision.
pub(super) doc: Option<(u64, u64)>,
pub(super) selection: Vec<NodeId>,
/// The picked object of a dynamic symbol instance.
pub(super) symbol_part: Option<Vec<u32>>,
/// Whether the Fill proxy is active.
pub(super) fill_active: bool,
pub(super) appearance_item: Option<usize>,
pub(super) stop: Option<usize>,
pub(super) freeform_point: Option<usize>,
/// The on-screen Appearance of Black.
pub(super) black_on_screen: String,
pub(super) under: Under,
/// The picked gradient mesh points, which the active tool keeps without a revision.
pub(super) mesh_points: Vec<(NodeId, Vec<usize>)>,
/// Whether the Live Paint Bucket paints, which gives the proxies its paints without a revision.
pub(super) bucket: bool,
}
/// The active color settings and profiles generation, which change how a color displays without
/// a document revision (Edit › Color Settings, a document's assigned profiles).
pub(super) type Under = (cms::ColorSettings, u64);
fn under() -> Under {
(cms::active_settings(), cms::profiles_generation())
}
/// The path of the picked object of a dynamic symbol instance, if one is picked.
fn picked_part(st: &vectorcraft_engine::DocState) -> Option<Vec<u32>> {
st.selection.symbol_part.as_ref().map(|sp| sp.path.clone())
}
/// The background the contrast row measures against: the pinned color, else the color
/// `color.contrast` reads behind the selection, kept per document revision and selection, so a
/// drag that moves the selection reads it again. None with nothing selected.
fn background(app: &mut VectorcraftApp, panel: &mut WheelUi) -> Option<Color> {
if let Some(c) = app.ui.color_wheel.contrast_background {
return Some(c);
}
let st = app.session.active()?;
let key: BehindKey = (st.uid, st.revision, st.selection.objects.clone(), picked_part(st), app.session.prefs.black_on_screen.clone(), under());
let hex = match &panel.behind {
Some((k, hex)) if *k == key => hex.clone(),
_ => {
// Any opaque color reads the background; only `against` is used.
let r = app.session.execute("color.contrast", &json!({ "color": "#000000" })).ok();
let hex = r.and_then(|r| r["against"].as_str().map(str::to_string));
panel.behind = Some((key, hex.clone()));
hex
}
};
// `against` is written in working RGB, the form a color takes.
Color::from_hex(&hex?)
}
/// The `color.contrast` answer against `pinned`, else against the color behind the selection
/// (`against: "below"`), kept per [`RatioKey`].
fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option<Color>) -> Option<Value> {
let st = app.session.active();
let key = RatioKey {
background: pinned.map_or_else(|| "below".to_string(), |bg| format!("{bg:?}")),
paint: format!("{:?}", super::active_paint(app)),
doc: st.map(|d| (d.uid, d.revision)),
selection: st.map(|d| d.selection.objects.clone()).unwrap_or_default(),
symbol_part: st.and_then(picked_part),
fill_active: app.session.fill_active,
appearance_item: app.session.appearance_item(),
stop: app.session.selected_stop(),
freeform_point: app.session.selected_freeform_point(),
black_on_screen: app.session.prefs.black_on_screen.clone(),
under: under(),
mesh_points: app.session.fill_mesh_points(),
bucket: app.session.tool_paints(!app.session.fill_active),
};
match &panel.ratio {
Some((k, r)) if *k == key => r.clone(),
_ => {
let against = pinned.as_ref().map_or_else(|| json!("below"), crate::panels::color_json);
let r = app.session.execute("color.contrast", &json!({ "against": against })).ok();
panel.ratio = Some((key, r.clone()));
r
}
}
}
/// The contrast row: the background's chip, the ratio cut off at two decimals and the AA and AAA
/// results for the chosen category; a dash when there is no background or no color to measure.
/// Without a pinned background the row asks `color.contrast` for the color behind the selection
/// (`against: "below"`), also during an interaction, so translucent groups and layers count as the
/// command counts them; the chip then shows the background in the answer. Only when there is no
/// answer is the background read on its own ([`background`]), so the chip still shows it. The chip
/// is a color well named Background whose value is the background's hex value, as the color vision
/// chips are; a click on it does nothing.
fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: &Cms) {
let category = app.ui.color_wheel.contrast_for;
let pinned = app.ui.color_wheel.contrast_background;
let answer = ratio_answer(app, panel, pinned);
// The background the ratio was measured against.
let measured = answer.as_ref().filter(|_| pinned.is_none()).and_then(|r| r["against"].as_str()).and_then(Color::from_hex);
let chip = match pinned.or(measured) {
Some(c) => Some(c),
None => background(app, panel),
};
let mut tip = tl!(
"WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11)."
)
.to_string();
if pinned.is_none() {
tip.push(' ');
tip.push_str(tl!("The background is read at the center of the selection."));
}
let ratio = answer.as_ref().and_then(|r| r["ratio"].as_f64());
Row::new().show(ui, |ui, _| {
let well = Mixed::Same(chip.map(|c| srgb(cms.display_rgb(&c))));
let _ = Swatch::optional(tl!("Background").to_string(), well).tooltip(tip.clone()).show(ui);
let Some(ratio) = ratio else {
Text::new("—").tooltip(tip.clone()).show(ui);
return;
};
Text::new(wcag::ratio_text(ratio)).tooltip(tip.clone()).show(ui);
let (aa, aaa) = category.passes(ratio);
let result = |pass: bool| if pass { tl!("Pass") } else { tl!("Fail") };
Text::new(format!("AA {}", result(aa))).tooltip(tip.clone()).show(ui);
if let Some(aaa) = aaa {
Text::new(format!("AAA {}", result(aaa))).tooltip(tip.clone()).show(ui);
}
});
}
/// What the HSB picked last belongs to: the document, the selected objects or text characters,
/// the appearance item, the proxy, the gradient stop or freeform point, its paint, and the color
/// the pick stored. The wheel shows that HSB only while all of them are unchanged.
@@ -1276,6 +1534,9 @@ fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pi
app.sync_views();
panel.rows_live = None;
}
if set.contrast {
contrast_row(app, panel, ui, cx.cms);
}
if set.vision {
vision_row(ui, cx.cms, cx.color.as_ref());
}
@@ -82,13 +82,13 @@ fn a_drag_in_the_field_is_one_undo_step_and_the_strip_sets_the_channel() {
#[test]
fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let harmony = json!({
"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false, "vision": false,
"documentColors": false
let others = json!({
"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false, "contrast": false,
"contrastFor": "normalText", "contrastBackground": null, "vision": false, "documentColors": false
});
let with = |v: serde_json::Value| {
let mut v = v;
v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone());
v.as_object_mut().unwrap().extend(others.as_object().unwrap().clone());
v
};
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), with(json!({"view": "wheel", "channel": "hue"})));
@@ -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, vision, documentColors"
"unknown parameter `veiw`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, 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, vision, documentColors"
"unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors"
);
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing");
}
@@ -0,0 +1,371 @@
//! The Color Wheel panel's Show Contrast row drawn headless through the `Fixture`: the ratio and
//! the AA and AAA results, the color behind the selection, a pinned background, a drag on the
//! wheel, the panel menu and `ui.colorWheel`.
use craft::ui::runtime::access::Role;
use serde_json::{Value, json};
use vectorcraft_color::wcag;
use vectorcraft_engine::Session;
use super::color_wheel::{BehindKey, RatioKey};
use super::tests_color_wheel::Panel;
use crate::VectorcraftApp;
use crate::i18n::LangExt as _;
/// An app with a selected rectangle filled with `fill` and the contrast row shown.
fn app(fill: &str) -> 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": 40, "y": 40, "width": 50, "height": 50})).unwrap();
app.run("paint.setFill", json!({"color": fill})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
app
}
fn shows(p: &Panel, text: &str) -> bool {
p.fx.by_label(text).is_some()
}
#[test]
fn the_row_cuts_the_ratio_off_and_fails_aa_just_under_it() {
let mut app = app("#fdc96e");
app.run("ui.colorWheel", json!({"contrastBackground": "#355f78"})).unwrap();
let p = Panel::new(app);
assert!(shows(&p, "4.49:1"), "4.4963:1 is cut off, not rounded up to 4.50:1");
assert!(shows(&p, "AA Fail") && shows(&p, "AAA Fail"));
}
#[test]
fn the_contrast_for_menu_shows_the_categories_in_the_interface_language() {
use vectorcraft_color::wcag::Category;
crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered"));
let names: Vec<&str> = Category::ALL.iter().map(|c| super::color_wheel::category_name(*c)).collect();
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(names, ["Normaler Text", "Großer Text", crate::i18n::tr(crate::i18n::Lang::from_code("de").unwrap(), "Graphics")]);
assert_ne!(names[0], Category::NormalText.label());
}
/// The panel menu's Show Contrast, Contrast For and Contrast Background rows set the settings, and
/// Current Color pins the color the panel edits.
#[test]
fn the_panel_menu_sets_the_contrast_settings() {
let mut app = app("#336699");
app.run("ui.colorWheel", json!({"contrast": false})).unwrap();
let run = |app: &mut VectorcraftApp, row: &str| super::color_wheel::run(app, &format!("ui.colorWheel.{row}"), &json!({})).unwrap().unwrap();
assert_eq!(run(&mut app, "contrast")["contrast"], true);
assert_eq!(run(&mut app, "contrastFor.graphics")["contrastFor"], "graphics");
run(&mut app, "contrastBackground.current");
assert_eq!(app.ui.color_wheel.contrast_background.map(|c| c.to_hex()).as_deref(), Some("#336699"));
assert_eq!(run(&mut app, "contrastBackground.below")["contrastBackground"], Value::Null);
let mut states = craft::ui::runtime::commands::CommandStates::new();
app.run("paint.setFill", json!({"none": true})).unwrap();
super::color_wheel::menu_states(&app, &mut states);
let current = states.get(&craft::keymap::CommandRef::new("ui.colorWheel.contrastBackground.current")).expect("a state");
assert!(!current.is_enabled(), "Current Color needs a color to pin");
let e = super::color_wheel::run(&mut app, "ui.colorWheel.contrastBackground.current", &json!({})).unwrap().unwrap_err();
assert_eq!(e, "Current Color needs a solid color in the active proxy");
assert_eq!(app.ui.color_wheel.contrast_background, None, "the error pins nothing");
}
/// An answer kept under other color settings (here a profiles generation not yet reached) is asked
/// again: Edit › Color Settings changes how a color displays without a document revision.
#[test]
fn an_answer_kept_under_other_color_settings_is_asked_again() {
let mut app = app("#000000");
app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
let mut p = Panel::new(app);
assert!(shows(&p, "21.00:1"));
let (mut key, answer) = p.app().ui.color_wheel_panel.ratio.clone().expect("the row keeps its answer");
let mut stale = answer.expect("an answer");
stale["ratio"] = json!(1.0);
key.under.1 = u64::MAX;
p.app_mut().ui.color_wheel_panel.ratio = Some((key, Some(stale)));
p.fx.idle(2);
assert!(shows(&p, "21.00:1"), "the answer is asked again under the current settings");
}
#[test]
fn the_row_follows_the_appearance_of_black() {
let mut app = app("#000000");
app.run("paint.setFill", json!({"color": {"c": 0, "m": 0, "y": 0, "k": 100}})).unwrap();
app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
app.run("prefs.set", json!({"key": "blackOnScreen", "value": "accurate"})).unwrap();
let mut p = Panel::new(app);
let text = |p: &Panel| {
let r = p.app_mut().session.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
wcag::ratio_text(r["ratio"].as_f64().unwrap())
};
let accurate = text(&p);
assert!(shows(&p, &accurate), "{accurate}");
p.run("prefs.set", json!({"key": "blackOnScreen", "value": "rich"}));
let rich = text(&p);
assert_ne!(accurate, rich, "rich black draws the black darker");
assert!(shows(&p, &rich), "the row shows {rich}, not {accurate}");
}
#[test]
fn the_category_changes_the_results_and_graphics_have_no_aaa() {
let mut app = app("#fdc96e");
app.run("ui.colorWheel", json!({"contrastBackground": "#355f78", "contrastFor": "largeText"})).unwrap();
let mut p = Panel::new(app);
assert!(shows(&p, "AA Pass") && shows(&p, "AAA Fail"));
p.run("ui.colorWheel", json!({"contrastFor": "graphics"}));
assert!(shows(&p, "AA Pass") && !shows(&p, "AAA Fail") && !shows(&p, "AAA Pass"));
}
#[test]
fn the_background_is_the_art_behind_the_selection() {
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": 180, "height": 180})).unwrap();
app.run("paint.setFill", json!({"color": "#ffff00"})).unwrap();
app.run("object.lock", json!({})).unwrap();
app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap();
app.run("paint.setFill", json!({"color": "#000000"})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let p = Panel::new(app);
let want = wcag::ratio_text(wcag::contrast_ratio([0.0; 3], [1.0, 1.0, 0.0]));
assert!(shows(&p, &want), "black on the locked yellow: {want}");
// Screen readers find the chip by its name, with the background's hex value as its value.
let chip = p.node("Background");
assert_eq!(p.fx.tree().role_of(chip.node), Some(Role::COLOR_WELL));
assert_eq!(p.value("Background").as_deref(), Some("#ffff00"));
}
#[test]
fn nothing_selected_and_nothing_pinned_shows_no_ratio() {
let mut app = app("#000000");
app.run("select.none", json!({})).unwrap();
let mut p = Panel::new(app);
assert!(shows(&p, "—"));
// A pinned background needs no selection: the proxy shows the defaults for new art.
p.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"}));
assert!(!shows(&p, "—"));
}
/// With nothing selected the row measures the default fill for new art, and follows a change of
/// it, which leaves the document's revision as it is.
#[test]
fn the_row_follows_the_default_fill_with_nothing_selected() {
let mut app = app("#000000");
app.run("select.none", json!({})).unwrap();
app.run("paint.setFill", json!({"color": "#000000"})).unwrap();
app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
let mut p = Panel::new(app);
assert!(shows(&p, "21.00:1"));
p.run("paint.setFill", json!({"color": "#ffffff"}));
assert!(shows(&p, "1.00:1"), "white on the pinned white");
}
/// The background read on its own, with what it was read for.
fn behind(p: &Panel) -> Option<(BehindKey, Option<String>)> {
p.app().ui.color_wheel_panel.behind.clone()
}
/// The background in the row's kept answer.
fn measured(p: &Panel) -> Option<String> {
let kept: Option<(RatioKey, Option<Value>)> = p.app().ui.color_wheel_panel.ratio.clone();
kept.and_then(|(_, r)| r).and_then(|r| r["against"].as_str().map(str::to_string))
}
/// During a drag on the wheel every preview raises the document's revision, and the row asks again
/// for the ratio, whose answer gives the chip: the background is not read on its own as well. The
/// drag is an interaction whose previews set the fill, as the Show Document Colors row's drag test
/// runs it.
#[test]
fn a_drag_on_the_wheel_reads_the_background_only_with_the_ratio() {
let mut p = Panel::new(app("#336699"));
assert_eq!(measured(&p).as_deref(), Some("#ffffff"));
assert!(behind(&p).is_none(), "the answer gave the background");
p.app_mut().session.begin_interaction("test").unwrap();
for fill in ["#3a6a9a", "#406f9f", "#4675a5"] {
p.run("paint.setFill", json!({"color": fill}));
}
assert!(p.app().session.in_interaction(), "the drag previews on an interaction");
p.app_mut().session.commit_interaction().unwrap();
p.fx.idle(2);
assert!(behind(&p).is_none(), "the background was not read on its own during or after the drag");
assert_eq!(measured(&p).as_deref(), Some("#ffffff"));
}
/// With no color to measure the row has no ratio, and the chip still shows the background, read on
/// its own, and read again for another selection during an interaction.
#[test]
fn a_paint_with_no_color_still_shows_the_background() {
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": 0, "y": 0, "width": 100, "height": 200})).unwrap();
app.run("paint.setFill", json!({"color": "#ffff00"})).unwrap();
app.run("object.lock", json!({})).unwrap();
let id = |v: Value| v["id"].as_u64().unwrap();
let b = id(app.run("shape.rectangle", json!({"x": 130, "y": 20, "width": 40, "height": 40})).unwrap());
app.run("paint.setFill", json!({"none": true})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap();
app.run("paint.setFill", json!({"none": true})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let mut p = Panel::new(app);
assert!(shows(&p, "—"), "a fill of None has no ratio");
let hex = |p: &Panel| behind(p).and_then(|(_, hex)| hex);
assert_eq!(hex(&p).as_deref(), Some("#ffff00"));
assert_eq!(p.value("Background").as_deref(), Some("#ffff00"), "the chip shows it");
p.app_mut().run("select.set", json!({"ids": [b]})).unwrap();
p.app_mut().session.begin_interaction("test").unwrap();
p.fx.idle(2);
assert_eq!(hex(&p).as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction");
}
/// With no color to measure, a move during an interaction reads the background again at the
/// selection's new place.
#[test]
fn a_move_during_an_interaction_reads_the_background_again() {
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": 0, "y": 0, "width": 100, "height": 200})).unwrap();
app.run("paint.setFill", json!({"color": "#ffff00"})).unwrap();
app.run("object.lock", json!({})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap();
app.run("paint.setFill", json!({"none": true})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let mut p = Panel::new(app);
let hex = |p: &Panel| behind(p).and_then(|(_, hex)| hex);
p.app_mut().session.begin_interaction("test").unwrap();
p.fx.idle(2);
assert_eq!(hex(&p).as_deref(), Some("#ffff00"));
p.app_mut().run("object.move", json!({"dx": 110, "dy": 0})).unwrap();
assert!(p.app().session.in_interaction(), "the move is part of the interaction");
p.fx.idle(2);
assert_eq!(hex(&p).as_deref(), Some("#ffffff"), "the background at the new place");
}
/// An interaction keeps no answer for another selection: the row asks again, and the chip shows
/// the other selection's background.
#[test]
fn an_interaction_reads_the_background_again_for_another_selection() {
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": 0, "y": 0, "width": 100, "height": 200})).unwrap();
app.run("paint.setFill", json!({"color": "#ffff00"})).unwrap();
app.run("object.lock", json!({})).unwrap();
let id = |v: Value| v["id"].as_u64().unwrap();
let b = id(app.run("shape.rectangle", json!({"x": 130, "y": 20, "width": 40, "height": 40})).unwrap());
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#000000"})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let mut p = Panel::new(app);
assert_eq!(measured(&p).as_deref(), Some("#ffff00"));
p.app_mut().run("select.set", json!({"ids": [b]})).unwrap();
p.app_mut().session.begin_interaction("test").unwrap();
p.fx.idle(2);
assert_eq!(measured(&p).as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction");
assert_eq!(p.value("Background").as_deref(), Some("#ffffff"), "the chip shows it");
}
/// Without a pin the row asks for the color behind the selection, so a translucent group holding
/// other art behind the object counts as `color.contrast {}` counts it.
#[test]
fn the_row_answers_as_color_contrast_does_inside_a_translucent_group() {
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": 0, "y": 0, "width": 200, "height": 200})).unwrap();
app.run("paint.setFill", json!({"color": "#ffff00"})).unwrap();
app.run("object.lock", json!({})).unwrap();
let id = |v: Value| v["id"].as_u64().unwrap();
let back = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 120, "height": 120})).unwrap());
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
let front = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap());
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
let g = id(app.run("object.group", json!({"ids": [back, front]})).unwrap());
app.run("select.set", json!({"ids": [g]})).unwrap();
app.run("transparency.set", json!({"opacity": 50})).unwrap();
app.run("select.set", json!({"ids": [front]})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let p = Panel::new(app);
let want = p.app_mut().session.execute("color.contrast", &json!({})).unwrap();
let against = want["against"].clone();
let given = p.app_mut().session.execute("color.contrast", &json!({"against": against})).unwrap();
let (want, given) = (wcag::ratio_text(want["ratio"].as_f64().unwrap()), wcag::ratio_text(given["ratio"].as_f64().unwrap()));
assert_ne!(want, given, "the group's other art makes the two answers differ");
assert!(shows(&p, &want), "the row shows {want}, not {given}");
}
/// Clicks the point of the selected gradient mesh at (`x`, `y`) with the Mesh tool, which picks it
/// alone.
fn pick_point(s: &mut Session, x: f64, y: f64) {
use vectorcraft_tools::{PointerEvent, PointerKind};
let v = vectorcraft_engine::ViewInfo::default();
s.select_tool("mesh", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, x, y), v).unwrap();
}
}
/// The row asks again when the Mesh tool picks another point, which changes no document revision:
/// here a black point at 50 % after an opaque black one.
#[test]
fn the_row_follows_the_picked_mesh_points() {
let mut app = app("#000000");
app.run("object.mesh.create", json!({"rows": 1, "cols": 1})).unwrap();
app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
pick_point(&mut app.session, 40.0, 40.0);
app.run("transparency.set", json!({"opacity": 50})).unwrap();
pick_point(&mut app.session, 90.0, 40.0);
let mut p = Panel::new(app);
assert!(shows(&p, "21.00:1"), "the opaque top-right point");
let revision = |p: &Panel| p.app().session.active().map(|d| d.revision);
let before = revision(&p);
pick_point(&mut p.app_mut().session, 40.0, 40.0);
assert_eq!(revision(&p), before, "a pick is no document change");
p.fx.idle(2);
let gray = wcag::ratio_text(wcag::contrast_ratio([0.5; 3], [1.0; 3]));
assert!(shows(&p, &gray), "the top-left point at 50 % shows {gray}");
}
#[test]
fn ui_color_wheel_sets_the_keys_given_and_refuses_bad_values() {
let mut app = app("#000000");
let r = app.run("ui.colorWheel", json!({"contrastFor": "graphics", "contrastBackground": "#ff0000"})).unwrap();
assert_eq!(r["contrast"], true, "keys left out keep their values");
assert_eq!(r["contrastFor"], "graphics");
assert_eq!(app.ui.color_wheel.contrast_background.map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
let before = app.ui.color_wheel.clone();
for (p, e) in [
(json!({"contrast": "yes"}), "`contrast` must be true or false"),
(json!({"contrastFor": "huge"}), "`contrastFor` must be one of normalText, largeText, graphics"),
(json!({"contrastFor": 3}), "`contrastFor` must be one of normalText, largeText, graphics"),
(json!({"contrastBackground": "nope"}), "`contrastBackground` must be a color or null"),
(json!({"contrast": false, "contrastBackground": 5}), "`contrastBackground` must be a color or null"),
] {
assert_eq!(app.run("ui.colorWheel", p.clone()).unwrap_err(), e, "{p}");
}
assert_eq!(app.ui.color_wheel, before, "an error changes nothing");
let r = app.run("ui.colorWheel", json!({"contrastBackground": null})).unwrap();
assert_eq!(r["contrastBackground"], Value::Null, "null goes back to the color behind the selection");
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), r, "{{}} reads the settings");
}
#[test]
fn the_settings_are_saved_and_each_key_reads_on_its_own() {
let mut app = app("#000000");
app.run("ui.colorWheel", json!({"contrastFor": "largeText", "contrastBackground": {"c": 0, "m": 1, "y": 0, "k": 0}})).unwrap();
let saved: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
assert_eq!(saved.color_wheel, app.ui.color_wheel);
let ui: crate::UiState =
serde_json::from_value(json!({"color_wheel": {"contrast": true, "contrastFor": "huge", "contrastBackground": 5}, "place_link": false}))
.unwrap();
assert!(ui.color_wheel.contrast, "a key that reads keeps its value");
assert_eq!((ui.color_wheel.contrast_for, ui.color_wheel.contrast_background), (wcag::Category::NormalText, None));
assert!(!ui.place_link, "the other preferences still load");
let ui: crate::UiState = serde_json::from_value(json!({"color_wheel": 3, "place_link": false})).unwrap();
assert_eq!((ui.color_wheel, ui.place_link), (Default::default(), false));
}
#[test]
fn ui_color_wheel_answers_junk_params_without_a_panic() {
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3;
let mut app = app("#336699");
for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) {
let _ = app.run("ui.colorWheel", p);
}
let mut app = VectorcraftApp::new(Session::new(), Default::default());
assert_eq!(app.run("ui.colorWheel", json!({"contrast": true})).unwrap()["contrast"], true);
}
@@ -83,8 +83,10 @@ fn ui_color_wheel_sets_gamut() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let with = |v: serde_json::Value| {
let mut v = v;
let rest =
json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "opacity": false, "vision": false, "documentColors": false});
let rest = json!({
"sliders": "none", "harmony": false, "harmonyRule": "complementary", "opacity": false, "contrast": false, "contrastFor": "normalText",
"contrastBackground": null, "vision": false, "documentColors": false
});
v.as_object_mut().unwrap().extend(rest.as_object().unwrap().clone());
v
};
@@ -88,7 +88,12 @@ fn with_a_none_fill_the_chips_have_no_color() {
#[test]
fn ui_color_wheel_sets_and_reads_the_settings() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false, "vision": vision, "sliders": "none", "documentColors": false});
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
})
};
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false));
assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), settings("wheel", true));
assert_eq!(crate::control::inspect(&app, &crate::testing::ui_context())["ui"]["color_wheel"]["vision"], true);
@@ -99,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, vision, documentColors"
"unknown parameter `visoin`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors"
);
assert!(app.ui.color_wheel.vision);
assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true);
+2 -2
View File
@@ -892,8 +892,8 @@ 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 and the color vision row
/// (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]).
/// 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`]).
#[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
+7
View File
@@ -241,6 +241,13 @@ its variation grid; the panel draws the same grid. `ui.colorGuideOptions` opens
as `ui.color_guide` (`variation`, `steps`, `amount`). Save Colors as Swatches runs `swatch.new {colors: [...]}`
(one swatch per colour, one undo step).
Color Wheel contrast: `color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio of the active
proxy's color against the color drawn behind the selection (`against: "below"`, the default) or against a given color,
with the AA and AAA results for normal text and large text and the AA result for graphics (docs/mcp.md). The Color Wheel panel's Show
Contrast row shows the same answer for the category picked under Contrast For; `ui.colorWheel {contrast?, contrastFor?,
contrastBackground?}` sets the row, its category and a pinned background, and `ui.inspect` reports them as
`ui.color_wheel`.
Color Guide Limit to Library: `ui.colorGuideLimit {library}` (a swatch library id or name, `"document"` for the
document's swatches, `""` for none) limits the panel's colours; `ui.inspect` reports it as `ui.color_guide_limit`, and
`color.harmony {..., limitTo}` answers the limited guide (every colour snaps to the library's nearest colour, ΔE 2000).
+37 -2
View File
@@ -697,10 +697,13 @@ with a slider and a percent field sets the opacity of the fill row (`paint.setFi
(`paint.setStroke {opacity}`), the selected gradient stop or the selected freeform point (the first stop or point
when none is selected), and `false` hides the row. The row is gray with nothing selected, for an object selected in
a symbol instance, and when the fill or stroke row it would set is on type characters or missing.
`{"contrast": true}` shows Show Contrast's row under the wheel or the box, `contrastFor` (`normalText`, `largeText` or
`graphics`, which has AA only) picks the category its results are for, and `contrastBackground` (a color, or `null` for
the color behind the selection) pins the background it measures against, as `color.contrast` below answers it.
`{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel
or the box. Keys left out keep their values. Params that are not an object, another key or a value off
the list return an error and change nothing. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors}`,
and the settings are kept with the preferences.
the list return an error and change nothing. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, opacity,
contrast, contrastFor, contrastBackground, vision, documentColors}`, and the settings are kept with the preferences.
`ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or
the box), and `"none"` hides them in any RGB space. `"oklch"` is an error while the active document's RGB space is
@@ -1204,6 +1207,38 @@ panel's Limit to Library does (`ui.colorGuideLimit`); Recolor Artwork's `limitTo
that is not a string, such as `5`, names no library and gets the same error as an unknown name; `null` or `""` sets no
limit.
`color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio
([definition](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio)) of a color against a background, from 1 to 21, and
whether it meets AA and AAA for normal text (4.5:1 and 7:1), large text (3:1 and 4.5:1) and graphics (3:1, AA only):
`{ratio, against, normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}`. The results compare the unrounded
ratio. `color` defaults to the active Fill or Stroke proxy's color (its selected gradient stop or freeform point, or
the first picked point of a gradient mesh; for a picked object of a dynamic symbol instance, its solid color mixed towards the fill that stains the instance), at
the opacity it is drawn with (the object's opacity times that of its groups and layer, and for a picked object of a
dynamic symbol instance also of the instance and the groups of the symbol's art around it, of its fill or stroke row,
which type's character paint does not use, and of a stop or point; a translucent group or layer draws the art inside
it, the art behind the object included, over what is outside it) and with the blend modes it is drawn with (its
fill or stroke row's, the object's and those of its groups and layer, innermost first, each blending the result with
the art below it inside the object, groups and layer around it, the object's rows below its row included, or with
the background when `against` or `opacity` is given;
inside an object, group or layer that isolates its blending, the modes blend only with the art it holds);
`opacity` (0 to 100) replaces that opacity. A given `color` is drawn in Normal mode, at `opacity` or fully opaque.
`against` takes a color, or `"below"` (the default, also for `null`): the color VectorCraft draws at the center of the
selection's bounds with the selected objects hidden, as the canvas shows it (locked art, opacity, blend modes and
images included; template layers and guides left out, as exports leave them out; the artboard's white where nothing
is drawn); a picked object of a dynamic symbol instance hides only itself, and the color is read at its own center.
These are errors: `"below"` with nothing selected; a "?" proxy (hidden objects count there, as in the Color panel);
selected objects that draw one color with different blend modes, or at different opacities without `opacity` (with
`"below"`, also in different groups or layers that are translucent, have a blend mode or isolate their blending, or
with a translucent or blending row over different shown rows below it), where hidden objects do not count, and the
error names `opacity` when giving it settles the difference; a proxy of None, a pattern or a hidden row without `color`; and without `color`, a
proxy's object drawn through an opacity mask that is not disabled, its own or that of a group, layer or instance
around it, since the mask sets how much of the color shows at each point. `against` in the
answer is the background as a working RGB `#rrggbb`, the form `against` takes; the sampled background is rounded to 8
bits, so giving it back answers the same ratio, except when `opacity` is omitted and a group or layer around the
object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over
rows below it: there `"below"` reads the art below each such level, and a given background stands for that art.
Headless MCP answers it too.
Color Themes (local only: no online service) keeps five-colour themes in the preferences. `colorTheme.save
{colors: [...]}` saves up to five colours as they are, `colorTheme.save {color, rule}` saves the five-colour theme a
harmony rule makes from a base colour (base first; `name?` defaults to "Theme N", `replace: "<name>"` overwrites
+72 -30
View File
@@ -1,11 +1,12 @@
# Windows, Linux and macOS release-ref nightly: supervised manual go-live
**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the
signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed
manual actors dispatches them. There is no schedule yet. The installed policy
[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3
policy. Once `nightly.yml` reaches `main`, populate `producer_workflow_id` with its registration ID
before promoting the policy to `release`:
**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and
the signer (`nightly-sign.yml`, on the dedicated `nightly-signer` branch) keep only their exact
context guards and run when one of the reviewed manual actors dispatches them.
`nightly-dispatch.yml` stays literally off: it only forwards scheduled producers. There is no
schedule. The installed policy
[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy.
Its `producer_workflow_id` is the registration of `nightly.yml` on main, read with:
```bash
gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id
@@ -14,38 +15,66 @@ gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id
The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation
permissions are for its isolated attester; its compiler narrows to contents and Actions read
only, with no OIDC, attestation write, release environment or platform signing secrets.
Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions
main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded
lineage compares and an issue reread at the end of candidate admission) on top of
[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input
and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed
source availability, not provider, queue, native signing or crypto qualification.
Existing stable workflows are unchanged.
Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions
main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the
candidate is admitted on the built commit's own Sonar analysis, not main's latest) after
[#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly
registry rows for the 14 apps) and
[#369](https://github.com/storytold/craft-common-actions/pull/369) (shared helper checkouts kept out
of the app's clean-source check, and macOS on `macos-15`), following
[#364](https://github.com/storytold/craft-common-actions/pull/364) (the signer may run on the
policy's signer branch) and [#363](https://github.com/storytold/craft-common-actions/pull/363) (the
multi-app pipeline, which makes the signer's `app-name` input required and admits any reviewed
registry app), with #342 (`a4f6fd51`, policy v3 and the `platforms` input) and #339 (`605d5876`)
earlier. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source
availability, not provider, queue, native signing or crypto qualification. Existing stable workflows are unchanged.
**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that
producer run ID and attempt, by a listed manual actor.
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `nightly-signer`
with that producer run ID and attempt, by a listed manual actor. `nightly-dispatch.yml` only matters
once a schedule is approved.
**Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release`
branch, so nightly signer files never need a stable release sync. The policy's `release_branch`
names it, the signer's guard requires it and the dispatcher targets it. The branch only
fast-forwards to reviewed main commits, through the settings script's `advance` (no queued signer
run, a trust-closure scan, then the full diff of `.github/` and `packaging/`), and the existing
`release` environment must admit `nightly-signer` alongside `release` before the first dispatch (a
repository settings change, not a workflow one). Its trust closure is all of `.github/` and
`packaging/`, including `packaging/env.sh`, which `packaging/macos/import-cert.sh` sources with the
Apple keys. On that branch only the pinned `nightly-sign.yml` caller may reach an environment: no
app workflow binds one, nothing else calls `nightly-release.yml`, and the only caller of the shared
stable `release.yml` is `release.yml`, whose callee must carry the stable-only environment guard.
The contract tests check the in-repo part on every main PR; the settings scan also resolves the
callee. Stable releases still come only from `refs/heads/release`. History does not carry over a
switch between `release` and `nightly-signer`, so the switch happens before the first publication.
**Registry admission.** The signer requires the protected policy's `platforms` map to equal the
run app's admitted targets in craft-common-actions' `nightly-apps.json`, and it refuses rather
than sign a subset. VectorCraft's row admits `linux-x86_64`, `windows-x86_64` and `macos-aarch64`, with
each target's entrypoint and asset pattern, since craft-common-actions #370 (in the pin).
**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the
producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers
team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes.
team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team
changes.
**Platform rows.** The producer caller lists
`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer
run builds every listed platform for one all-or-nothing release (one failed or
skipped platform stops that night's release, Windows included), and the release-ref signer admits
skipped platform stops that night's release, Windows included), and the signer admits
platforms only from the protected policy, so there is no separate Linux or macOS caller job and
the signer caller has no platform input.
## Installed policy values and their sources
Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` after `nightly.yml` lands on `main`) before the policy is promoted to `release`.
Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` is advanced to it.
| Field | Value | Source |
|---|---|---|
| `repository_id` | `1398097510` | `gh api repos/storytold/vectorcraft --jq .id` |
| `producer_workflow_id` | `null` (pending first registration on `main`) | Read via `gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` is on `main` |
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin |
| `producer_workflow_id` | `430275079` | `gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id` |
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions #371 after #370, #369 and #364) | The callers' pin |
| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` |
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
| `platforms` | three rows | Learning Machines stable identities (Windows Authenticode publisher subject, Linux OpenPGP fingerprint, Apple Developer ID team `DJ6XS33FX8`) |
@@ -57,11 +86,15 @@ Read on 2026-11-24; re-read anything that may have moved (and populate `producer
- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named
`VectorCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets
may be passed or inherited.
- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch,
and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch,
- `.github/workflows/nightly-sign.yml`: top-level registration on `nightly-signer`, enabled for manual dispatch,
and only ever fast-forwards to reviewed main commits. It rejects wrong repository/event/actual branch,
including same-name tags. Its constant whole-run concurrency (`vectorcraft-nightly-release`) is distinct
from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no
credentials; only the shared callee's sign jobs bind the `release` environment.
credentials; only the shared callee's sign jobs bind the `release` environment, which must admit
`nightly-signer` alongside `release` before the first dispatch.
- `.github/workflows/nightly-dispatch.yml`: transport only, never authorization. It is literally
off (`false &&`) and forwards only a first-attempt scheduled producer to `nightly-sign.yml` on
`nightly-signer`. No schedule is registered until activation is reviewed.
- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in
`storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable
commit**; the defining workflow SHA and tooling input must match.
@@ -73,7 +106,14 @@ Read on 2026-11-24; re-read anything that may have moved (and populate `producer
- Manual actors match the reviewed release-managers list in both `nightly.yml` and `.github/nightly-signing-policy.json`, with `automatic_signer_actors` empty.
- Both callers pin the same immutable `craft-common-actions` commit in `uses` and `tooling-revision`.
- No nightly schedule is registered, no cache actions or secrets appear in the app callers, and `nightly-sign.yml` retains its literal root `concurrency` block (`group: vectorcraft-nightly-release`, `cancel-in-progress: false`, `queue: max`).
- Policy v3 schema, platform rows, bounds, required main-push CI workflow, and SonarCloud project identity match `sonar-project.properties`.
- Policy v3 schema, platform rows, bounds, required main-push CI workflow, and SonarCloud project identity match `sonar-project.properties`, and the Sonar gate shape keeps every live condition once with accepted failures inside the reviewed issue scope.
- The signer guards `refs/heads/nightly-signer`, passes `app-name: vectorcraft`, and the policy's
`release_branch` names it.
- A trust-closure scan reads every workflow: nothing binds an `environment`, only `nightly-sign.yml`
calls `nightly-release.yml` (at a full SHA), and the only caller of the shared stable `release.yml`
is `release.yml`.
- `nightly-dispatch.yml` keeps a literal-off guard, a `workflow_run`-only trigger and a
`refs/heads/nightly-signer` request.
## The app side of a Nightly build
@@ -139,12 +179,14 @@ enabled, so no `app.ron` is written anywhere); if it is ever turned on, its stat
installation on every platform, and `apps/vectorcraft/src/profile.rs` (`install_data_root`) is the
one hook every data path follows.
## Activation prerequisite: the Sonar issue scope
## The Sonar issue scope
The pinned candidate validator requires every entry in `candidate_policy.sonar.issue_types` to map
from a reviewed `accepted_conditions` row, and it requires the gate condition set to equal
`accepted_conditions` plus `required_conditions`. The installed policy lists `VULNERABILITY` with no
accepted condition, so it fails that contract before SonarCloud is read. Correct the policy in this
app's activation review with Skylar, together with the live gate conditions, before the first run:
the callers cannot run before that review anyway, because their `producer_workflow_id` stays null
until `nightly.yml` is registered on `main` and the signer is promoted to `release`.
`accepted_conditions` plus `required_conditions`. The installed policy lists `VULNERABILITY` with
`new_security_rating` accepted (max 5) and the other five gate conditions required - the same shape
PhotoCraft and WordCraft ship - so it satisfies that contract before SonarCloud is read. `debt` stays
empty, so any unresolved vulnerability on `main` is still refused, and the live gate is still compared
condition by condition against the policy. `producer_workflow_id` is now populated and the signer runs
on `nightly-signer`; the registry's Windows and macOS targets are what still stand between this tree
and a first signed nightly.
+8 -1
View File
@@ -243,10 +243,17 @@ the job fails and asks for a version bump (`cargo xtask version set`).
## Secrets
The jobs that sign (macOS, Windows) and the draft-release job run in the `release` environment,
which only the `release` branch can use and which holds the signing secrets. The other jobs get no
which only the `release` branch can use today and which holds the signing secrets. The other jobs get no
secrets. Every secret is optional: a missing one produces unsigned artifacts and a
warning, never a failed build.
The supervised nightly signer does not sign from `release`: it runs on `refs/heads/nightly-signer`,
which only ever fast-forwards to reviewed main commits, and the `release` environment must admit
`nightly-signer` alongside `release` before the first dispatch. Everything that can reach it is the
trust closure: all of `.github/` and `packaging/`, including `packaging/env.sh`, which
`packaging/macos/import-cert.sh` sources with the Apple keys. Stable releases still come only from
`refs/heads/release`.
| Secret | Used for |
|---|---|
| `APPLE_CERTIFICATE`, `APPLE_CERTIFICATE_PASSWORD`, `KEYCHAIN_PASSWORD` | the Developer ID certificate (base64 `.p12`), imported into a temporary keychain by `packaging/macos/import-cert.sh` |
+1
View File
@@ -2042,6 +2042,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`.
- **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged.
VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Scores and estimates are unchanged.
The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics (AA only for graphics). `color.contrast` answers the same for agents.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
**Color panel spectrum mode tooltip (part of #7235):** hovering the spectrum names the displayed mode (Grayscale, RGB, HSB, CMYK, Web Safe RGB or Lab), including after Shift-clicking to switch modes and with Show Options or Hide Options. Hovering changes no paint or undo history. Spectrum rendering and vertical resizing remain open. Evidence: `spectrum_tooltip_names_its_displayed_mode` and `spectrum_tooltip_follows_shift_cycle_without_painting` in `crates/ui-egui/tests/color_working_components.rs`. Scores and estimates unchanged.
+375 -2
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""Local regression checks for VectorCraft nightly workflow and signing-policy contracts."""
import copy
from decimal import Decimal
import json
from pathlib import Path
import re
@@ -9,6 +10,23 @@ import unittest
ROOT = Path(__file__).resolve().parents[1]
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
def security_bound_problem(maximum):
"""None when an accepted security-rating maximum is the reviewed whole A..E rating.
Decimal, not float: "5.0000000000000001" rounds to 5.0 as a float, so the shared candidate
contract would refuse a bound this suite had already accepted.
"""
value = Decimal(maximum)
if int(value) != value:
return "the A..E bound is a whole rating"
if not 1 <= value <= 5:
return "the security bound stays A..E"
return None
APP_NAME = "vectorcraft"
PRODUCER_WORKFLOW_NAME = "VectorCraft unsigned nightly"
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
@@ -262,7 +280,7 @@ class NightlyEnabledCallers(unittest.TestCase):
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-sign.yml": "github.repository == 'storytold/vectorcraft' && github.event_name == 'workflow_dispatch' && "
"github.ref == 'refs/heads/release' && github.ref_type == 'branch'",
"github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'",
}
def test_enabled_jobs_keep_exact_context_guards(self):
@@ -334,7 +352,8 @@ class NightlyInstalledPolicy(unittest.TestCase):
self.assertEqual(set(self.policy), expected)
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
self.assertEqual(self.policy["repository"], "storytold/vectorcraft")
self.assertEqual(self.policy["release_branch"], "release")
self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH,
"the signer runs on its dedicated branch")
self.assertIs(type(self.policy["repository_id"]), int)
self.assertGreater(self.policy["repository_id"], 0)
producer_id = self.policy["producer_workflow_id"]
@@ -425,6 +444,360 @@ class NightlyInstalledPolicy(unittest.TestCase):
self.assertIn(item["type"], sonar["issue_types"])
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
def test_sonar_policy_keeps_the_shared_candidate_contract(self):
"""The Sonar shape craft-common-actions' candidate contract() admits, refused here first.
An empty issue scope, an accepted condition outside the reviewed issue types, a metric in both
lists, a missing live gate condition or a widened security bound is refused at admission, so
this suite must catch it before a nightly run can. `debt` stays empty, so any unresolved
vulnerability on main is still refused; accepting the new-code rating only records the
reviewed A threshold instead of demanding a clean rating the live gate does not.
"""
sonar = self.policy["candidate_policy"]["sonar"]
accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL",
"security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"}
gate = {"new_reliability_rating", "new_security_rating", "new_maintainability_rating",
"new_coverage", "new_duplicated_lines_density", "new_security_hotspots_reviewed"}
self.assertTrue(sonar["issue_types"], "an empty issue scope is refused as unreviewed")
self.assertEqual(len(sonar["issue_types"]), len(set(sonar["issue_types"])))
metrics = {}
for field in ("accepted_conditions", "required_conditions"):
for condition in sonar[field]:
with self.subTest(field=field, metric=condition.get("metric")):
expected = {"metric", "comparator", "error_threshold"}
if field == "accepted_conditions":
expected.add("maximum")
self.assertEqual(set(condition), expected)
self.assertNotIn(condition["metric"], metrics, "one condition per gate metric")
metrics[condition["metric"]] = condition
self.assertIn(condition["comparator"], ("GT", "LT"))
self.assertRegex(condition["error_threshold"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$")
if field != "accepted_conditions":
continue
self.assertIn(condition["metric"], accepted, "an accepted metric outside the reviewed map")
self.assertIn(accepted[condition["metric"]], sonar["issue_types"],
"an accepted failure must lie inside the reviewed issue scope")
self.assertEqual(condition["comparator"], "GT")
self.assertRegex(condition["maximum"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$")
maximum = Decimal(condition["maximum"])
if condition["metric"] in ("security_rating", "new_security_rating"):
self.assertIsNone(security_bound_problem(condition["maximum"]),
"the security bound stays the reviewed whole A..E rating")
self.assertEqual(condition["error_threshold"], "1", "the reviewed A threshold stays")
else:
self.assertLessEqual(maximum, len(sonar["debt"]), "accepted failures exceed the reviewed debt")
self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]),
"accepted conditions and reviewed issue types must cover the same scope")
self.assertEqual(set(metrics), gate, "every live gate condition stays gated exactly once")
def test_security_bound_rejects_a_maximum_float_rounds_to_five(self):
"""The shared candidate contract reads the bound as a decimal; float() would hide the widening."""
self.assertIsNone(security_bound_problem("5"))
self.assertIsNone(security_bound_problem("5.0"))
self.assertEqual(security_bound_problem("5.0000000000000001"), "the A..E bound is a whole rating")
self.assertEqual(security_bound_problem("6"), "the security bound stays A..E")
SIGNER_BRANCH = "nightly-signer"
SHARED = "storytold/craft-common-actions/.github/workflows/"
# App workflows reviewed to call the shared stable release.yml. That callee must carry the
# stable-only environment guard (dry runs and non-release refs bind no environment); the
# nightly-signer settings scan checks the resolved callee before creating or advancing the branch.
REVIEWED_STABLE_RELEASE_CALLERS = {"release.yml"}
def app_workflows():
return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))}
WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''')
def _workflow_key(text):
if text.startswith('"'):
return None if "\\" in text else text[1:-1]
if text.startswith("'"):
return text[1:-1].replace("''", "'")
return text
def _workflow_value(text):
"""A one-line scalar value without its comment and quotes; None when escaped or unterminated."""
text = text.strip()
if text.startswith('"'):
quoted = re.match(r'"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$', text)
return None if quoted is None or "\\" in quoted.group(1) else quoted.group(1)
if text.startswith("'"):
quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text)
return None if quoted is None else quoted.group(1).replace("''", "'")
return re.split(r"\s+#", text, maxsplit=1)[0].strip()
def _strip_comment(text):
"""(text without its comment, unterminated) using a quote-aware scan.
As in YAML, a quote opens a quoted scalar only where a scalar starts (line start or after
`:`, `-`, `,`, `{` or `[`), and a `#` starts a comment only outside quotes, at the start or
after whitespace.
"""
quote, index = None, 0
while index < len(text):
char = text[index]
if quote == '"':
if char == "\\":
index += 2
continue
if char == '"':
quote = None
elif quote == "'":
if char == "'":
if text[index + 1:index + 2] == "'":
index += 2
continue
quote = None
elif char in "\"'" and text[:index].rstrip()[-1:] in ("", ":", "-", ",", "{", "["):
quote = char
elif char == "#" and (index == 0 or text[index - 1] in " \t"):
return text[:index].rstrip(), False
index += 1
return text.rstrip(), quote is not None
FLOW_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'")
FLOW_FORBIDDEN_KEYS = {"environment", "uses"}
def workflow_entries(source):
"""Every mapping entry in a workflow, plus the YAML forms this reader refuses.
A narrow reader, not a YAML parser (none ships with the runner's Python). Each entry is
(line, key, value, multiline): plain, single- and double-quoted keys and one-line values in
block and simple one-line flow mappings. Block scalar bodies are skipped, and an entry whose
value is a block scalar or continues on the next lines is marked multiline. It refuses whatever
could hide a key from it: escaped double-quoted keys, explicit `?` keys, merge keys, anchors,
aliases, tags, tab indentation and nested or multi-line flow.
"""
lines = source.splitlines()
entries, refused, block = [], [], None
def continues(index, indent):
for follow in lines[index + 1:]:
stripped = follow.strip()
if not stripped or stripped.startswith("#"):
continue
deeper = len(follow) - len(follow.lstrip(" ")) > indent
return deeper and not stripped.startswith("- ") and WORKFLOW_KEY.match(stripped) is None
return False
for index, raw in enumerate(lines):
number = index + 1
stripped = raw.strip()
indent = len(raw) - len(raw.lstrip(" "))
if block is not None:
if not stripped or indent > block:
continue
block = None
if not stripped or stripped.startswith("#"):
continue
if "\t" in raw[:indent + 1]:
refused.append(f"line {number}: tab indentation"); continue
body, unterminated = _strip_comment(stripped)
if unterminated:
refused.append(f"line {number}: unterminated or multi-line quoted scalar"); continue
if not body:
continue
while body.startswith("- "):
body = body[2:].lstrip()
if body == "?" or body.startswith("? "):
refused.append(f"line {number}: explicit key"); continue
match = WORKFLOW_KEY.match(body)
value = body
if match is not None:
key, value = _workflow_key(match.group(1)), match.group(2) or ""
if key is None:
refused.append(f"line {number}: escaped double-quoted key"); continue
if key == "<<":
refused.append(f"line {number}: merge key"); continue
plain = re.sub(r"\$\{\{.*?\}\}", "", value).strip()
bare = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'", "''", plain)
if re.match(r"[&*!]", plain):
refused.append(f"line {number}: anchor, alias or tag")
is_block = re.fullmatch(r"[|>][0-9+-]*", plain) is not None
if match is not None:
entries.append((number, key, _workflow_value(value),
is_block or ((value == "" or not is_block) and continues(index, indent))))
if "{" in bare and bare != "{}":
masked = re.fullmatch(r"\{([^{}\[\]]*)\}", FLOW_QUOTED.sub("''", value.strip()))
flow = re.fullmatch(r"\{([^{}\[\]]*)\}", value.strip())
if any(set(scalar[1:-1]) & set("#{}[],") for scalar in FLOW_QUOTED.findall(value)):
refused.append(f"line {number}: flow mapping quoted scalar with # or flow punctuation")
elif masked is None or flow is None:
refused.append(f"line {number}: nested or multi-line flow mapping")
else:
# The masked text only proves the shape: a quoted key ("uses", 'environment') keeps
# its identity, so the entries are read from the original mapping text, never ''.
for item in flow.group(1).split(","):
entry = WORKFLOW_KEY.match(item.strip())
key = _workflow_key(entry.group(1)) if entry else None
if key is None:
refused.append(f"line {number}: unreadable flow mapping entry")
elif key in FLOW_FORBIDDEN_KEYS:
refused.append(f"line {number}: {key} in a flow mapping (must be block style)")
else:
entries.append((number, key, _workflow_value(entry.group(2) or ""), False))
if match is not None and is_block:
block = indent
return entries, refused
def workflow_keys(source):
"""(line, key) for every mapping entry, plus the refused YAML forms."""
entries, refused = workflow_entries(source)
return [(number, key) for number, key, _, _ in entries], refused
SHARED_CALLEE = re.compile(r"storytold/craft-common-actions/\.github/workflows/([\w.-]+\.ya?ml)@(\S+)", re.IGNORECASE)
INSPECTED_KEYS = {"environment", "uses"}
def trust_closure_problems(workflows):
"""The nightly-signer trust-closure scan over app workflow sources; empty when the tree is safe.
Every key it inspects comes from workflow_entries(), never a regex over the raw text.
"""
problems, stable_callers, signer_calls = [], set(), 0
for name, source in workflows.items():
entries, refused = workflow_entries(source)
problems.extend(name + " uses YAML the scan cannot read (" + reason + ")" for reason in refused)
for number, key, value, multiline in entries:
if key not in INSPECTED_KEYS:
continue
if key == "environment":
problems.append(f"{name} binds an environment directly (line {number})")
continue
if value is None or multiline:
problems.append(f"{name} has a uses value the scan cannot read (line {number})")
continue
callee = SHARED_CALLEE.fullmatch(value)
if callee is None:
if re.search(r"craft-common-actions", value, re.IGNORECASE) and re.search(r"workflows/(nightly-)?release\.ya?ml", value, re.IGNORECASE):
problems.append(f"{name} has an unrecognised shared release caller (line {number})")
continue
workflow, ref = callee.group(1), callee.group(2)
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
if name == "nightly-sign.yml":
signer_calls += 1
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
problems.append(name + " calls nightly-release.yml@" + ref)
if workflow.lower() in ("release.yml", "release.yaml"):
stable_callers.add(name)
if ref != "main" and not re.fullmatch(r"[0-9a-f]{40}", ref):
problems.append(name + " calls release.yml@" + ref + "; use @main or a reviewed full SHA")
if stable_callers != REVIEWED_STABLE_RELEASE_CALLERS:
problems.append("shared release.yml callers are " + ", ".join(sorted(stable_callers)))
if signer_calls != 1:
problems.append("nightly-sign.yml must call nightly-release.yml exactly once")
return problems
class NightlySignerBranchTrustClosure(unittest.TestCase):
"""On refs/heads/nightly-signer, only the pinned signer caller may reach an environment."""
def test_trust_closure_scan_passes_on_this_tree(self):
self.assertEqual(trust_closure_problems(app_workflows()), [])
def test_trust_closure_scan_refuses_each_route_into_an_environment(self):
tree = app_workflows()
bad = {
"a workflow binds an environment": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment: release\n"},
"a double-quoted environment key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environment": release\n'},
"a single-quoted environment key": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n 'environment' : release\n"},
"an environment mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment:\n name: release\n"},
"an environment in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {runs-on: ubuntu-latest, environment: release}\n"},
"an escaped key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environ\\u006dent": release\n'},
"a merge key": {**tree, "extra.yml": "base: &b\n runs-on: ubuntu-latest\njobs:\n x:\n <<: *b\n"},
"an explicit key": {**tree, "extra.yml": "jobs:\n x:\n ? environment\n : release\n"},
"a nested flow mapping": {**tree, "extra.yml": "jobs:\n x: {steps: [{run: a}]}\n"},
"a double-quoted uses key copying the signer": {**tree, "extra.yml": 'jobs:\n x:\n "uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a single-quoted uses key": {**tree, "extra.yml": "jobs:\n x:\n 'uses': " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a quoted uses value": {**tree, "extra.yml": 'jobs:\n x:\n uses: "' + SHARED + "nightly-release.yml@" + "a" * 40 + '"\n'},
"uses in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
"a differently cased owner": {**tree, "extra.yml": "jobs:\n x:\n uses: Storytold/Craft-Common-Actions/.github/workflows/nightly-release.yml@" + "a" * 40 + "\n"},
"a folded uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: >-\n " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a continued uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "\n nightly-release.yml@" + "a" * 40 + "\n"},
"a quoted second signer call": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"] + " again:\n \"uses\": " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a hash inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a} # b", runs-on: ubuntu-latest, environment: release, steps: []}\n'},
"a single-quoted hash in a flow scalar": {**tree, "extra.yml": "jobs:\n x: {name: 'a # b', runs-on: ubuntu-latest}\n"},
"a comma inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a, environment: release", runs-on: ubuntu-latest}\n'},
"a bracket inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "[a]", runs-on: ubuntu-latest}\n'},
"an unterminated quote": {**tree, "extra.yml": 'jobs:\n x:\n name: "a\n b"\n runs-on: ubuntu-latest\n'},
"environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"},
"a double-quoted environment key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n with: {"environment": release}\n'},
"a single-quoted environment key in a flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {'environment': release}\n"},
"a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
}
for label, workflows in bad.items():
with self.subTest(case=label):
self.assertTrue(trust_closure_problems(workflows))
def test_quoted_keys_in_a_flow_mapping_are_read_not_masked(self):
entries, refused = workflow_entries('jobs:\n x: {runs-on: ubuntu-latest, "name": build}\n')
self.assertEqual(refused, [])
self.assertIn((2, "name", "build", False), entries, "a quoted key keeps its identity")
self.assertIn((2, "runs-on", "ubuntu-latest", False), entries)
_, refused = workflow_entries("jobs:\n x: {runs-on: ubuntu-latest, 'environment': release}\n")
self.assertEqual(refused, ["line 2: environment in a flow mapping (must be block style)"])
def test_signer_dispatch_guard_and_policy_name_the_same_branch(self):
sign = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
(_, guard), = job_conditions(sign.split("\njobs:\n", 1)[1])
self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard)
self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch")
self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), [APP_NAME],
"the shared signer needs the reviewed registry app")
dispatch = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text()
self.assertEqual(re.findall(r"'ref': '([^']+)'", dispatch), ["refs/heads/" + SIGNER_BRANCH])
self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH)
def dispatch_triggers(source):
"""The dispatch workflow's own triggers, one per line, as a caller may register them."""
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
return [line for line in events.splitlines() if line.startswith(" ") and not line.startswith(" ")
and line.strip() and not line.lstrip().startswith("#")]
class NightlyDispatchTransport(unittest.TestCase):
"""The scheduled transport stays literally off and can only reach the signer branch."""
def setUp(self):
self.source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text()
def test_every_dispatch_job_is_literal_off(self):
jobs = self.source.split("\njobs:\n", 1)[1]
headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs)
conditions = job_conditions(jobs)
self.assertTrue(headers)
self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition")
for _, expression in conditions:
self.assertTrue(literal_off(expression), "nightly activation requires reviewed test update")
def test_only_a_completed_scheduled_producer_is_transported(self):
self.assertEqual(re.findall(r"(?m)^ workflows: (.+)$", self.source),
["[" + PRODUCER_WORKFLOW_NAME + "]"])
self.assertEqual(dispatch_triggers(self.source), [" workflow_run:"],
"the transport is not a second entry point")
self.assertNotIn("schedule:", self.source)
self.assertIn("producer.get('event') == 'schedule'", self.source)
def test_the_request_names_the_signer_workflow_and_branch(self):
self.assertIn("repos/storytold/" + APP_NAME + "/actions/workflows/nightly-sign.yml/dispatches", self.source)
self.assertNotIn("'ref': 'release'", self.source)
if __name__ == "__main__":
unittest.main(verbosity=2)